From 2ceb32e1868fa4aedcbf0c5c68adf9336738dfa5 Mon Sep 17 00:00:00 2001 From: GRZ4NA Date: Mon, 5 Jul 2021 20:42:23 +0200 Subject: [PATCH] EventEmitter, reformatting, system message disable option --- src/Bot.ts | 165 +++++++++++++++++------------ src/Command.ts | 243 ++++++++++++++++++++++++------------------- src/Help.ts | 97 +++++++++-------- src/SystemMessage.ts | 181 ++++++++++++++++++++------------ 4 files changed, 402 insertions(+), 284 deletions(-) diff --git a/src/Bot.ts b/src/Bot.ts index 5fc3efe..d476b6b 100644 --- a/src/Bot.ts +++ b/src/Bot.ts @@ -1,38 +1,40 @@ //IMPORTS -import { Client, ClientOptions, Message } from 'discord.js'; -import { Command, CommandManager, CommandMessageStructure, PermissionsError } from './Command.js'; -import { HelpMessage, HelpMessageParams } from './Help.js'; -import * as http from 'http'; -import { SystemMessageManager } from './SystemMessage.js'; +import { Client, ClientOptions, Message } from "discord.js"; +import { + Command, + CommandManager, + CommandMessageStructure, + PermissionsError, +} from "./Command.js"; +import { HelpMessage, HelpMessageParams } from "./Help.js"; +import * as http from "http"; +import { SystemMessageManager } from "./SystemMessage.js"; +import { EventEmitter } from "events"; //TYPE DEFINITIONS interface ConfigurationOptions { - token?: string, - helpCommand: boolean + token?: string; + helpCommand: boolean; } interface ConstructorOptions { - name: string, - prefix: string, - argumentSeparator?: string - helpCommand?: boolean, - clientOptions?: ClientOptions, - token?: string, + name: string; + prefix: string; + argumentSeparator?: string; + helpCommand?: boolean; + clientOptions?: ClientOptions; + token?: string; } //MAIN CLASS -class Bot { +class Bot extends EventEmitter { name: string; client: Client; commands: CommandManager; config: ConfigurationOptions; messages: { - help: HelpMessageParams, - system: SystemMessageManager - } - on: { - message: (m: Message) => any, - command: (m: Message, cmdInfo?: CommandMessageStructure) => any - } + help: HelpMessageParams; + system: SystemMessageManager; + }; /** * Bot instance initializer @@ -46,85 +48,110 @@ class Bot { * @param {string} [options.token] - bot token from Discord Developer Portal */ constructor(options: ConstructorOptions) { + super(); this.name = options.name; this.client = new Client(options.clientOptions); - this.commands = new CommandManager(options.prefix, options.argumentSeparator); + this.commands = new CommandManager( + options.prefix, + options.argumentSeparator + ); this.config = { token: options.token, - helpCommand: options.helpCommand != undefined ? options.helpCommand : true - } + helpCommand: + options.helpCommand != undefined ? options.helpCommand : true, + }; this.messages = { help: { - title: 'Help', - description: 'List of all available commands', - color: '#ff5500', - usage: '[command name (optional)]', - bottomText: 'List of all available commands' + title: "Help", + description: "List of all available commands", + color: "#ff5500", + usage: "[command name (optional)]", + bottomText: "List of all available commands", }, - system: new SystemMessageManager(this.name) - } - this.on = { - message: (m: Message) => {}, - command: (m: Message, cmdInfo?: CommandMessageStructure) => {} - } + system: new SystemMessageManager(this.name), + }; } - + /** * Starts your Discord bot * @param {number} [port] - if specified, the app will create a http server that will be listening on the specified port - * @param {string} [token] - app token from Discord Developer Portal + * @param {string} [token] - app token from Discord Developer Portal * @returns *Promise* */ - async start(port?: number, token?: string) : Promise { + async start(port?: number, token?: string): Promise { try { console.log(`Bot name: ${this.name}`); console.log(`Prefix: ${this.commands.prefix} \n`); - const loginToken: string = token || this.config.token || ''; - if(loginToken === '') { - throw new ReferenceError('No token specified. Please pass your Discord application token as an argument to the "start" method or in the constructor'); + const loginToken: string = token || this.config.token || ""; + if (loginToken === "") { + throw new ReferenceError( + 'No token specified. Please pass your Discord application token as an argument to the "start" method or in the constructor' + ); } - if(port) { + if (port) { console.log(`Creating http server on port ${port}...`); http.createServer().listen(port); } - console.log('Starting modules...'); - if(this.config.helpCommand) { - const helpMsg: Command = new HelpMessage(this.commands, this.messages.help, this.name); + console.log("Starting modules..."); + if (this.config.helpCommand) { + const helpMsg: Command = new HelpMessage( + this.commands, + this.messages.help, + this.name + ); this.commands.add(helpMsg); } - console.log('Connecting to Discord...'); - if(await this.client.login(loginToken)) { - console.log('BOT IS READY!\n'); - this.client.on('message', async m => { - this.on.message(m); - const cmdMsg: CommandMessageStructure | null = this.commands.fetch(m); - if(cmdMsg?.command) { - this.on.command(m, cmdMsg); + console.log("Connecting to Discord..."); + if (await this.client.login(loginToken)) { + this.client.on("ready", () => { + this.emit("ready"); + }); + this.client.on("message", async (m) => { + const cmdMsg: CommandMessageStructure | null = + this.commands.fetch(m); + if (cmdMsg?.command) { + this.emit("command", [m, cmdMsg]); try { - await cmdMsg.command.start(m, cmdMsg.arguments); - } - catch (e) { - if(e instanceof PermissionsError) { - this.messages.system.send('PERMISSION', { user: m.member || undefined, command: cmdMsg.command }, m.channel); - } - else { - this.messages.system.send('ERROR', { command: cmdMsg.command, user: m.member || undefined, error: e }, m.channel); + await cmdMsg.command.start(m, cmdMsg.arguments); + } catch (e) { + if (e instanceof PermissionsError) { + this.messages.system.send( + "PERMISSION", + { + user: m.member || undefined, + command: cmdMsg.command, + }, + m.channel + ); + } else { + this.messages.system.send( + "ERROR", + { + command: cmdMsg.command, + user: m.member || undefined, + error: e, + }, + m.channel + ); console.error(e); } return; } - } - else if(cmdMsg) { - this.messages.system.send('NOT_FOUND', { phrase: m.content, user: m.member || undefined }, m.channel); + } else if (cmdMsg) { + this.messages.system.send( + "NOT_FOUND", + { phrase: m.content, user: m.member || undefined }, + m.channel + ); + } else { + this.emit("message", [m]); } }); - } - else { + } else { return false; } return true; - } - catch (e) { + } catch (e) { console.error(`ERROR! ${e.toString()}`); return false; } @@ -133,4 +160,4 @@ class Bot { //EXPORTS export default Bot; -export { Bot, Command }; \ No newline at end of file +export { Bot, Command }; diff --git a/src/Command.ts b/src/Command.ts index bb4a1b7..6e47be1 100644 --- a/src/Command.ts +++ b/src/Command.ts @@ -1,29 +1,38 @@ //IMPORTS -import { Permissions, PermissionResolvable, Message, GuildMember, MessageEmbed } from 'discord.js'; +import { + Permissions, + PermissionResolvable, + Message, + GuildMember, + MessageEmbed, +} from "discord.js"; //TYPE DEFINITIONS interface CommandBuilder { - name: string, - aliases?: string[] | string, - keywords?: string[] | string, - description?: string, - usage?: string, - permissionCheck?: PermissionCheckTypes, - permissions?: PermissionResolvable, - visible?: boolean - function: (message?: Message, cmdArguments?: string[]) => void | string | MessageEmbed | Promise; + name: string; + aliases?: string[] | string; + keywords?: string[] | string; + description?: string; + usage?: string; + permissionCheck?: PermissionCheckTypes; + permissions?: PermissionResolvable; + visible?: boolean; + function: ( + message?: Message, + cmdArguments?: string[] + ) => void | string | MessageEmbed | Promise; } interface CommandMessageStructure { - name: string, - arguments: string[], - command: Command | null + name: string; + arguments: string[]; + command: Command | null; } interface PhraseOccurrenceData { - command: Command, - type: 'NAME' | 'ALIAS' + command: Command; + type: "NAME" | "ALIAS"; } -type GetMode = 'ALL' | 'PREFIX' | 'NO_PREFIX'; -type PermissionCheckTypes = 'ALL' | 'ANY'; +type GetMode = "ALL" | "PREFIX" | "NO_PREFIX"; +type PermissionCheckTypes = "ALL" | "ANY"; //ERROR CLASSES class PermissionsError { @@ -48,7 +57,10 @@ class Command { permissionCheck: PermissionCheckTypes; permissions: Permissions; visible: boolean; - private function: (message?: Message, cmdArguments?: string[]) => void | string | MessageEmbed | Promise; + private function: ( + message?: Message, + cmdArguments?: string[] + ) => void | string | MessageEmbed | Promise; /** * Command constructor @@ -65,12 +77,15 @@ class Command { * @param {Function} options.function - function that will trigger when the commands gets called */ constructor(options: CommandBuilder) { - this.name = options.name.split(' ').join('_'); + this.name = options.name.split(" ").join("_"); this.aliases = Command.processPhrase(options.aliases); this.keywords = Command.processPhrase(options.keywords); this.description = options.description || "No description"; this.usage = options.usage || ""; - this.permissionCheck = options.permissionCheck == 'ALL' || options.permissionCheck == 'ANY' ? options.permissionCheck : "ANY"; + this.permissionCheck = + options.permissionCheck == "ALL" || options.permissionCheck == "ANY" + ? options.permissionCheck + : "ANY"; this.permissions = new Permissions(options.permissions || 0); this.visible = options.visible != undefined ? options.visible : true; this.function = options.function; @@ -82,41 +97,42 @@ class Command { * @param {string[]} [cmdArguments] - list of processed arguments passed in a Discord message * @returns *Promise* */ - async start(message?: Message, cmdArguments?: string[]) : Promise { - const memberPermissions : Readonly = message?.member?.permissions || new Permissions(0); - if(this.permissionCheck == 'ALL' ? memberPermissions.has(this.permissions, true) : memberPermissions.any(this.permissions, true)) { + async start(message?: Message, cmdArguments?: string[]): Promise { + const memberPermissions: Readonly = + message?.member?.permissions || new Permissions(0); + if ( + this.permissionCheck == "ALL" + ? memberPermissions.has(this.permissions, true) + : memberPermissions.any(this.permissions, true) + ) { const fnResult = await this.function(message, cmdArguments); - if(typeof fnResult == 'string') { + if (typeof fnResult == "string") { await message?.reply(fnResult); - } - else if(fnResult instanceof MessageEmbed) { + } else if (fnResult instanceof MessageEmbed) { await message?.channel.send(fnResult); } - } - else { + } else { throw new PermissionsError(this, message?.member); } } - private static processPhrase(phrase?: string | string[]) : string[] { - if(Array.isArray(phrase)) { + private static processPhrase(phrase?: string | string[]): string[] { + if (Array.isArray(phrase)) { const buff = phrase.map((p) => { - return p.split(' ').join('_'); + return p.split(" ").join("_"); }); - buff.map(e => { - if(e == '' || e == ' ') { + buff.map((e) => { + if (e == "" || e == " ") { const i = buff.indexOf(e); buff.splice(i, 1); } }); return buff; - } - else if(typeof phrase == 'string' && phrase != '' && phrase != ' ') { + } else if (typeof phrase == "string" && phrase != "" && phrase != " ") { const buff = []; - buff.push(phrase.split(' ').join('_')); + buff.push(phrase.split(" ").join("_")); return buff; - } - else { + } else { return []; } } @@ -129,7 +145,7 @@ class CommandManager { constructor(prefix: string, argumentSeparator?: string) { this.list = []; this.prefix = prefix; - this.argumentSeparator = argumentSeparator || ','; + this.argumentSeparator = argumentSeparator || ","; } /** @@ -138,39 +154,39 @@ class CommandManager { * @param {GetMode} [mode='ALL'] - specifies which types of command triggers will be used to find the command [*NO_PREFIX* - only keywords; *PREFIX* - names and aliases] * @returns *Command* | *null* */ - get(phrase: string, mode?: GetMode) : Command | null { - if(!mode) mode = 'ALL'; - let command : Command | null = null; + get(phrase: string, mode?: GetMode): Command | null { + if (!mode) mode = "ALL"; + let command: Command | null = null; this.list.map((c) => { switch (mode) { - case 'PREFIX': - if(c.name == phrase) { + case "PREFIX": + if (c.name == phrase) { command = c; } - c.aliases.map(a => { - if(a == phrase) { + c.aliases.map((a) => { + if (a == phrase) { command = c; } }); break; - case 'NO_PREFIX': - c.keywords.map(k => { - if(k == phrase) { + case "NO_PREFIX": + c.keywords.map((k) => { + if (k == phrase) { command = c; } }); break; - case 'ALL': - if(c.name == phrase) { + case "ALL": + if (c.name == phrase) { command = c; } - c.aliases.map(a => { - if(a == phrase) { + c.aliases.map((a) => { + if (a == phrase) { command = c; } }); - c.keywords.map(k => { - if(k == phrase) { + c.keywords.map((k) => { + if (k == phrase) { command = c; } }); @@ -185,36 +201,43 @@ class CommandManager { * @param {Command} command - *Command* or *HelpMessage* object * @returns *boolean* */ - add(command: Command) : boolean { + add(command: Command): boolean { try { - if(!(command instanceof Command)) { - throw new TypeError('Inavlid argument type'); + if (!(command instanceof Command)) { + throw new TypeError("Inavlid argument type"); } - const nameOccurrence: PhraseOccurrenceData | null = this.findPhraseOccurrence(command.name); - if(nameOccurrence) { - throw new Error(`The name "${command.name}" has already been registered as ${nameOccurrence.type} in the "${nameOccurrence.command.name}" command.`); + const nameOccurrence: PhraseOccurrenceData | null = + this.findPhraseOccurrence(command.name); + if (nameOccurrence) { + throw new Error( + `The name "${command.name}" has already been registered as ${nameOccurrence.type} in the "${nameOccurrence.command.name}" command.` + ); } - command.aliases.map(a => { - const aliasOccurrence: PhraseOccurrenceData | null = this.findPhraseOccurrence(a); - if(aliasOccurrence) { - console.warn(`WARN! The name "${a}" is already registered as ${aliasOccurrence.type} in the "${aliasOccurrence.command.name}" command. It will be removed from the "${command.name}" command.`); + command.aliases.map((a) => { + const aliasOccurrence: PhraseOccurrenceData | null = + this.findPhraseOccurrence(a); + if (aliasOccurrence) { + console.warn( + `WARN! The name "${a}" is already registered as ${aliasOccurrence.type} in the "${aliasOccurrence.command.name}" command. It will be removed from the "${command.name}" command.` + ); const iToRemove = command.aliases.indexOf(a); command.aliases.splice(iToRemove, 1); } }); - this.list.map(c => { - command.keywords.map(k => { - if(c.keywords.indexOf(k) != -1) { - console.warn(`WARN! The name "${k}" is already a registered KEYWORD for the "${c.name}" command. It will be removed from the "${command.name}" command`); + this.list.map((c) => { + command.keywords.map((k) => { + if (c.keywords.indexOf(k) != -1) { + console.warn( + `WARN! The name "${k}" is already a registered KEYWORD for the "${c.name}" command. It will be removed from the "${command.name}" command` + ); const iToRemove = command.keywords.indexOf(k); command.keywords.splice(iToRemove, 1); } }); }); this.list.push(command); - return true; - } - catch(e) { + return true; + } catch (e) { console.error(`ERROR! ${e.toString()}`); return false; } @@ -225,66 +248,70 @@ class CommandManager { * @param {Message} message - *Message* object * @returns *CommandMessagesStructure* | *null* */ - fetch(message: Message) : CommandMessageStructure | null { - if(!message.author.bot && message.content.startsWith(this.prefix)) { - let msgContent = message.content.replace(this.prefix, ''); - const cmdName = msgContent.split(' ')[0]; - const cmd: Command | null = this.get(cmdName, 'PREFIX'); - msgContent = msgContent.replace(cmdName, ''); - let cmdArguments: string[] = msgContent.split(this.argumentSeparator); + fetch(message: Message): CommandMessageStructure | null { + if (!message.author.bot && message.content.startsWith(this.prefix)) { + let msgContent = message.content.replace(this.prefix, ""); + const cmdName = msgContent.split(" ")[0]; + const cmd: Command | null = this.get(cmdName, "PREFIX"); + msgContent = msgContent.replace(cmdName, ""); + let cmdArguments: string[] = msgContent.split( + this.argumentSeparator + ); cmdArguments = cmdArguments.map((a) => { - return a.replace(' ', ''); + return a.replace(" ", ""); }); - if((cmdArguments[0] == '' || cmdArguments[0] == ' ') && cmdArguments.length == 1) { + if ( + (cmdArguments[0] == "" || cmdArguments[0] == " ") && + cmdArguments.length == 1 + ) { cmdArguments = []; } return { name: cmdName, arguments: cmdArguments, - command: cmd - } - } - else if(!message.author.bot) { - const cmdName = message.content.split(' ')[0]; - const cmd: Command | null = this.get(cmdName, 'NO_PREFIX'); - if(cmd) { - const cmdArgumentsStr = message.content.replace(cmdName, ''); - let cmdArguments: string[] = cmdArgumentsStr.split(','); + command: cmd, + }; + } else if (!message.author.bot) { + const cmdName = message.content.split(" ")[0]; + const cmd: Command | null = this.get(cmdName, "NO_PREFIX"); + if (cmd) { + const cmdArgumentsStr = message.content.replace(cmdName, ""); + let cmdArguments: string[] = cmdArgumentsStr.split(","); cmdArguments = cmdArguments.map((a) => { - return a.replace(' ', ''); + return a.replace(" ", ""); }); - if((cmdArguments[0] == '' || cmdArguments[0] == ' ') && cmdArguments.length == 1) { + if ( + (cmdArguments[0] == "" || cmdArguments[0] == " ") && + cmdArguments.length == 1 + ) { cmdArguments = []; } return { name: cmdName, arguments: cmdArguments, - command: cmd - } - } - else { + command: cmd, + }; + } else { return null; } - } - else { + } else { return null; } } - private findPhraseOccurrence(phrase?: string) : PhraseOccurrenceData | null { + private findPhraseOccurrence(phrase?: string): PhraseOccurrenceData | null { let returnValue: PhraseOccurrenceData | null = null; - this.list.map(c => { - if(phrase == c.name) { + this.list.map((c) => { + if (phrase == c.name) { returnValue = { command: c, - type: 'NAME' - } - } - else if(c.aliases.indexOf(phrase || '') != -1) { + type: "NAME", + }; + } else if (c.aliases.indexOf(phrase || "") != -1) { returnValue = { command: c, - type: 'ALIAS' - } + type: "ALIAS", + }; } }); return returnValue; @@ -292,4 +319,4 @@ class CommandManager { } //EXPORTS -export { Command, CommandManager, CommandMessageStructure, PermissionsError } \ No newline at end of file +export { Command, CommandManager, CommandMessageStructure, PermissionsError }; diff --git a/src/Help.ts b/src/Help.ts index f847a45..a0729d2 100644 --- a/src/Help.ts +++ b/src/Help.ts @@ -1,78 +1,93 @@ -import { ColorResolvable, MessageEmbed } from 'discord.js'; -import { Command, CommandManager } from './Command.js'; +import { ColorResolvable, MessageEmbed } from "discord.js"; +import { Command, CommandManager } from "./Command.js"; interface HelpMessageParams { - title: string, - bottomText: string - color: ColorResolvable, - description: string, - usage: string + title: string; + bottomText: string; + color: ColorResolvable; + description: string; + usage: string; } class HelpMessage extends Command { - constructor(cmdManager: CommandManager, params: HelpMessageParams, botName?: string) { + constructor( + cmdManager: CommandManager, + params: HelpMessageParams, + botName?: string + ) { super({ - name: 'help', + name: "help", usage: params.usage, permissions: 0, description: params.description, function: (m, a) => { - const helpMsg = new MessageEmbed() + const helpMsg = new MessageEmbed(); helpMsg.setColor(params.color); helpMsg.setTimestamp(); - helpMsg.setFooter(botName || ''); - if(helpMsg != null) { - if(a && a[0]) { - const cmd: Command | null = cmdManager.get(a[0], 'ALL'); - if(cmd) { - helpMsg.setTitle(`${cmd.name} ${cmd.visible ? '' : '[HIDDEN]'}`); + helpMsg.setFooter(botName || ""); + if (helpMsg != null) { + if (a && a[0]) { + const cmd: Command | null = cmdManager.get(a[0], "ALL"); + if (cmd) { + helpMsg.setTitle( + `${cmd.name} ${cmd.visible ? "" : "[HIDDEN]"}` + ); helpMsg.setDescription(cmd.description); - if(cmd.usage) helpMsg.addField('Usage:', `${cmdManager.prefix}${cmd.name} ${cmd.usage}`, false); - if(cmd.permissions.toArray(false).length > 0) { - let permList: string = ''; - cmd.permissions.toArray(false).map(p => { - permList += p + '\n'; + if (cmd.usage) + helpMsg.addField( + "Usage:", + `${cmdManager.prefix}${cmd.name} ${cmd.usage}`, + false + ); + if (cmd.permissions.toArray(false).length > 0) { + let permList: string = ""; + cmd.permissions.toArray(false).map((p) => { + permList += p + "\n"; }); - helpMsg.addField('Permissions:', permList, false); + helpMsg.addField( + "Permissions:", + permList, + false + ); } - if(cmd.aliases.length > 0) { - let aList: string = ''; - cmd.aliases.map(a => { - aList += a + '\n'; + if (cmd.aliases.length > 0) { + let aList: string = ""; + cmd.aliases.map((a) => { + aList += a + "\n"; }); - helpMsg.addField('Aliases:', aList, false); + helpMsg.addField("Aliases:", aList, false); } - if(cmd.keywords.length > 0) { - let kwrdList: string = ''; - cmd.keywords.map(k => { - kwrdList += k + '\n'; + if (cmd.keywords.length > 0) { + let kwrdList: string = ""; + cmd.keywords.map((k) => { + kwrdList += k + "\n"; }); - helpMsg.addField('Keywords:', kwrdList, false); + helpMsg.addField("Keywords:", kwrdList, false); } + } else { + throw new ReferenceError( + `Command "${a[0]}" does not exist` + ); } - else { - throw new ReferenceError(`Command "${a[0]}" does not exist`); - } - } - else { + } else { helpMsg.setTitle(params.title); helpMsg.setDescription(params.bottomText); cmdManager.list.map((c) => { - if(c.visible) { + if (c.visible) { helpMsg.addField( `${cmdManager.prefix}${c.name} ${c.usage}`, c.description, false - ) + ); } }); } } return helpMsg; - } + }, }); } } -export { HelpMessage, HelpMessageParams }; \ No newline at end of file +export { HelpMessage, HelpMessageParams }; diff --git a/src/SystemMessage.ts b/src/SystemMessage.ts index 381994e..57b9806 100644 --- a/src/SystemMessage.ts +++ b/src/SystemMessage.ts @@ -1,48 +1,59 @@ -import { ColorResolvable, DMChannel, GuildMember, Message, MessageEmbed, NewsChannel, TextChannel, User } from 'discord.js'; -import { Command, PermissionsError } from './Command.js'; +import { + ColorResolvable, + DMChannel, + GuildMember, + Message, + MessageEmbed, + NewsChannel, + TextChannel, + User, +} from "discord.js"; +import { Command, PermissionsError } from "./Command.js"; -type MessageType = 'PERMISSION' | 'ERROR' | 'NOT_FOUND'; +type MessageType = "PERMISSION" | "ERROR" | "NOT_FOUND"; interface SystemMessageAppearance { - title: string, - bottomText?: string, - accentColor?: ColorResolvable, - showTimestamp?: boolean, - footer?: string + title: string; + bottomText?: string; + accentColor?: ColorResolvable; + showTimestamp?: boolean; + footer?: string; } interface SystemMessageData { - command?: Command, - phrase?: string, - user?: GuildMember | User, - error?: Error | PermissionsError | string + command?: Command; + phrase?: string; + user?: GuildMember | User; + error?: Error | PermissionsError | string; } class SystemMessageManager { + enabled: boolean; PERMISSION: SystemMessageAppearance; ERROR: SystemMessageAppearance; NOT_FOUND: SystemMessageAppearance; deleteTimeout: number; constructor(botName?: string) { + this.enabled = true; this.PERMISSION = { - title: '👮‍♂️ Insufficient permissions', + title: "👮‍♂️ Insufficient permissions", bottomText: "You don't have enough permissions to run this command", - accentColor: '#1d1dc4', + accentColor: "#1d1dc4", showTimestamp: true, - footer: botName - } + footer: botName, + }; this.ERROR = { - title: '❌ An error occurred', - bottomText: 'Something went wrong while processing your request.', - accentColor: '#ff0000', + title: "❌ An error occurred", + bottomText: "Something went wrong while processing your request.", + accentColor: "#ff0000", showTimestamp: true, - footer: botName - } + footer: botName, + }; this.NOT_FOUND = { - title: '🔍 Command not found', - accentColor: '#ff5500', + title: "🔍 Command not found", + accentColor: "#ff5500", showTimestamp: true, - footer: botName - } + footer: botName, + }; this.deleteTimeout = Infinity; } @@ -53,70 +64,108 @@ class SystemMessageManager { * @param {TextChannel | DMChannel | NewsChannel} [channel] - if specified, the generated message will be sent in this channel * @returns *Promise* */ - async send(type: MessageType, data?: SystemMessageData, channel?: TextChannel | DMChannel | NewsChannel) : Promise { - if(this[type]) { + async send( + type: MessageType, + data?: SystemMessageData, + channel?: TextChannel | DMChannel | NewsChannel + ): Promise { + if (!this.enabled) { + return; + } + if (this[type]) { const embed = new MessageEmbed(); embed.setTitle(this[type].title); - if(this[type].bottomText) embed.setDescription(this[type].bottomText); - embed.setColor(this[type].accentColor || '#000'); - if(this[type].showTimestamp) embed.setTimestamp(); - if(this[type].footer) embed.setFooter(this[type].footer); - if(data) { - switch(type) { - case 'ERROR': - if(data.command) { - embed.addField('Command name:', data.command.name, false); + if (this[type].bottomText) + embed.setDescription(this[type].bottomText); + embed.setColor(this[type].accentColor || "#000"); + if (this[type].showTimestamp) embed.setTimestamp(); + if (this[type].footer) embed.setFooter(this[type].footer); + if (data) { + switch (type) { + case "ERROR": + if (data.command) { + embed.addField( + "Command name:", + data.command.name, + false + ); } - if(data.error) { - if(data.error instanceof Error || data.error instanceof PermissionsError) { - embed.addField('Error details:', data.error.toString(), false); - } - else if(typeof data.error == 'string') { - embed.addField('Error details:', data.error, false); + if (data.error) { + if ( + data.error instanceof Error || + data.error instanceof PermissionsError + ) { + embed.addField( + "Error details:", + data.error.toString(), + false + ); + } else if (typeof data.error == "string") { + embed.addField( + "Error details:", + data.error, + false + ); } } - if(data.user) { - embed.addField('User:', data.user.toString(), false); + if (data.user) { + embed.addField( + "User:", + data.user.toString(), + false + ); } break; - case 'NOT_FOUND': - if(data.phrase) { - embed.addField('Phrase:', data.phrase, false); + case "NOT_FOUND": + if (data.phrase) { + embed.addField("Phrase:", data.phrase, false); } break; - case 'PERMISSION': - if(data.user) { - embed.addField('User:', data.user.toString(), false); + case "PERMISSION": + if (data.user) { + embed.addField( + "User:", + data.user.toString(), + false + ); } - if(data.command) { - embed.addField('Command name:', data.command.name, false); - if(data.command.permissions) { - let permList: string = ''; - data.command.permissions.toArray(false).map(p => { - permList += p + '\n'; - }); - embed.addField('Required permissions:', permList, false); + if (data.command) { + embed.addField( + "Command name:", + data.command.name, + false + ); + if (data.command.permissions) { + let permList: string = ""; + data.command.permissions + .toArray(false) + .map((p) => { + permList += p + "\n"; + }); + embed.addField( + "Required permissions:", + permList, + false + ); } } break; } } - if(channel) { + if (channel) { const message = await channel.send(embed); - if(this.deleteTimeout != Infinity && message.deletable) { + if (this.deleteTimeout != Infinity && message.deletable) { await message.delete({ timeout: this.deleteTimeout }); } return message; - } - else { + } else { return embed; } - } - else { - console.error('ERROR! System message: Incorrect parameter'); + } else { + console.error("ERROR! System message: Incorrect parameter"); return; } } } -export { MessageType, SystemMessageAppearance, SystemMessageManager }; \ No newline at end of file +export { MessageType, SystemMessageAppearance, SystemMessageManager };