aboutsummaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
authorIRONM00N <64110067+IRONM00N@users.noreply.github.com>2021-09-05 13:45:44 -0400
committerIRONM00N <64110067+IRONM00N@users.noreply.github.com>2021-09-05 13:45:44 -0400
commit81d69f983983ac71dbdbd5f13e2f2d8ddc35dced (patch)
tree6a06124a6696bb4036607d179972aa889b7b3769 /src/lib
parent93e8fce44ec1dd3294b1c785d93d3f8b00ee4cef (diff)
downloadtanzanite-81d69f983983ac71dbdbd5f13e2f2d8ddc35dced.tar.gz
tanzanite-81d69f983983ac71dbdbd5f13e2f2d8ddc35dced.tar.bz2
tanzanite-81d69f983983ac71dbdbd5f13e2f2d8ddc35dced.zip
cleaning up and some imporvements to the stats command
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/extensions/discord-akairo/BushClient.ts24
-rw-r--r--src/lib/extensions/discord-akairo/BushClientUtil.ts33
-rw-r--r--src/lib/extensions/discord-akairo/BushCommandHandler.ts3
-rw-r--r--src/lib/extensions/discord.js/BushGuild.ts2
-rw-r--r--src/lib/extensions/discord.js/BushGuildMember.ts11
-rw-r--r--src/lib/models/Guild.ts8
-rw-r--r--src/lib/models/Stat.ts58
7 files changed, 115 insertions, 24 deletions
diff --git a/src/lib/extensions/discord-akairo/BushClient.ts b/src/lib/extensions/discord-akairo/BushClient.ts
index 4cc8712..5c1cb35 100644
--- a/src/lib/extensions/discord-akairo/BushClient.ts
+++ b/src/lib/extensions/discord-akairo/BushClient.ts
@@ -29,12 +29,13 @@ import { durationTypeCaster } from '../../../arguments/duration';
import { permissionTypeCaster } from '../../../arguments/permission';
import { roleWithDurationTypeCaster } from '../../../arguments/roleWithDuation';
import { snowflakeTypeCaster } from '../../../arguments/snowflake';
-import { UpdateCacheTask } from '../../../tasks/updateCache';
+import UpdateCacheTask from '../../../tasks/updateCache';
import { ActivePunishment } from '../../models/ActivePunishment';
import { Global } from '../../models/Global';
import { Guild as GuildModel } from '../../models/Guild';
import { Level } from '../../models/Level';
import { ModLog } from '../../models/ModLog';
+import { Stat } from '../../models/Stat';
import { StickyRole } from '../../models/StickyRole';
import { AllowedMentions } from '../../utils/AllowedMentions';
import { BushCache } from '../../utils/BushCache';
@@ -137,6 +138,15 @@ export class BushClient<Ready extends boolean = boolean> extends AkairoClient<Re
public declare user: If<Ready, BushClientUser>;
public declare users: BushUserManager;
+ public customReady = false;
+ public stats: {
+ cpu: number | undefined;
+ commandsUsed: bigint;
+ } = {
+ cpu: undefined,
+ commandsUsed: 0n
+ };
+
public config: Config;
public listenerHandler: BushListenerHandler;
public inhibitorHandler: BushInhibitorHandler;
@@ -301,6 +311,7 @@ export class BushClient<Ready extends boolean = boolean> extends AkairoClient<Re
ActivePunishment.initModel(this.db);
Level.initModel(this.db);
StickyRole.initModel(this.db);
+ Stat.initModel(this.db);
await this.db.sync({ alter: true }); // Sync all tables to fix everything if updated
await this.console.success('startup', `Successfully connected to <<database>>.`, false);
} catch (e) {
@@ -312,16 +323,19 @@ export class BushClient<Ready extends boolean = boolean> extends AkairoClient<Re
}
}
- /** Starts the bot */
+ /**
+ * Starts the bot
+ */
public async start(): Promise<void> {
- const that = this;
eventsIntercept.patch(this);
- //@ts-ignore: no typings
+ //@ts-expect-error: no typings
this.intercept('ready', async (arg, done) => {
- const promises = that.guilds.cache.map((guild) => {
+ await this.guilds.fetch();
+ const promises = this.guilds.cache.map((guild) => {
return guild.members.fetch();
});
await Promise.all(promises);
+ this.customReady = true;
return done(null, `intercepted ${arg}`);
});
diff --git a/src/lib/extensions/discord-akairo/BushClientUtil.ts b/src/lib/extensions/discord-akairo/BushClientUtil.ts
index 1a13c13..3f9e0b6 100644
--- a/src/lib/extensions/discord-akairo/BushClientUtil.ts
+++ b/src/lib/extensions/discord-akairo/BushClientUtil.ts
@@ -568,16 +568,27 @@ export class BushClientUtil extends ClientUtil {
* @param content The text to post
* @returns The url of the posted text
*/
- public async haste(content: string): Promise<string> {
+ public async haste(
+ content: string,
+ substr = false
+ ): Promise<{ url?: string; error?: 'content too long' | 'substr' | 'unable to post' }> {
+ let isSubstr = false;
+ if (content.length > 400_000 && !substr) {
+ void this.handleError('haste', new Error(`content over 400,000 characters (${content.length.toLocaleString()})`));
+ return { error: 'content too long' };
+ } else {
+ content = content.substr(0, 400_000);
+ isSubstr = true;
+ }
for (const url of this.#hasteURLs) {
try {
const res: hastebinRes = await got.post(`${url}/documents`, { body: content }).json();
- return `${url}/${res.key}`;
+ return { url: `${url}/${res.key}`, error: isSubstr ? 'substr' : undefined };
} catch {
void client.console.error('haste', `Unable to upload haste to ${url}`);
}
}
- return 'Unable to post';
+ return { error: 'unable to post' };
}
/**
@@ -856,13 +867,19 @@ export class BushClientUtil extends ClientUtil {
* * Embed Description Limit = 4096 characters
* * Embed Field Limit = 1024 characters
*/
- public async codeblock(code: string, length: number, language?: CodeBlockLang): Promise<string> {
+ public async codeblock(code: string, length: number, language?: CodeBlockLang, substr = false): Promise<string> {
let hasteOut = '';
const prefix = `\`\`\`${language}\n`;
const suffix = '\n```';
language = language ?? 'txt';
- if (code.length + (prefix + suffix).length >= length)
- hasteOut = `Too large to display. Hastebin: ${await this.haste(code)}`;
+ if (code.length + (prefix + suffix).length >= length) {
+ const haste = await this.haste(code, substr);
+ hasteOut = `Too large to display. ${
+ haste.url
+ ? `Hastebin: ${haste.url}${haste.error ? `(${haste.error})` : ''}`
+ : `${this.emojis.error} Hastebin: ${haste.error}`
+ }`;
+ }
const FormattedHaste = hasteOut.length ? `\n${hasteOut}` : '';
const shortenedCode = hasteOut ? code.substring(0, length - (prefix + FormattedHaste + suffix).length) : code;
@@ -946,7 +963,7 @@ export class BushClientUtil extends ClientUtil {
input = typeof input !== 'string' ? this.inspect(input, inspectOptions ?? undefined) : input;
input = this.discord.cleanCodeBlockContent(input);
input = this.redact(input);
- return this.codeblock(input, length, language);
+ return this.codeblock(input, length, language, true);
}
public async inspectCleanRedactHaste(input: any, inspectOptions?: BushInspectOptions) {
@@ -1162,8 +1179,6 @@ export class BushClientUtil extends ClientUtil {
extraInfo?: Snowflake;
}): Promise<ActivePunishment | null> {
const expires = options.duration ? new Date(new Date().getTime() + options.duration ?? 0) : undefined;
- client.console.debug(expires, 1);
- client.console.debug(typeof expires);
const user = (await util.resolveNonCachedUser(options.user))!.id;
const guild = client.guilds.resolveId(options.guild)!;
const type = this.#findTypeEnum(options.type)!;
diff --git a/src/lib/extensions/discord-akairo/BushCommandHandler.ts b/src/lib/extensions/discord-akairo/BushCommandHandler.ts
index c533832..f8dcd93 100644
--- a/src/lib/extensions/discord-akairo/BushCommandHandler.ts
+++ b/src/lib/extensions/discord-akairo/BushCommandHandler.ts
@@ -1,6 +1,5 @@
import { Category, CommandHandler, CommandHandlerEvents, CommandHandlerOptions } from 'discord-akairo';
import { Collection, PermissionString } from 'discord.js';
-import { BushConstants } from '../../utils/BushConstants';
import { BushMessage } from '../discord.js/BushMessage';
import { BushClient } from './BushClient';
import { BushCommand } from './BushCommand';
@@ -8,8 +7,6 @@ import { BushSlashMessage } from './BushSlashMessage';
export type BushCommandHandlerOptions = CommandHandlerOptions;
-const commandHandlerEvents = BushConstants.CommandHandlerEvents;
-
export interface BushCommandHandlerEvents extends CommandHandlerEvents {
commandBlocked: [message: BushMessage, command: BushCommand, reason: string];
diff --git a/src/lib/extensions/discord.js/BushGuild.ts b/src/lib/extensions/discord.js/BushGuild.ts
index 12db49a..efecdcd 100644
--- a/src/lib/extensions/discord.js/BushGuild.ts
+++ b/src/lib/extensions/discord.js/BushGuild.ts
@@ -37,7 +37,6 @@ export class BushGuild extends Guild {
}
public async getSetting<K extends keyof GuildModel>(setting: K): Promise<GuildModel[K]> {
- // client.console.debug(`getSetting: ${setting}`);
return (
client.cache.guilds.get(this.id)?.[setting] ??
((await GuildDB.findByPk(this.id)) ?? GuildDB.build({ id: this.id }))[setting]
@@ -45,7 +44,6 @@ export class BushGuild extends Guild {
}
public async setSetting<K extends keyof GuildModel>(setting: K, value: GuildDB[K]): Promise<GuildDB> {
- // client.console.debug(`setSetting: ${setting}`);
const row = (await GuildDB.findByPk(this.id)) ?? GuildDB.build({ id: this.id });
row[setting] = value;
client.cache.guilds.set(this.id, row.toJSON() as GuildDB);
diff --git a/src/lib/extensions/discord.js/BushGuildMember.ts b/src/lib/extensions/discord.js/BushGuildMember.ts
index 2c41873..ab4eee4 100644
--- a/src/lib/extensions/discord.js/BushGuildMember.ts
+++ b/src/lib/extensions/discord.js/BushGuildMember.ts
@@ -93,8 +93,12 @@ export class BushGuildMember extends GuildMember {
: undefined;
const dmSuccess = await this.send({
content: `You have been ${punishment} in **${this.guild.name}** ${
- duration !== null || duration !== undefined ? (duration ? `for ${util.humanizeDuration(duration)}` : 'permanently') : ''
- }for **${reason ?? 'No reason provided'}**.${ending ? `\n\n${ending}` : ''}`,
+ duration !== null && duration !== undefined
+ ? duration
+ ? `for ${util.humanizeDuration(duration)} `
+ : 'permanently '
+ : ''
+ }for **${reason?.trim() ?? 'No reason provided'}**.`,
embeds: dmEmbed ? [dmEmbed] : undefined
}).catch(() => false);
return !!dmSuccess;
@@ -124,7 +128,6 @@ export class BushGuildMember extends GuildMember {
}
public async addRole(options: AddRoleOptions): Promise<AddRoleResponse> {
- client.console.debug(`addRole: ${options.role.name}`);
const ifShouldAddRole = this.#checkIfShouldAddRole(options.role);
if (ifShouldAddRole !== true) return ifShouldAddRole;
@@ -144,7 +147,6 @@ export class BushGuildMember extends GuildMember {
if (!modlog && options.addToModlog) return 'error creating modlog entry';
if (options.addToModlog || options.duration) {
- client.console.debug('got to punishment');
const punishmentEntrySuccess = await util.createPunishmentEntry({
type: 'role',
user: this,
@@ -164,7 +166,6 @@ export class BushGuildMember extends GuildMember {
}
public async removeRole(options: RemoveRoleOptions): Promise<RemoveRoleResponse> {
- client.console.debug(`removeRole: ${options.role.name}`);
const ifShouldAddRole = this.#checkIfShouldAddRole(options.role);
if (ifShouldAddRole !== true) return ifShouldAddRole;
diff --git a/src/lib/models/Guild.ts b/src/lib/models/Guild.ts
index 3dbb0ea..6933794 100644
--- a/src/lib/models/Guild.ts
+++ b/src/lib/models/Guild.ts
@@ -82,6 +82,10 @@ export const guildFeaturesObj = {
name: 'Sticky Roles',
description: 'Restores past roles to a user when they rejoin.'
},
+ reporting: {
+ name: 'Reporting',
+ description: 'Allow users to make reports.'
+ },
modsCanPunishMods: {
name: 'Mods Can Punish Mods',
description: 'Allow moderators to punish other moderators.'
@@ -96,6 +100,10 @@ export const guildLogsObj = {
moderation: {
description: 'Sends a message in this channel every time a moderation action is performed.',
configurable: false
+ },
+ report: {
+ description: 'Logs user reports.',
+ configurable: true
}
};
export type GuildLogType = keyof typeof guildLogsObj;
diff --git a/src/lib/models/Stat.ts b/src/lib/models/Stat.ts
new file mode 100644
index 0000000..9391ad4
--- /dev/null
+++ b/src/lib/models/Stat.ts
@@ -0,0 +1,58 @@
+import { DataTypes, Sequelize } from 'sequelize';
+import { BaseModel } from './BaseModel';
+import { NEVER_USED } from './__helpers';
+
+export interface StatModel {
+ environment: 'production' | 'development' | 'beta';
+ commandsUsed: bigint;
+}
+
+export interface StatModelCreationAttributes {
+ environment: 'production' | 'development' | 'beta';
+ commandsUsed: bigint;
+}
+
+export class Stat extends BaseModel<StatModel, StatModelCreationAttributes> implements StatModel {
+ /**
+ * The bot's environment.
+ */
+ public get environment(): 'production' | 'development' | 'beta' {
+ throw new Error(NEVER_USED);
+ }
+ public set environment(_: 'production' | 'development' | 'beta') {
+ throw new Error(NEVER_USED);
+ }
+
+ /**
+ * The number of commands used
+ */
+ public get commandsUsed(): bigint {
+ throw new Error(NEVER_USED);
+ }
+ public set commandsUsed(_: bigint) {
+ throw new Error(NEVER_USED);
+ }
+
+ public static initModel(sequelize: Sequelize): void {
+ Stat.init(
+ {
+ environment: {
+ type: DataTypes.STRING,
+ primaryKey: true
+ },
+ commandsUsed: {
+ type: DataTypes.TEXT,
+ allowNull: false,
+ get: function (): bigint {
+ return BigInt(this.getDataValue('commandsUsed') as unknown as string);
+ },
+ set: function (val: bigint) {
+ return this.setDataValue('commandsUsed', `${val}` as any);
+ },
+ defaultValue: '0'
+ }
+ },
+ { sequelize }
+ );
+ }
+}