From 5f4c3b10b1a4d9391a6422701b3da48bbca3a135 Mon Sep 17 00:00:00 2001 From: "Ean Milligan (Bastion)" Date: Sun, 10 Jul 2022 20:48:38 -0400 Subject: [PATCH] deno fmt this time + readme update --- README.md | 5 +- config.example.ts | 58 +-- db/initialize.ts | 38 +- db/populateDefaults.ts | 18 +- deps.ts | 45 ++- mod.ts | 831 ++++++++++++++++++++--------------------- src/constantCmds.ts | 145 ++++--- src/games.ts | 72 ++-- src/intervals.ts | 110 +++--- src/lfgHandlers.d.ts | 22 +- src/lfgHandlers.ts | 299 ++++++++------- src/mod.d.ts | 56 ++- src/timeUtils.ts | 8 +- src/utils.ts | 6 +- 14 files changed, 850 insertions(+), 863 deletions(-) diff --git a/README.md b/README.md index 8ba1137..2ae0db6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ -# GroupUp +# Group Up - An Event Scheduling Discord Bot | V0.5.6 - 2022/05/24 +[![SonarCloud](https://sonarcloud.io/images/project_badges/sonarcloud-orange.svg)](https://sonarcloud.io/summary/new_code?id=GroupUp) +[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=GroupUp&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=GroupUp) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=GroupUp&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=GroupUp) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=GroupUp&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=GroupUp) [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=GroupUp&metric=bugs)](https://sonarcloud.io/summary/new_code?id=GroupUp) [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=GroupUp&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=GroupUp) [![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=GroupUp&metric=ncloc)](https://sonarcloud.io/summary/new_code?id=GroupUp) + Group Up is a Discord bot built for scheduling events in your Guild. # Invite Link diff --git a/config.example.ts b/config.example.ts index c569891..ab5f80d 100644 --- a/config.example.ts +++ b/config.example.ts @@ -1,37 +1,37 @@ export const config = { - "name": "Group Up", // Name of the bot - "version": "0.5.6", // Version of the bot - "token": "the_bot_token", // Discord API Token for this bot - "localtoken": "local_testing_token", // Discord API Token for a secondary OPTIONAL testing bot, THIS MUST BE DIFFERENT FROM "token" - "prefix": "gu!", // Prefix for all commands - "db": { // Settings for the MySQL database, this is required for use with the API, if you do not want to set this up, you will need to rip all code relating to the DB out of the bot - "host": "", // IP address for the db, usually localhost - "localhost": "", // IP address for a secondary OPTIONAL local testing DB, usually also is localhost, but depends on your dev environment - "port": 3306, // Port for the db - "username": "", // Username for the account that will access your DB, this account will need "DB Manager" admin rights and "REFERENCES" Global Privalages - "password": "", // Password for the account, user account may need to be authenticated with the "Standard" Authentication Type if this does not work out of the box - "name": "" // Name of the database Schema to use for the bot + 'name': 'Group Up', // Name of the bot + 'version': '0.5.6', // Version of the bot + 'token': 'the_bot_token', // Discord API Token for this bot + 'localtoken': 'local_testing_token', // Discord API Token for a secondary OPTIONAL testing bot, THIS MUST BE DIFFERENT FROM "token" + 'prefix': 'gu!', // Prefix for all commands + 'db': { // Settings for the MySQL database, this is required for use with the API, if you do not want to set this up, you will need to rip all code relating to the DB out of the bot + 'host': '', // IP address for the db, usually localhost + 'localhost': '', // IP address for a secondary OPTIONAL local testing DB, usually also is localhost, but depends on your dev environment + 'port': 3306, // Port for the db + 'username': '', // Username for the account that will access your DB, this account will need "DB Manager" admin rights and "REFERENCES" Global Privalages + 'password': '', // Password for the account, user account may need to be authenticated with the "Standard" Authentication Type if this does not work out of the box + 'name': '', // Name of the database Schema to use for the bot }, - "logChannel": "the_log_channel", // Discord channel ID where the bot should put startup messages and other error messages needed - "reportChannel": "the_report_channel", // Discord channel ID where reports will be sent when using the built-in report command - "devServer": "the_dev_server", // Discord guild ID where testing of indev features/commands will be handled, used in conjuction with the DEVMODE bool in mod.ts - "owner": "the_bot_owner", // Discord user ID of the bot admin - "botLists": [ // Array of objects containing all bot lists that stats should be posted to + 'logChannel': 'the_log_channel', // Discord channel ID where the bot should put startup messages and other error messages needed + 'reportChannel': 'the_report_channel', // Discord channel ID where reports will be sent when using the built-in report command + 'devServer': 'the_dev_server', // Discord guild ID where testing of indev features/commands will be handled, used in conjuction with the DEVMODE bool in mod.ts + 'owner': 'the_bot_owner', // Discord user ID of the bot admin + 'botLists': [ // Array of objects containing all bot lists that stats should be posted to { // Bot List object, duplicate for each bot list - "name": "Bot List Name", // Name of bot list, not used - "enabled": false, // Should statistics be posted to this list? - "apiUrl": "https://example.com/api/bots/?{bot_id}/stats", // API URL, use ?{bot_id} in place of the bot id so that it can be dynamically replaced - "headers": [ // Array of headers that need to be added to the request + 'name': 'Bot List Name', // Name of bot list, not used + 'enabled': false, // Should statistics be posted to this list? + 'apiUrl': 'https://example.com/api/bots/?{bot_id}/stats', // API URL, use ?{bot_id} in place of the bot id so that it can be dynamically replaced + 'headers': [ // Array of headers that need to be added to the request { // Header Object, duplicate for every header needed - "header": "header_name", // Name of header needed, usually Authorization is needed - "value": "header_value" // Value for the header - } + 'header': 'header_name', // Name of header needed, usually Authorization is needed + 'value': 'header_value', // Value for the header + }, ], - "body": { // Data payload to send to the bot list, will be turned into a string and any ?{} will be replaced with the required value, currently only has ?{server_count} - "param_name": "?{param_value}" // Add more params as needed - } - } - ] + 'body': { // Data payload to send to the bot list, will be turned into a string and any ?{} will be replaced with the required value, currently only has ?{server_count} + 'param_name': '?{param_value}', // Add more params as needed + }, + }, + ], }; export default config; diff --git a/db/initialize.ts b/db/initialize.ts index 9eaf13a..d850fd8 100644 --- a/db/initialize.ts +++ b/db/initialize.ts @@ -3,11 +3,11 @@ import { // MySQL deps - Client -} from "../deps.ts"; + Client, +} from '../deps.ts'; -import { LOCALMODE } from "../flags.ts"; -import config from "../config.ts"; +import { LOCALMODE } from '../flags.ts'; +import config from '../config.ts'; // Log into the MySQL DB const dbClient = await new Client().connect({ @@ -17,20 +17,20 @@ const dbClient = await new Client().connect({ password: config.db.password, }); -console.log("Attempting to create DB"); +console.log('Attempting to create DB'); await dbClient.execute(`CREATE SCHEMA IF NOT EXISTS ${config.db.name};`); await dbClient.execute(`USE ${config.db.name}`); -console.log("DB created"); +console.log('DB created'); -console.log("Attempt to drop all tables"); +console.log('Attempt to drop all tables'); await dbClient.execute(`DROP PROCEDURE IF EXISTS INC_CNT;`); await dbClient.execute(`DROP TABLE IF EXISTS command_cnt;`); await dbClient.execute(`DROP TABLE IF EXISTS guild_prefix;`); await dbClient.execute(`DROP TABLE IF EXISTS guild_mod_role;`); await dbClient.execute(`DROP TABLE IF EXISTS guild_clean_channel;`); -console.log("Tables dropped"); +console.log('Tables dropped'); -console.log("Attempting to create table command_cnt"); +console.log('Attempting to create table command_cnt'); await dbClient.execute(` CREATE TABLE command_cnt ( command char(20) NOT NULL, @@ -39,9 +39,9 @@ await dbClient.execute(` UNIQUE KEY command_cnt_command_UNIQUE (command) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; `); -console.log("Table created"); +console.log('Table created'); -console.log("Attempt creating increment Stored Procedure"); +console.log('Attempt creating increment Stored Procedure'); await dbClient.execute(` CREATE PROCEDURE INC_CNT( IN cmd CHAR(20) @@ -52,9 +52,9 @@ await dbClient.execute(` UPDATE command_cnt SET count = oldcnt + 1 WHERE command = cmd; END `); -console.log("Stored Procedure created"); +console.log('Stored Procedure created'); -console.log("Attempting to create table guild_prefix"); +console.log('Attempting to create table guild_prefix'); await dbClient.execute(` CREATE TABLE guild_prefix ( guildId bigint unsigned NOT NULL, @@ -63,9 +63,9 @@ await dbClient.execute(` UNIQUE KEY guild_prefix_guildid_UNIQUE (guildid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; `); -console.log("Table created"); +console.log('Table created'); -console.log("Attempting to create table guild_mod_role"); +console.log('Attempting to create table guild_mod_role'); await dbClient.execute(` CREATE TABLE guild_mod_role ( guildId bigint unsigned NOT NULL, @@ -74,9 +74,9 @@ await dbClient.execute(` UNIQUE KEY guild_mod_role_guildid_UNIQUE (guildid) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; `); -console.log("Table created"); +console.log('Table created'); -console.log("Attempting to create table guild_clean_channel"); +console.log('Attempting to create table guild_clean_channel'); await dbClient.execute(` CREATE TABLE guild_clean_channel ( guildId bigint unsigned NOT NULL, @@ -84,7 +84,7 @@ await dbClient.execute(` PRIMARY KEY (guildid, channelId) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; `); -console.log("Table created"); +console.log('Table created'); await dbClient.close(); -console.log("Done!"); +console.log('Done!'); diff --git a/db/populateDefaults.ts b/db/populateDefaults.ts index 344683b..d80fb98 100644 --- a/db/populateDefaults.ts +++ b/db/populateDefaults.ts @@ -2,11 +2,11 @@ import { // MySQL deps - Client -} from "../deps.ts"; + Client, +} from '../deps.ts'; -import { LOCALMODE } from "../flags.ts"; -import config from "../config.ts"; +import { LOCALMODE } from '../flags.ts'; +import config from '../config.ts'; // Log into the MySQL DB const dbClient = await new Client().connect({ @@ -17,14 +17,14 @@ const dbClient = await new Client().connect({ password: config.db.password, }); -console.log("Attempting to insert default commands into command_cnt"); -const commands = ["ping", "help", "info", "version", "report", "privacy", "lfg", "prefix"]; +console.log('Attempting to insert default commands into command_cnt'); +const commands = ['ping', 'help', 'info', 'version', 'report', 'privacy', 'lfg', 'prefix']; for (let i = 0; i < commands.length; i++) { - await dbClient.execute("INSERT INTO command_cnt(command) values(?)", [commands[i]]).catch(e => { + await dbClient.execute('INSERT INTO command_cnt(command) values(?)', [commands[i]]).catch((e) => { console.log(`Failed to insert into database`, e); }); } -console.log("Insertion done"); +console.log('Insertion done'); await dbClient.close(); -console.log("Done!"); +console.log('Done!'); diff --git a/deps.ts b/deps.ts index 854f4de..65f3887 100644 --- a/deps.ts +++ b/deps.ts @@ -1,18 +1,41 @@ // All external dependancies are to be loaded here to make updating dependancy versions much easier export { - startBot, editBotStatus, editBotNickname, - Intents, DiscordActivityTypes, DiscordButtonStyles, DiscordInteractionTypes, DiscordInteractionResponseTypes, - sendMessage, sendDirectMessage, sendInteractionResponse, getMessage, deleteMessage, - getGuild, getUser, + botId, + cache, + cacheHandlers, + deleteMessage, + DiscordActivityTypes, + DiscordButtonStyles, + DiscordInteractionResponseTypes, + DiscordInteractionTypes, + editBotNickname, + editBotStatus, + getGuild, + getMessage, + getUser, hasGuildPermissions, - cache, botId, structures, cacheHandlers -} from "https://deno.land/x/discordeno@12.0.1/mod.ts"; + Intents, + sendDirectMessage, + sendInteractionResponse, + sendMessage, + startBot, + structures, +} from 'https://deno.land/x/discordeno@12.0.1/mod.ts'; export type { - DiscordenoMessage, DiscordenoMember, DiscordenoGuild, ButtonData, DebugArg, - CreateMessage, Interaction, ButtonComponent, ActionRow, Embed, EmbedField -} from "https://deno.land/x/discordeno@12.0.1/mod.ts"; + ActionRow, + ButtonComponent, + ButtonData, + CreateMessage, + DebugArg, + DiscordenoGuild, + DiscordenoMember, + DiscordenoMessage, + Embed, + EmbedField, + Interaction, +} from 'https://deno.land/x/discordeno@12.0.1/mod.ts'; -export { Client } from "https://deno.land/x/mysql@v2.10.1/mod.ts"; +export { Client } from 'https://deno.land/x/mysql@v2.10.1/mod.ts'; -export { LogTypes as LT, initLog, log } from "https://raw.githubusercontent.com/Burn-E99/Log4Deno/V1.1.0/mod.ts"; +export { initLog, log, LogTypes as LT } from 'https://raw.githubusercontent.com/Burn-E99/Log4Deno/V1.1.0/mod.ts'; diff --git a/mod.ts b/mod.ts index 0b5915c..ed6fa54 100644 --- a/mod.ts +++ b/mod.ts @@ -1,31 +1,49 @@ import { - // Discordeno deps - startBot, editBotStatus, editBotNickname, - Intents, DiscordActivityTypes, DiscordButtonStyles, DiscordInteractionTypes, - sendMessage, sendInteractionResponse, deleteMessage, getMessage, sendDirectMessage, getGuild, getUser, - hasGuildPermissions, - cache, botId, DebugArg, cacheHandlers, - DiscordenoMessage, DiscordenoGuild, - ButtonComponent, ActionRow, ButtonData, - Embed, DiscordInteractionResponseTypes, - + ActionRow, + botId, + ButtonComponent, + ButtonData, + cache, + cacheHandlers, // MySQL Driver deps Client, - + DebugArg, + deleteMessage, + DiscordActivityTypes, + DiscordButtonStyles, + DiscordenoGuild, + DiscordenoMessage, + DiscordInteractionResponseTypes, + DiscordInteractionTypes, + editBotNickname, + editBotStatus, + Embed, + getGuild, + getMessage, + getUser, + hasGuildPermissions, + initLog, + Intents, + log, // Log4Deno deps - LT, initLog, log -} from "./deps.ts"; + LT, + sendDirectMessage, + sendInteractionResponse, + sendMessage, + // Discordeno deps + startBot, +} from './deps.ts'; -import { BuildingLFG, ActiveLFG, GuildPrefixes, GuildModRoles, GuildCleanChannels } from "./src/mod.d.ts"; -import intervals from "./src/intervals.ts"; -import { LFGActivities } from "./src/games.ts"; -import { JoinLeaveType } from "./src/lfgHandlers.d.ts"; -import { handleLFGStep, handleMemberJoin, handleMemberLeave, urlToIds } from "./src/lfgHandlers.ts"; -import { constantCmds, editBtns, lfgStepQuestions } from "./src/constantCmds.ts"; -import { jsonParseBig, jsonStringifyBig } from "./src/utils.ts"; +import { ActiveLFG, BuildingLFG, GuildCleanChannels, GuildModRoles, GuildPrefixes } from './src/mod.d.ts'; +import intervals from './src/intervals.ts'; +import { LFGActivities } from './src/games.ts'; +import { JoinLeaveType } from './src/lfgHandlers.d.ts'; +import { handleLFGStep, handleMemberJoin, handleMemberLeave, urlToIds } from './src/lfgHandlers.ts'; +import { constantCmds, editBtns, lfgStepQuestions } from './src/constantCmds.ts'; +import { jsonParseBig, jsonStringifyBig } from './src/utils.ts'; -import { DEBUG, LOCALMODE } from "./flags.ts"; -import config from "./config.ts"; +import { DEBUG, LOCALMODE } from './flags.ts'; +import config from './config.ts'; // Initialize DB client const dbClient = await new Client().connect({ @@ -33,46 +51,46 @@ const dbClient = await new Client().connect({ port: config.db.port, db: config.db.name, username: config.db.username, - password: config.db.password + password: config.db.password, }); // Initialize logging client with folder to use for logs, needs --allow-write set on Deno startup -initLog("logs", DEBUG); +initLog('logs', DEBUG); log(LT.INFO, `${config.name} Starting up . . .`); // Handle idling out the active builders const activeBuilders: Array = []; setInterval(() => { - intervals.buildingTimeout(activeBuilders); + intervals.buildingTimeout(activeBuilders); }, 1000); -const activeLFGPosts: Array = jsonParseBig(localStorage.getItem("activeLFGPosts") || "[]"); +const activeLFGPosts: Array = jsonParseBig(localStorage.getItem('activeLFGPosts') || '[]'); log(LT.INFO, `Loaded ${activeLFGPosts.length} activeLFGPosts`); setInterval(() => { intervals.lfgNotifier(activeLFGPosts); }, 60000); const guildPrefixes: Map = new Map(); -const getGuildPrefixes = await dbClient.query("SELECT * FROM guild_prefix"); +const getGuildPrefixes = await dbClient.query('SELECT * FROM guild_prefix'); getGuildPrefixes.forEach((g: GuildPrefixes) => { guildPrefixes.set(g.guildId, g.prefix); }); const guildModRoles: Map = new Map(); -const getGuildModRoles = await dbClient.query("SELECT * FROM guild_mod_role"); +const getGuildModRoles = await dbClient.query('SELECT * FROM guild_mod_role'); getGuildModRoles.forEach((g: GuildModRoles) => { guildModRoles.set(g.guildId, g.roleId); }); const cleanChannels: Map> = new Map(); -const getCleanChannels = await dbClient.query("SELECT * FROM guild_clean_channel"); +const getCleanChannels = await dbClient.query('SELECT * FROM guild_clean_channel'); getCleanChannels.forEach((g: GuildCleanChannels) => { const tempArr = cleanChannels.get(g.guildId) || []; tempArr.push(g.channelId); cleanChannels.set(g.guildId, tempArr); }); -const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Start up the Discord Bot startBot({ @@ -83,26 +101,26 @@ startBot({ log(LT.INFO, `${config.name} Logged in!`); editBotStatus({ activities: [{ - name: "Booting up . . .", + name: 'Booting up . . .', type: DiscordActivityTypes.Game, - createdAt: new Date().getTime() + createdAt: new Date().getTime(), }], - status: "online" + status: 'online', }); // Interval to rotate the status text every 30 seconds to show off more commands setInterval(async () => { - log(LT.LOG, "Changing bot status"); + log(LT.LOG, 'Changing bot status'); try { - const cachedCount = await cacheHandlers.size("guilds"); + const cachedCount = await cacheHandlers.size('guilds'); // Wrapped in try-catch due to hard crash possible editBotStatus({ activities: [{ name: intervals.getRandomStatus(cachedCount), type: DiscordActivityTypes.Game, - createdAt: new Date().getTime() + createdAt: new Date().getTime(), }], - status: "online" + status: 'online', }); } catch (e) { log(LT.ERROR, `Failed to update status: ${jsonStringifyBig(e)}`); @@ -110,46 +128,45 @@ startBot({ }, 30000); // Interval to update bot list stats every 24 hours - LOCALMODE ? log(LT.INFO, "updateListStatistics not running") : setInterval(() => { - log(LT.LOG, "Updating all bot lists statistics"); + LOCALMODE ? log(LT.INFO, 'updateListStatistics not running') : setInterval(() => { + log(LT.LOG, 'Updating all bot lists statistics'); intervals.updateListStatistics(botId, cache.guilds.size); }, 86400000); // setTimeout added to make sure the startup message does not error out setTimeout(() => { LOCALMODE && editBotNickname(config.devServer, `LOCAL - ${config.name}`); - LOCALMODE ? log(LT.INFO, "updateListStatistics not running") : intervals.updateListStatistics(botId, cache.guilds.size); + LOCALMODE ? log(LT.INFO, 'updateListStatistics not running') : intervals.updateListStatistics(botId, cache.guilds.size); editBotStatus({ activities: [{ - name: "Booting Complete", + name: 'Booting Complete', type: DiscordActivityTypes.Game, - createdAt: new Date().getTime() + createdAt: new Date().getTime(), }], - status: "online" + status: 'online', }); - sendMessage(config.logChannel, `${config.name} has started, running version ${config.version}.`).catch(e => { + sendMessage(config.logChannel, `${config.name} has started, running version ${config.version}.`).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(e)}`); }); }, 1000); }, guildCreate: (guild: DiscordenoGuild) => { log(LT.LOG, `Handling joining guild ${jsonStringifyBig(guild)}`); - sendMessage(config.logChannel, `New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`).catch(e => { + sendMessage(config.logChannel, `New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(e)}`); }); }, guildDelete: async (guild: DiscordenoGuild) => { log(LT.LOG, `Handling leaving guild ${jsonStringifyBig(guild)}`); - sendMessage(config.logChannel, `I have been removed from: ${guild.name} (id: ${guild.id}).`).catch(e => { + sendMessage(config.logChannel, `I have been removed from: ${guild.name} (id: ${guild.id}).`).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(e)}`); }); try { - await dbClient.execute("DELETE FROM guild_prefix WHERE guildId = ?", [guild.id]); - await dbClient.execute("DELETE FROM guild_mod_role WHERE guildId = ?", [guild.id]); - await dbClient.execute("DELETE FROM guild_clean_channel WHERE guildId = ?", [guild.id]); - } - catch (e) { + await dbClient.execute('DELETE FROM guild_prefix WHERE guildId = ?', [guild.id]); + await dbClient.execute('DELETE FROM guild_mod_role WHERE guildId = ?', [guild.id]); + await dbClient.execute('DELETE FROM guild_clean_channel WHERE guildId = ?', [guild.id]); + } catch (e) { log(LT.WARN, `Failed to remove guild from DB: ${jsonStringifyBig(e)}`); } }, @@ -157,7 +174,7 @@ startBot({ messageCreate: async (message: DiscordenoMessage) => { // Ignore all other bots if (message.isBot) return; - + const prefix = guildPrefixes.get(message.guildId) || config.prefix; // Handle messages not starting with the prefix @@ -165,7 +182,7 @@ startBot({ // Mentions if (message.mentionedUserIds[0] === botId && (message.content.trim().startsWith(`<@${botId}>`) || message.content.trim().startsWith(`<@!${botId}>`))) { // Light telemetry to see how many times a command is being run - await dbClient.execute(`CALL INC_CNT("prefix");`).catch(e => { + await dbClient.execute(`CALL INC_CNT("prefix");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); @@ -176,29 +193,27 @@ startBot({ fields: [ { name: `My prefix in this guild is: \`${prefix}\``, - value: "Mention me with a new prefix to change it." - } - ] - }] - }).catch(e =>{ + value: 'Mention me with a new prefix to change it.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); - } - - else if (await hasGuildPermissions(message.guildId, message.authorId, ["ADMINISTRATOR"])) { - const newPrefix = message.content.replace(`<@!${botId}>`, "").replace(`<@${botId}>`, "").trim(); + } else if (await hasGuildPermissions(message.guildId, message.authorId, ['ADMINISTRATOR'])) { + const newPrefix = message.content.replace(`<@!${botId}>`, '').replace(`<@${botId}>`, '').trim(); if (newPrefix.length <= 10) { let success = true; if (guildPrefixes.has(message.guildId)) { // Execute the DB update - await dbClient.execute("UPDATE guild_prefix SET prefix = ? WHERE guildId = ?", [newPrefix, message.guildId]).catch(e => { + await dbClient.execute('UPDATE guild_prefix SET prefix = ? WHERE guildId = ?', [newPrefix, message.guildId]).catch((e) => { log(LT.ERROR, `Failed to insert into database: ${jsonStringifyBig(e)}`); success = false; }); } else { // Execute the DB insertion - await dbClient.execute("INSERT INTO guild_prefix(guildId,prefix) values(?,?)", [message.guildId, newPrefix]).catch(e => { + await dbClient.execute('INSERT INTO guild_prefix(guildId,prefix) values(?,?)', [message.guildId, newPrefix]).catch((e) => { log(LT.ERROR, `Failed to insert into database: ${jsonStringifyBig(e)}`); success = false; }); @@ -211,11 +226,11 @@ startBot({ fields: [ { name: `My prefix in this guild is now: \`${newPrefix}\``, - value: "Mention me with a new prefix to change it." - } - ] - }] - }).catch(e =>{ + value: 'Mention me with a new prefix to change it.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } else { @@ -223,12 +238,12 @@ startBot({ embeds: [{ fields: [ { - name: "Something went wrong!", - value: `My prefix is still \`${prefix}\`. Please try again, and if the problem persists, please report this to the developers using \`${prefix}report\`.` - } - ] - }] - }).catch(e =>{ + name: 'Something went wrong!', + value: `My prefix is still \`${prefix}\`. Please try again, and if the problem persists, please report this to the developers using \`${prefix}report\`.`, + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } @@ -237,12 +252,12 @@ startBot({ embeds: [{ fields: [ { - name: "Prefix too long, please set a prefix less than 10 characters long.", - value: "Mention me with a new prefix to change it." - } - ] - }] - }).catch(e =>{ + name: 'Prefix too long, please set a prefix less than 10 characters long.', + value: 'Mention me with a new prefix to change it.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } @@ -251,40 +266,40 @@ startBot({ } // Other - const activeIdx = activeBuilders.findIndex(x => (message.channelId === x.channelId && message.authorId === x.userId)); + const activeIdx = activeBuilders.findIndex((x) => (message.channelId === x.channelId && message.authorId === x.userId)); if (activeIdx > -1) { activeBuilders[activeIdx].lastTouch = new Date(); activeBuilders[activeIdx] = await handleLFGStep(activeBuilders[activeIdx], message.content); - - if (activeBuilders[activeIdx].step === "done") { + + if (activeBuilders[activeIdx].step === 'done') { if (message.member) { const memberJoined = handleMemberJoin(activeBuilders[activeIdx].lfgMsg.embeds[0].fields || [], message.member, false); - const newTimestamp = new Date(parseInt(memberJoined.embed[1].value.split("#")[1])); - const newLfgUid = ALPHABET[Math.floor(Math.random()*26)] + ALPHABET[Math.floor(Math.random()*26)]; + const newTimestamp = new Date(parseInt(memberJoined.embed[1].value.split('#')[1])); + const newLfgUid = ALPHABET[Math.floor(Math.random() * 26)] + ALPHABET[Math.floor(Math.random() * 26)]; - const tempMembers = memberJoined.embed[4].name.split(":")[1].split("/"); + const tempMembers = memberJoined.embed[4].name.split(':')[1].split('/'); const currentMembers = parseInt(tempMembers[0]); const maxMembers = parseInt(tempMembers[1]); - + if (activeBuilders[activeIdx].editing) { if (currentMembers > maxMembers) { - const currentPeople = memberJoined.embed[4].value.split("\n"); + const currentPeople = memberJoined.embed[4].value.split('\n'); const newAlts = currentPeople.splice(maxMembers); - memberJoined.embed[4].value = currentPeople.join("\n") || "None"; - memberJoined.embed[5].value = `${newAlts.join("\n")}\n${memberJoined.embed[5].value === "None" ? "" : memberJoined.embed[5].value}`; + memberJoined.embed[4].value = currentPeople.join('\n') || 'None'; + memberJoined.embed[5].value = `${newAlts.join('\n')}\n${memberJoined.embed[5].value === 'None' ? '' : memberJoined.embed[5].value}`; memberJoined.embed[4].name = `Members Joined: ${maxMembers}/${maxMembers}`; } } await activeBuilders[activeIdx].lfgMsg.edit({ - content: "", + content: '', embeds: [{ fields: memberJoined.embed, footer: { text: `Created by: ${message.member.username} | ${newLfgUid}`, }, - timestamp: newTimestamp.toISOString() + timestamp: newTimestamp.toISOString(), }], components: [ { @@ -292,31 +307,33 @@ startBot({ components: [ { type: 2, - label: "Join", - customId: "active@join_group", - style: DiscordButtonStyles.Success + label: 'Join', + customId: 'active@join_group', + style: DiscordButtonStyles.Success, }, { type: 2, - label: "Leave", - customId: "active@leave_group", - style: DiscordButtonStyles.Danger + label: 'Leave', + customId: 'active@leave_group', + style: DiscordButtonStyles.Danger, }, { type: 2, - label: "Join as Alternate", - customId: "active@alternate_group", - style: DiscordButtonStyles.Primary - } - ] - } - ] - }).catch(e =>{ + label: 'Join as Alternate', + customId: 'active@alternate_group', + style: DiscordButtonStyles.Primary, + }, + ], + }, + ], + }).catch((e) => { log(LT.WARN, `Failed to edit message | ${jsonStringifyBig(e)}`); }); if (activeBuilders[activeIdx]) { - const activeLFGIdx = activeLFGPosts.findIndex(lfg => (lfg.channelId === activeBuilders[activeIdx].channelId && lfg.messageId === activeBuilders[activeIdx].lfgMsg.id && lfg.ownerId === activeBuilders[activeIdx].userId)); + const activeLFGIdx = activeLFGPosts.findIndex( + (lfg) => (lfg.channelId === activeBuilders[activeIdx].channelId && lfg.messageId === activeBuilders[activeIdx].lfgMsg.id && lfg.ownerId === activeBuilders[activeIdx].userId), + ); if (activeLFGIdx >= 0) { activeLFGPosts[activeLFGIdx].lfgUid = newLfgUid; activeLFGPosts[activeLFGIdx].lfgTime = newTimestamp.getTime(); @@ -330,19 +347,19 @@ startBot({ lfgUid: newLfgUid, lfgTime: newTimestamp.getTime(), notified: false, - locked: false + locked: false, }); } - localStorage.setItem("activeLFGPosts", jsonStringifyBig(activeLFGPosts)); + localStorage.setItem('activeLFGPosts', jsonStringifyBig(activeLFGPosts)); } } - - await activeBuilders[activeIdx].questionMsg.delete().catch(e =>{ + + await activeBuilders[activeIdx].questionMsg.delete().catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); activeBuilders.splice(activeIdx, 1); } - await message.delete().catch(e =>{ + await message.delete().catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); return; @@ -351,7 +368,7 @@ startBot({ // Should this get cleaned up? const enabledCleanChannels = cleanChannels.get(message.guildId); if (enabledCleanChannels && enabledCleanChannels.length && enabledCleanChannels.indexOf(message.channelId) > -1) { - message.delete("Cleaning Channel").catch(e =>{ + message.delete('Cleaning Channel').catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); return; @@ -361,13 +378,13 @@ startBot({ // User is sending a command, make sure its a lfg command if its being sent in a clean channel const enabledCleanChannels = cleanChannels.get(message.guildId); if (enabledCleanChannels && enabledCleanChannels.length && enabledCleanChannels.indexOf(message.channelId) > -1 && message.content.indexOf(`${prefix}lfg`) !== 0) { - message.delete("Cleaning Channel").catch(e =>{ + message.delete('Cleaning Channel').catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); return; } } - + log(LT.LOG, `Handling message ${jsonStringifyBig(message)}`); // Split into standard command + args format @@ -378,9 +395,9 @@ startBot({ // ping // Its a ping test, what else do you want. - if (command === "ping") { + if (command === 'ping') { // Light telemetry to see how many times a command is being run - dbClient.execute(`CALL INC_CNT("ping");`).catch(e => { + dbClient.execute(`CALL INC_CNT("ping");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); @@ -388,332 +405,303 @@ startBot({ try { const m = await message.send({ embeds: [{ - title: "Ping?" - }] + title: 'Ping?', + }], }); m.edit({ embeds: [{ - title: `Pong! Latency is ${m.timestamp - message.timestamp}ms.` - }] + title: `Pong! Latency is ${m.timestamp - message.timestamp}ms.`, + }], }); } catch (e) { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); } - } - - // lfg + } // lfg // Handles all LFG commands, creating, editing, deleting - else if (command === "lfg") { + else if (command === 'lfg') { // Light telemetry to see how many times a command is being run - dbClient.execute(`CALL INC_CNT("lfg");`).catch(e => { + dbClient.execute(`CALL INC_CNT("lfg");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); - const subcmd = (args[0] || "help").toLowerCase(); - const lfgUid = (args[1] || "").toUpperCase(); + const subcmd = (args[0] || 'help').toLowerCase(); + const lfgUid = (args[1] || '').toUpperCase(); // Learn how the LFG command works - if (subcmd === "help" || subcmd === "h" || subcmd === "?") { - message.send(constantCmds.lfgHelp).catch(e => { + if (subcmd === 'help' || subcmd === 'h' || subcmd === '?') { + message.send(constantCmds.lfgHelp).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); }); - } - - // Create a new LFG - else if (subcmd === "create" || subcmd === "c") { + } // Create a new LFG + else if (subcmd === 'create' || subcmd === 'c') { try { const lfgMsg = await message.send(`Creating new LFG post for <@${message.authorId}>. Please reply with the requested information and watch as your LFG post gets created!`); - const gameButtons: Array = Object.keys(LFGActivities).map(game => { + const gameButtons: Array = Object.keys(LFGActivities).map((game) => { return { type: 2, label: game, customId: `building@set_game#${game}`, - style: DiscordButtonStyles.Primary + style: DiscordButtonStyles.Primary, }; }); const buttonComps: Array = []; - const temp: Array = []; + const temp: Array = []; gameButtons.forEach((btn, idx) => { - if (!temp[Math.floor(idx/5)]) { - temp[Math.floor(idx/5)] = [btn]; + if (!temp[Math.floor(idx / 5)]) { + temp[Math.floor(idx / 5)] = [btn]; } else { - temp[Math.floor(idx/5)].push(btn); + temp[Math.floor(idx / 5)].push(btn); } }); - temp.forEach(btns => { + temp.forEach((btns) => { if (btns.length && btns.length <= 5) { buttonComps.push({ type: 1, - components: btns + components: btns, }); } }); const question = await message.send({ content: lfgStepQuestions.set_game, - components: buttonComps + components: buttonComps, }); activeBuilders.push({ userId: message.authorId, channelId: message.channelId, - step: "set_game", + step: 'set_game', lfgMsg: lfgMsg, questionMsg: question, lastTouch: new Date(), maxIdle: 60, - editing: false + editing: false, }); - message.delete().catch(e =>{ + message.delete().catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - catch (e) { + } catch (e) { log(LT.WARN, `LFG failed at step | create | ${jsonStringifyBig(e)}`); } - } - - // Delete an existing LFG - else if (subcmd === "delete" || subcmd === "d") { + } // Delete an existing LFG + else if (subcmd === 'delete' || subcmd === 'd') { try { // User provided a Uid, use it if (lfgUid) { - const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid)); + const matches = activeLFGPosts.filter((lfg) => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid)); // Found one, delete if (matches.length) { - await deleteMessage(matches[0].channelId, matches[0].messageId, "User requested LFG to be deleted.").catch(e =>{ + await deleteMessage(matches[0].channelId, matches[0].messageId, 'User requested LFG to be deleted.').catch((e) => { log(LT.WARN, `Failed to find message to delete | ${jsonStringifyBig(e)}`); }); - const lfgIdx = activeLFGPosts.findIndex(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid)); - + const lfgIdx = activeLFGPosts.findIndex((lfg) => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid)); + activeLFGPosts.splice(lfgIdx, 1); - - localStorage.setItem("activeLFGPosts", jsonStringifyBig(activeLFGPosts)); + + localStorage.setItem('activeLFGPosts', jsonStringifyBig(activeLFGPosts)); const m = await message.send(constantCmds.lfgDelete3); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - - // Did not find one + } // Did not find one else { const m = await message.send(constantCmds.lfgDelete1); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); } - } - - // User did not provide a Uid, find it automatically + } // User did not provide a Uid, find it automatically else { - const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId)); + const matches = activeLFGPosts.filter((lfg) => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId)); // Found one, delete if (matches.length === 1) { - await deleteMessage(matches[0].channelId, matches[0].messageId, "User requested LFG to be deleted.").catch(e =>{ + await deleteMessage(matches[0].channelId, matches[0].messageId, 'User requested LFG to be deleted.').catch((e) => { log(LT.WARN, `Failed to find message to delete | ${jsonStringifyBig(e)}`); }); - const lfgIdx = activeLFGPosts.findIndex(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId)); - + const lfgIdx = activeLFGPosts.findIndex((lfg) => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId)); + activeLFGPosts.splice(lfgIdx, 1); - - localStorage.setItem("activeLFGPosts", jsonStringifyBig(activeLFGPosts)); + + localStorage.setItem('activeLFGPosts', jsonStringifyBig(activeLFGPosts)); const m = await message.send(constantCmds.lfgDelete3); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - - // Found multiple, notify user + } // Found multiple, notify user else if (matches.length) { const deleteMsg = constantCmds.lfgDelete2; const deepCloningFailedSoThisIsTheSolution = constantCmds.lfgDelete2.embeds[0].fields[0].value; - matches.forEach(mt => { - deleteMsg.embeds[0].fields[0].value += `[${mt.lfgUid}](https://discord.com/channels/${message.guildId}/${mt.channelId}/${mt.messageId})\n` + matches.forEach((mt) => { + deleteMsg.embeds[0].fields[0].value += `[${mt.lfgUid}](https://discord.com/channels/${message.guildId}/${mt.channelId}/${mt.messageId})\n`; }); - deleteMsg.embeds[0].fields[0].value += "\nThis message will self descruct in 30 seconds." + deleteMsg.embeds[0].fields[0].value += '\nThis message will self descruct in 30 seconds.'; const m = await message.send(deleteMsg); constantCmds.lfgDelete2.embeds[0].fields[0].value = deepCloningFailedSoThisIsTheSolution; - m.delete("Channel Cleanup", 30000).catch(e =>{ + m.delete('Channel Cleanup', 30000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 30000).catch(e =>{ + message.delete('Channel Cleanup', 30000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - - // Found none, notify user you cannot delete other's lfgs + } // Found none, notify user you cannot delete other's lfgs else { const m = await message.send(constantCmds.lfgDelete1); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); } - } - } - catch (e) { + } + } catch (e) { log(LT.WARN, `LFG failed at step | delete | ${jsonStringifyBig(e)}`); } - } - - // Edit an existing LFG - else if (subcmd === "edit" || subcmd === "e") { + } // Edit an existing LFG + else if (subcmd === 'edit' || subcmd === 'e') { try { // User provided a Uid, use it if (lfgUid) { - const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid)); + const matches = activeLFGPosts.filter((lfg) => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId && lfgUid === lfg.lfgUid)); // Found one, edit if (matches.length) { const lfgMessage = await (await getMessage(matches[0].channelId, matches[0].messageId)).edit({ - content: `Editing new LFG post for <@${matches[0].ownerId}>. Please reply with the requested information and watch as your LFG post gets edited!` + content: `Editing new LFG post for <@${matches[0].ownerId}>. Please reply with the requested information and watch as your LFG post gets edited!`, }); const question = await message.send({ - content: "Please select an item to edit from the buttons below:", + content: 'Please select an item to edit from the buttons below:', components: [{ type: 1, - components: editBtns - }] + components: editBtns, + }], }); activeBuilders.push({ userId: matches[0].ownerId, channelId: matches[0].channelId, - step: "edit_btn", + step: 'edit_btn', lfgMsg: lfgMessage, questionMsg: question, lastTouch: new Date(), maxIdle: 60, - editing: true + editing: true, }); - message.delete().catch(e =>{ + message.delete().catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - - // Did not find one + } // Did not find one else { const m = await message.send(constantCmds.lfgEdit1); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); } - } - - // User did not provide a Uid, find it automatically + } // User did not provide a Uid, find it automatically else { - const matches = activeLFGPosts.filter(lfg => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId)); + const matches = activeLFGPosts.filter((lfg) => (message.authorId === lfg.ownerId && message.channelId === lfg.channelId)); // Found one, edit if (matches.length === 1) { const lfgMessage = await (await getMessage(matches[0].channelId, matches[0].messageId)).edit({ - content: `Editing new LFG post for <@${matches[0].ownerId}>. Please reply with the requested information and watch as your LFG post gets edited!` + content: `Editing new LFG post for <@${matches[0].ownerId}>. Please reply with the requested information and watch as your LFG post gets edited!`, }); const question = await message.send({ - content: "Please select an item to edit from the buttons below:", + content: 'Please select an item to edit from the buttons below:', components: [{ type: 1, - components: editBtns - }] + components: editBtns, + }], }); activeBuilders.push({ userId: matches[0].ownerId, channelId: matches[0].channelId, - step: "edit_btn", + step: 'edit_btn', lfgMsg: lfgMessage, questionMsg: question, lastTouch: new Date(), maxIdle: 60, - editing: true + editing: true, }); - message.delete().catch(e =>{ + message.delete().catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - - // Found multiple, notify user + } // Found multiple, notify user else if (matches.length) { const deleteMsg = constantCmds.lfgEdit2; const deepCloningFailedSoThisIsTheSolution = constantCmds.lfgEdit2.embeds[0].fields[0].value; - matches.forEach(mt => { - deleteMsg.embeds[0].fields[0].value += `[${mt.lfgUid}](https://discord.com/channels/${message.guildId}/${mt.channelId}/${mt.messageId})\n` + matches.forEach((mt) => { + deleteMsg.embeds[0].fields[0].value += `[${mt.lfgUid}](https://discord.com/channels/${message.guildId}/${mt.channelId}/${mt.messageId})\n`; }); - deleteMsg.embeds[0].fields[0].value += "\nThis message will self descruct in 30 seconds." + deleteMsg.embeds[0].fields[0].value += '\nThis message will self descruct in 30 seconds.'; const m = await message.send(deleteMsg); constantCmds.lfgEdit2.embeds[0].fields[0].value = deepCloningFailedSoThisIsTheSolution; - m.delete("Channel Cleanup", 30000).catch(e =>{ + m.delete('Channel Cleanup', 30000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 30000).catch(e =>{ + message.delete('Channel Cleanup', 30000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - - // Found none, notify user you cannot edit other's lfgs + } // Found none, notify user you cannot edit other's lfgs else { const m = await message.send(constantCmds.lfgEdit1); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); } } - } - catch (e) { + } catch (e) { log(LT.WARN, `LFG failed at step | edit | ${jsonStringifyBig(e)}`); } - } - - // Join a LFG on behalf of a user - // gu!lfg join [url] [join/leave/alternate] [member?] - else if (subcmd === "join" || subcmd === "leave" || subcmd === "alternate") { + } // Join a LFG on behalf of a user + // gu!lfg join [url] [join/leave/alternate] [member?] + else if (subcmd === 'join' || subcmd === 'leave' || subcmd === 'alternate') { try { const action = subcmd; - const lfgIds = urlToIds(args[1] || ""); + const lfgIds = urlToIds(args[1] || ''); const memberStr = args[2] || `<@${message.authorId}>`; const member = await message.guild?.members.get(BigInt(memberStr.substr(3, memberStr.length - 4))); - + const modRole = guildModRoles.get(message.guildId) || 0n; // Join yourself (or others if you are a guild mod) to an LFG @@ -725,21 +713,21 @@ startBot({ embed: [], success: false, full: true, - justFilled: false + justFilled: false, }; let actionResp: string; switch (action) { - case "join": + case 'join': results = handleMemberJoin(embeds, member, false); - actionResp = "joined"; + actionResp = 'joined'; break; - case "leave": + case 'leave': results = handleMemberLeave(embeds, member); - actionResp = "left"; + actionResp = 'left'; break; - case "alternate": + case 'alternate': results = handleMemberJoin(embeds, member, true); - actionResp = "joined as alternate"; + actionResp = 'joined as alternate'; break; } @@ -751,80 +739,79 @@ startBot({ embeds: [{ fields: results.embed, footer: lfgMessage.embeds[0].footer, - timestamp: lfgMessage.embeds[0].timestamp + timestamp: lfgMessage.embeds[0].timestamp, }], - components: [buttonRow] + components: [buttonRow], }); if (results.justFilled) { - const thisLFGPost = activeLFGPosts.filter(lfg => (lfgMessage.id === lfg.messageId && lfgMessage.channelId === lfg.channelId))[0]; + const thisLFGPost = activeLFGPosts.filter((lfg) => (lfgMessage.id === lfg.messageId && lfgMessage.channelId === lfg.channelId))[0]; const thisLFG = (await getMessage(thisLFGPost.channelId, thisLFGPost.messageId)).embeds[0].fields || []; sendDirectMessage(thisLFGPost.ownerId, { embeds: [{ - title: `Hello ${(await getUser(thisLFGPost.ownerId)).username}! Your event in ${lfgMessage.guild?.name || (await getGuild(message.guildId, {counts:false, addToCache: false})).name} has filled up!`, + title: `Hello ${(await getUser(thisLFGPost.ownerId)).username}! Your event in ${ + lfgMessage.guild?.name || (await getGuild(message.guildId, { counts: false, addToCache: false })).name + } has filled up!`, fields: [ thisLFG[0], { - name: "Your members are:", - value: thisLFG[4].value - } - ] - }] + name: 'Your members are:', + value: thisLFG[4].value, + }, + ], + }], }); } resp = `Successfully ${actionResp} LFG.`; } else { - resp = `Failed to ${action} LFG.` + resp = `Failed to ${action} LFG.`; } const m = await message.send({ embeds: [{ - title: resp - }] + title: resp, + }], }); - m.delete("Channel Cleanup", 5000).catch(e =>{ + m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e =>{ + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); } - } - catch (e) { + } catch (e) { log(LT.WARN, `Member Join/Leave/Alt command failed: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); const m = await message.send({ embeds: [{ - title: "Failed to find LFG." - }] + title: 'Failed to find LFG.', + }], }); - m.delete("Channel Cleanup", ).catch(e => { + m.delete('Channel Cleanup').catch((e) => { log(LT.WARN, `Failed to clean up joiner | joining on behalf | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e => { + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to clean up joiner | joining on behalf | ${jsonStringifyBig(e)}`); }); } - } - - // Sets the mod role - else if (subcmd === "set_mod_role" && (await hasGuildPermissions(message.guildId, message.authorId, ["ADMINISTRATOR"]))) { - const mentionedRole = args[1] || ""; + } // Sets the mod role + else if (subcmd === 'set_mod_role' && (await hasGuildPermissions(message.guildId, message.authorId, ['ADMINISTRATOR']))) { + const mentionedRole = args[1] || ''; const roleId = BigInt(mentionedRole.substr(3, mentionedRole.length - 4)); if (message.guild?.roles.has(roleId)) { let success = true; if (guildModRoles.has(message.guildId)) { // Execute the DB update - await dbClient.execute("UPDATE guild_mod_role SET roleId = ? WHERE guildId = ?", [roleId, message.guildId]).catch(e => { + await dbClient.execute('UPDATE guild_mod_role SET roleId = ? WHERE guildId = ?', [roleId, message.guildId]).catch((e) => { log(LT.ERROR, `Failed to insert into database: ${jsonStringifyBig(e)}`); success = false; }); } else { // Execute the DB insertion - await dbClient.execute("INSERT INTO guild_mod_role(guildId,roleId) values(?,?)", [message.guildId, roleId]).catch(e => { + await dbClient.execute('INSERT INTO guild_mod_role(guildId,roleId) values(?,?)', [message.guildId, roleId]).catch((e) => { log(LT.ERROR, `Failed to insert into database: ${jsonStringifyBig(e)}`); success = false; }); @@ -836,12 +823,12 @@ startBot({ embeds: [{ fields: [ { - name: "LFG Mod Role set successfully", - value: `LFG Mod Role set to ${args[1]}.` - } - ] - }] - }).catch(e => { + name: 'LFG Mod Role set successfully', + value: `LFG Mod Role set to ${args[1]}.`, + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } else { @@ -849,12 +836,12 @@ startBot({ embeds: [{ fields: [ { - name: "Something went wrong!", - value: "LFG Mod Role has been left unchanged." - } - ] - }] - }).catch(e => { + name: 'Something went wrong!', + value: 'LFG Mod Role has been left unchanged.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } @@ -864,12 +851,12 @@ startBot({ embeds: [{ fields: [ { - name: "LFG Mod Role is currently set to:", - value: `<@&${guildModRoles.get(message.guildId)}>` - } - ] - }] - }).catch(e => { + name: 'LFG Mod Role is currently set to:', + value: `<@&${guildModRoles.get(message.guildId)}>`, + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } else { @@ -877,25 +864,23 @@ startBot({ embeds: [{ fields: [ { - name: "There is no LFG Mod Role set for this guild.", - value: `To set one, run this command again with the role mentioned.\n\nExample: \`${prefix}lfg set_mod_role @newModRole\`` - } - ] - }] - }).catch(e => { + name: 'There is no LFG Mod Role set for this guild.', + value: `To set one, run this command again with the role mentioned.\n\nExample: \`${prefix}lfg set_mod_role @newModRole\``, + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } } - } - - // Sets the channel cleaning up for LFG channels to keep LFG events visible and prevent conversations - else if (subcmd === "set_clean_channel" && (await hasGuildPermissions(message.guildId, message.authorId, ["ADMINISTRATOR"]))) { - const cleanSetting = (args[1] || "list").toLowerCase(); + } // Sets the channel cleaning up for LFG channels to keep LFG events visible and prevent conversations + else if (subcmd === 'set_clean_channel' && (await hasGuildPermissions(message.guildId, message.authorId, ['ADMINISTRATOR']))) { + const cleanSetting = (args[1] || 'list').toLowerCase(); let success = true; - if (cleanSetting === "on") { + if (cleanSetting === 'on') { // Execute the DB insertion - await dbClient.execute("INSERT INTO guild_clean_channel(guildId,channelId) values(?,?)", [message.guildId, message.channelId]).catch(e => { + await dbClient.execute('INSERT INTO guild_clean_channel(guildId,channelId) values(?,?)', [message.guildId, message.channelId]).catch((e) => { log(LT.ERROR, `Failed to insert into database: ${jsonStringifyBig(e)}`); success = false; }); @@ -909,20 +894,19 @@ startBot({ embeds: [{ fields: [ { - name: "Channel Cleaning turned ON.", - value: "This message will self destruct in 5 seconds." - } - ] - }] - }).catch(e => { + name: 'Channel Cleaning turned ON.', + value: 'This message will self destruct in 5 seconds.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); - - m && m.delete("Channel Cleanup", 5000).catch(e => { + m && m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to clean up | set_clean_channel | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e => { + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to clean up | set_clean_channel | ${jsonStringifyBig(e)}`); }); } else { @@ -930,45 +914,45 @@ startBot({ embeds: [{ fields: [ { - name: "Something went wrong!", - value: "Channel Clean status left off." - } - ] - }] - }).catch(e => { + name: 'Something went wrong!', + value: 'Channel Clean status left off.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } - } else if (cleanSetting === "off") { + } else if (cleanSetting === 'off') { // turns clean off for channel // Execute the DB insertion - await dbClient.execute("DELETE FROM guild_clean_channel WHERE guildId = ? AND channelId = ?", [message.guildId, message.channelId]).catch(e => { + await dbClient.execute('DELETE FROM guild_clean_channel WHERE guildId = ? AND channelId = ?', [message.guildId, message.channelId]).catch((e) => { log(LT.ERROR, `Failed to delete from database: ${jsonStringifyBig(e)}`); success = false; }); if (success) { let tempArr = cleanChannels.get(message.guildId) || []; - tempArr = tempArr.filter(channelId => channelId !== message.channelId); + tempArr = tempArr.filter((channelId) => channelId !== message.channelId); cleanChannels.set(message.guildId, tempArr); const m = await message.send({ embeds: [{ fields: [ { - name: "Channel Cleaning turned OFF.", - value: "This message will self destruct in 5 seconds." - } - ] - }] - }).catch(e => { + name: 'Channel Cleaning turned OFF.', + value: 'This message will self destruct in 5 seconds.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); - m && m.delete("Channel Cleanup", 5000).catch(e => { + m && m.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to clean up | set_clean_channel | ${jsonStringifyBig(e)}`); }); - message.delete("Channel Cleanup", 5000).catch(e => { + message.delete('Channel Cleanup', 5000).catch((e) => { log(LT.WARN, `Failed to clean up | set_clean_channel | ${jsonStringifyBig(e)}`); }); } else { @@ -976,18 +960,18 @@ startBot({ embeds: [{ fields: [ { - name: "Something went wrong!", - value: "Channel Clean status left on." - } - ] - }] - }).catch(e => { + name: 'Something went wrong!', + value: 'Channel Clean status left on.', + }, + ], + }], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } - } else if (cleanSetting === "list") { + } else if (cleanSetting === 'list') { // send list of channels with clean on - let cleanChannelStr = ""; + let cleanChannelStr = ''; for (const channelId of cleanChannels.get(message.guildId) || []) { cleanChannelStr += `<#${channelId}>\n`; @@ -999,74 +983,66 @@ startBot({ if (cleanChannelStr) { tmpEmbed.fields = [ { - name: "Clean Channels enabled for this guild:", - value: cleanChannelStr - } - ] + name: 'Clean Channels enabled for this guild:', + value: cleanChannelStr, + }, + ]; } else { - tmpEmbed.title = "No Clean Channels are enabled for this guild." + tmpEmbed.title = 'No Clean Channels are enabled for this guild.'; } await message.send({ - embeds: [tmpEmbed] - }).catch(e => { + embeds: [tmpEmbed], + }).catch((e) => { log(LT.WARN, `Failed to send message | ${jsonStringifyBig(e)}`); }); } } - } - - // report or r (command that failed) + } // report or r (command that failed) // Manually report something that screwed up - else if (command === "report" || command === "r") { + else if (command === 'report' || command === 'r') { // Light telemetry to see how many times a command is being run - dbClient.execute(`CALL INC_CNT("report");`).catch(e => { + dbClient.execute(`CALL INC_CNT("report");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); - sendMessage(config.reportChannel, ("USER REPORT:\n" + args.join(" "))).catch(e => { + sendMessage(config.reportChannel, 'USER REPORT:\n' + args.join(' ')).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); }); - message.send(constantCmds.report).catch(e => { + message.send(constantCmds.report).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); }); - } - - // version or v + } // version or v // Returns version of the bot - else if (command === "version" || command === "v") { + else if (command === 'version' || command === 'v') { // Light telemetry to see how many times a command is being run - dbClient.execute(`CALL INC_CNT("version");`).catch(e => { + dbClient.execute(`CALL INC_CNT("version");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); - message.send(constantCmds.version).catch(e => { + message.send(constantCmds.version).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); }); - } - - // info or i + } // info or i // Info command, prints short desc on bot and some links - else if (command === "info" || command === "i") { + else if (command === 'info' || command === 'i') { // Light telemetry to see how many times a command is being run - dbClient.execute(`CALL INC_CNT("info");`).catch(e => { + dbClient.execute(`CALL INC_CNT("info");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); - message.send(constantCmds.info).catch(e => { + message.send(constantCmds.info).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); }); - } - - // help or h or ? + } // help or h or ? // Help command, prints available commands - else if (command === "help" || command === "h" || command === "?") { + else if (command === 'help' || command === 'h' || command === '?') { // Light telemetry to see how many times a command is being run - dbClient.execute(`CALL INC_CNT("help");`).catch(e => { + dbClient.execute(`CALL INC_CNT("help");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${jsonStringifyBig(e)}`); }); - message.send(constantCmds.help).catch(e => { + message.send(constantCmds.help).catch((e) => { log(LT.ERROR, `Failed to send message: ${jsonStringifyBig(message)} | ${jsonStringifyBig(e)}`); }); } @@ -1079,55 +1055,55 @@ startBot({ log(LT.LOG, `Button Data | ${jsonStringifyBig(interact)}`); sendInteractionResponse(BigInt(interact.id), interact.token, { - type: DiscordInteractionResponseTypes.DeferredUpdateMessage + type: DiscordInteractionResponseTypes.DeferredUpdateMessage, }); - const [handler, stepInfo] = (interact.data as ButtonData).customId.split("@"); - const [action, value] = stepInfo.split("#"); + const [handler, stepInfo] = (interact.data as ButtonData).customId.split('@'); + const [action, value] = stepInfo.split('#'); switch (handler) { - case "building": { + case 'building': { await activeBuilders.some(async (x, i) => { - if (x.channelId === BigInt(interact.channelId || "0") && member && x.userId === BigInt(member.id)) { + if (x.channelId === BigInt(interact.channelId || '0') && member && x.userId === BigInt(member.id)) { x.lastTouch = new Date(); x = await handleLFGStep(x, value); - if (x.step === "done" && x.lfgMsg.components) { + if (x.step === 'done' && x.lfgMsg.components) { const currentLFG = (x.lfgMsg.embeds[0].fields || []); - const newTimestamp = new Date(parseInt(currentLFG[1].value.split("#")[1])); - const newLfgUid = ALPHABET[Math.floor(Math.random()*26)] + ALPHABET[Math.floor(Math.random()*26)]; + const newTimestamp = new Date(parseInt(currentLFG[1].value.split('#')[1])); + const newLfgUid = ALPHABET[Math.floor(Math.random() * 26)] + ALPHABET[Math.floor(Math.random() * 26)]; - const tempMembers = currentLFG[4].name.split(":")[1].split("/"); + const tempMembers = currentLFG[4].name.split(':')[1].split('/'); const currentMembers = parseInt(tempMembers[0]); const maxMembers = parseInt(tempMembers[1]); const buttonRow: ActionRow = x.lfgMsg.components[0] as ActionRow; if (currentMembers > maxMembers) { - const currentPeople = currentLFG[4].value.split("\n"); + const currentPeople = currentLFG[4].value.split('\n'); const newAlts = currentPeople.splice(maxMembers - 1); - currentLFG[4].value = currentPeople.join("\n"); - currentLFG[5].value = `${newAlts.join("\n")}\n${currentLFG[5].value}`; + currentLFG[4].value = currentPeople.join('\n'); + currentLFG[5].value = `${newAlts.join('\n')}\n${currentLFG[5].value}`; currentLFG[4].name = `Members Joined: ${maxMembers}/${maxMembers}`; } await x.lfgMsg.edit({ - content: "", + content: '', embeds: [{ fields: currentLFG, footer: { text: `Created by: ${member.username} | ${newLfgUid}`, }, - timestamp: newTimestamp.toISOString() + timestamp: newTimestamp.toISOString(), }], - components: [buttonRow] + components: [buttonRow], }); - const activeIdx = activeLFGPosts.findIndex(lfg => (lfg.channelId === x.channelId && lfg.messageId === x.lfgMsg.id && lfg.ownerId === x.userId)); + const activeIdx = activeLFGPosts.findIndex((lfg) => (lfg.channelId === x.channelId && lfg.messageId === x.lfgMsg.id && lfg.ownerId === x.userId)); activeLFGPosts[activeIdx].lfgTime = newTimestamp.getTime(); activeLFGPosts[activeIdx].lfgUid = newLfgUid; - localStorage.setItem("activeLFGPosts", jsonStringifyBig(activeLFGPosts)); + localStorage.setItem('activeLFGPosts', jsonStringifyBig(activeLFGPosts)); - await activeBuilders[i].questionMsg.delete().catch(e =>{ + await activeBuilders[i].questionMsg.delete().catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); activeBuilders.splice(i, 1); @@ -1140,24 +1116,24 @@ startBot({ }); break; } - case "active": { - const message = await getMessage(BigInt(interact.channelId || "0"), BigInt(interact.message.id)); + case 'active': { + const message = await getMessage(BigInt(interact.channelId || '0'), BigInt(interact.message.id)); const embeds = message.embeds[0].fields || []; let results: JoinLeaveType = { embed: [], success: false, full: true, - justFilled: false + justFilled: false, }; switch (action) { - case "join_group": + case 'join_group': results = handleMemberJoin(embeds, member, false); break; - case "leave_group": + case 'leave_group': results = handleMemberLeave(embeds, member); break; - case "alternate_group": + case 'alternate_group': results = handleMemberJoin(embeds, member, true); break; } @@ -1167,76 +1143,78 @@ startBot({ embeds: [{ fields: results.embed, footer: message.embeds[0].footer, - timestamp: message.embeds[0].timestamp + timestamp: message.embeds[0].timestamp, }], }); if (results.justFilled) { - const thisLFGPost = activeLFGPosts.filter(lfg => (message.id === lfg.messageId && message.channelId === lfg.channelId))[0]; + const thisLFGPost = activeLFGPosts.filter((lfg) => (message.id === lfg.messageId && message.channelId === lfg.channelId))[0]; const thisLFG = (await getMessage(thisLFGPost.channelId, thisLFGPost.messageId)).embeds[0].fields || []; sendDirectMessage(thisLFGPost.ownerId, { embeds: [{ - title: `Hello ${(await getUser(thisLFGPost.ownerId)).username}! Your event in ${message.guild?.name || (await getGuild(message.guildId, {counts:false, addToCache: false})).name} has filled up!`, + title: `Hello ${(await getUser(thisLFGPost.ownerId)).username}! Your event in ${ + message.guild?.name || (await getGuild(message.guildId, { counts: false, addToCache: false })).name + } has filled up!`, fields: [ thisLFG[0], { - name: "Your members are:", - value: thisLFG[4].value - } - ] - }] + name: 'Your members are:', + value: thisLFG[4].value, + }, + ], + }], }); } } break; } - case "editing": { + case 'editing': { await activeBuilders.some(async (x, i) => { - if (x.editing && x.channelId === BigInt(interact.channelId || "0") && member && x.userId === BigInt(member.id)) { + if (x.editing && x.channelId === BigInt(interact.channelId || '0') && member && x.userId === BigInt(member.id)) { x.step = action; x.lastTouch = new Date(); - let nextQuestion = ""; + let nextQuestion = ''; const nextComponents: Array = []; switch (action) { - case "set_game": { + case 'set_game': { nextQuestion = lfgStepQuestions.set_game; - const gameButtons: Array = Object.keys(LFGActivities).map(game => { + const gameButtons: Array = Object.keys(LFGActivities).map((game) => { return { type: 2, label: game, customId: `building@set_game#${game}`, - style: DiscordButtonStyles.Primary + style: DiscordButtonStyles.Primary, }; }); - const temp: Array = []; + const temp: Array = []; gameButtons.forEach((btn, idx) => { - if (!temp[Math.floor(idx/5)]) { - temp[Math.floor(idx/5)] = [btn]; + if (!temp[Math.floor(idx / 5)]) { + temp[Math.floor(idx / 5)] = [btn]; } else { - temp[Math.floor(idx/5)].push(btn); + temp[Math.floor(idx / 5)].push(btn); } }); - temp.forEach(btns => { + temp.forEach((btns) => { if (btns.length && btns.length <= 5) { nextComponents.push({ type: 1, - components: btns + components: btns, }); } }); break; } - case "set_time": { - nextQuestion = "Please enter the time of the activity:"; + case 'set_time': { + nextQuestion = 'Please enter the time of the activity:'; break; } - case "set_desc": { - nextQuestion = "Please enter a description for the activity. Enter `none` to skip:"; + case 'set_desc': { + nextQuestion = 'Please enter a description for the activity. Enter `none` to skip:'; break; } default: @@ -1245,7 +1223,7 @@ startBot({ x.questionMsg = await x.questionMsg.edit({ content: nextQuestion, - components: nextComponents + components: nextComponents, }); activeBuilders[i] = x; @@ -1260,10 +1238,9 @@ startBot({ } } } - } - catch(e) { + } catch (e) { log(LT.ERROR, `Interaction failed: ${jsonStringifyBig(interact)} | ${jsonStringifyBig(member)} | ${jsonStringifyBig(e)}`); } - } - } + }, + }, }); diff --git a/src/constantCmds.ts b/src/constantCmds.ts index e4dd96b..bf2a751 100644 --- a/src/constantCmds.ts +++ b/src/constantCmds.ts @@ -1,8 +1,6 @@ -import { - DiscordButtonStyles, ActionRow -} from "../deps.ts"; +import { ActionRow, DiscordButtonStyles } from '../deps.ts'; -import config from "../config.ts"; +import config from '../config.ts'; export const constantCmds = { help: { @@ -10,49 +8,49 @@ export const constantCmds = { title: `${config.name} Help`, fields: [ { - name: "All commands must have the bot's prefix before them.", - value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.` + name: 'All commands must have the bot\'s prefix before them.', + value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.`, }, { - name: "LFG Commands", + name: 'LFG Commands', value: ` \`lfg help\` - More detailed help for the LFG commands \`lfg create\` - Create a new LFG post \`lfg edit\` - Edit an existing LFG post \`lfg delete\` - Delete an existing LFG post - ` + `, }, { - name: "Utility Commands", + name: 'Utility Commands', value: ` \`info\` - Information about the bot \`ping\` - Pings the bot to check its connection \`report [TEXT]\` - Report an issue to the developer \`version\` - Prints the bot's current version - ` - } - ] - }] + `, + }, + ], + }], }, lfgHelp: { embeds: [{ title: `${config.name} LFG Help`, fields: [ { - name: "All commands must have the bot's prefix before them.", - value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.` + name: 'All commands must have the bot\'s prefix before them.', + value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.`, }, { - name: "lfg create", + name: 'lfg create', value: ` \`lfg create\`, alternatively \`lfg c\`, will walk you through creating a new LFG post. Simply follow the prompts and the bot will walk you through building a new LFG. Make sure you run this command in the channel you wish the LFG post to be created in. `, - inline: true + inline: true, }, { - name: "lfg edit", + name: 'lfg edit', value: ` \`lfg edit [id?]\`, alternatively \`lfg e [id?]\`, will walk you through editing an existing LFG. Like \`lfg create\`, the bot will walk you through editing it. @@ -60,10 +58,10 @@ export const constantCmds = { If you only have one LFG in this channel, the editing process will begin. If you have more than one LFG in this channel, the bot will ask you to specify the LFG post using a two character id. `, - inline: true + inline: true, }, { - name: "lfg delete", + name: 'lfg delete', value: ` \`lfg delete [id?]\`, alternatively \`lfg d [id?]\`, will delete an existing LFG. You only can delete LFG posts that you own. @@ -71,113 +69,114 @@ export const constantCmds = { If you only have one LFG in this channel, the LFG will be deleted. If you have more than one LFG in this channel, the bot will ask you to specify the LFG post using a two character id. `, - inline: true - } - ] - }] + inline: true, + }, + ], + }], }, info: { embeds: [{ fields: [ { - name: "Group Up, the LFG bot", + name: 'Group Up, the LFG bot', value: `Group Up is developed by Ean AKA Burn_E99. Want to check out my source code? Check it out [here](https://github.com/Burn-E99/GroupUp). - Need help with this bot? Join my support server [here](https://discord.gg/peHASXMZYv).` - } - ] - }] + Need help with this bot? Join my support server [here](https://discord.gg/peHASXMZYv).`, + }, + ], + }], }, version: { embeds: [{ - title: `My current version is ${config.version}` - }] + title: `My current version is ${config.version}`, + }], }, report: { embeds: [{ fields: [ { - name: "Failed command has been reported to my developer.", - value: "For more in depth support, and information about planned maintenance, please join the support server [here](https://discord.gg/peHASXMZYv)." - } - ] - }] + name: 'Failed command has been reported to my developer.', + value: 'For more in depth support, and information about planned maintenance, please join the support server [here](https://discord.gg/peHASXMZYv).', + }, + ], + }], }, lfgDelete1: { embeds: [{ fields: [ { - name: "Could not find any LFGs to delete.", - value: "Make sure you are the owner of the LFG and are running this command in the same channel as the LFG" - } - ] - }] + name: 'Could not find any LFGs to delete.', + value: 'Make sure you are the owner of the LFG and are running this command in the same channel as the LFG', + }, + ], + }], }, lfgDelete2: { embeds: [{ fields: [ { name: `Multiple LFGs found, please run this command again with the two character ID of the LFG you wish to delete.\n\nExample: \`${config.prefix}lfg delete XX\``, - value: "Click on the two character IDs below to view the LFG:\n" - } - ] - }] + value: 'Click on the two character IDs below to view the LFG:\n', + }, + ], + }], }, lfgDelete3: { embeds: [{ - title: "LFG deleted." - }] + title: 'LFG deleted.', + }], }, lfgEdit1: { embeds: [{ fields: [ { - name: "Could not find any LFGs to edit.", - value: "Make sure you are the owner of the LFG and are running this command in the same channel as the LFG" - } - ] - }] + name: 'Could not find any LFGs to edit.', + value: 'Make sure you are the owner of the LFG and are running this command in the same channel as the LFG', + }, + ], + }], }, lfgEdit2: { embeds: [{ fields: [ { name: `Multiple LFGs found, please run this command again with the two character ID of the LFG you wish to edit.\n\nExample: \`${config.prefix}lfg edit XX\``, - value: "Click on the two character IDs below to view the LFG:\n" - } - ] - }] - } + value: 'Click on the two character IDs below to view the LFG:\n', + }, + ], + }], + }, }; -export const editBtns: ActionRow["components"] = [ +export const editBtns: ActionRow['components'] = [ { type: 2, - label: "Change Game/Activity", + label: 'Change Game/Activity', customId: `editing@set_game`, - style: DiscordButtonStyles.Primary + style: DiscordButtonStyles.Primary, }, { type: 2, - label: "Change Time", + label: 'Change Time', customId: `editing@set_time`, - style: DiscordButtonStyles.Primary + style: DiscordButtonStyles.Primary, }, { type: 2, - label: "Change Description", + label: 'Change Description', customId: `editing@set_desc`, - style: DiscordButtonStyles.Primary - } + style: DiscordButtonStyles.Primary, + }, ]; export const lfgStepQuestions = { - "set_game": "Please select a game from the list below. If your game is not listed, please type it out:", - "set_activity_with_button": "Please select an Activity from the list below. Depending on the game selected, these may be categories you can use to drill down to a specific activity.\n\nIf your activity is not listed, please type it out:", - "set_activity_with_text": "Please type the activity name out:", - "set_activity_from_category": "Please select an Activity from the list below.\n\nIf your activity is not listed, please type it out:", - "set_player_cnt": "Please enter the max number of members for this activity:", - "set_time": "Please enter the time of the activity:\nRecommended format: `h:mm am/pm tz month/day`", - "set_desc": "Please enter a description for the activity. Enter `none` to skip:", - "set_done": "Finalizing, please wait. . ." + 'set_game': 'Please select a game from the list below. If your game is not listed, please type it out:', + 'set_activity_with_button': + 'Please select an Activity from the list below. Depending on the game selected, these may be categories you can use to drill down to a specific activity.\n\nIf your activity is not listed, please type it out:', + 'set_activity_with_text': 'Please type the activity name out:', + 'set_activity_from_category': 'Please select an Activity from the list below.\n\nIf your activity is not listed, please type it out:', + 'set_player_cnt': 'Please enter the max number of members for this activity:', + 'set_time': 'Please enter the time of the activity:\nRecommended format: `h:mm am/pm tz month/day`', + 'set_desc': 'Please enter a description for the activity. Enter `none` to skip:', + 'set_done': 'Finalizing, please wait. . .', }; diff --git a/src/games.ts b/src/games.ts index f86e71a..e724272 100644 --- a/src/games.ts +++ b/src/games.ts @@ -1,53 +1,53 @@ export const LFGActivities = { - "Destiny 2": { - "Raids": { - "Vow of the Disciple": 6, - "Vault of Glass": 6, - "Deep Stone Crypt": 6, - "Garden of Salvation": 6, - "Last Wish": 6 + 'Destiny 2': { + 'Raids': { + 'Vow of the Disciple': 6, + 'Vault of Glass': 6, + 'Deep Stone Crypt': 6, + 'Garden of Salvation': 6, + 'Last Wish': 6, }, - "Dungeons": { - "Duality": 3, - "Grasp of Avarice": 3, - "Prophecy": 3, - "Pit of Heresy": 3, - "Shattered Throne": 3 + 'Dungeons': { + 'Duality': 3, + 'Grasp of Avarice': 3, + 'Prophecy': 3, + 'Pit of Heresy': 3, + 'Shattered Throne': 3, }, - "Crucible": { - "Crucible (Control)": 6, - "Crucible (Survival)": 3, - "Crucible (Elimination)": 3, - "Crucible (Private Match)": 12, - "Iron Banner": 6, - "Trials of Osiris": 3 + 'Crucible': { + 'Crucible (Control)': 6, + 'Crucible (Survival)': 3, + 'Crucible (Elimination)': 3, + 'Crucible (Private Match)': 12, + 'Iron Banner': 6, + 'Trials of Osiris': 3, }, - "Gambit": { - "Gambit (Classic)": 4, - "Gambit (Private Match)": 8 + 'Gambit': { + 'Gambit (Classic)': 4, + 'Gambit (Private Match)': 8, }, /* "Exotic Missions": { // "Presage": 3, // "Harbinger": 3 }, */ - "Nightfall": 3, - "Miscellaneous": { - "Weekly Witch Queen Campaign Mission": 3, - "Wellspring": 6, - "Dares of Eternity": 6, + 'Nightfall': 3, + 'Miscellaneous': { + 'Weekly Witch Queen Campaign Mission': 3, + 'Wellspring': 6, + 'Dares of Eternity': 6, // "Astral Alignment": 6, // "Shattered Realm": 3, // "Override": 6, // "Expunge": 3, // "Battlegrounds": 3, - "Wrathborn Hunt": 3, - "Empire Hunt": 3, - "Vanguard Operations": 3 + 'Wrathborn Hunt': 3, + 'Empire Hunt': 3, + 'Vanguard Operations': 3, // "Nightmare Hunt": 3 - } + }, + }, + 'Among Us': { + 'Vanilla': 15, + 'Modded': 15, }, - "Among Us": { - "Vanilla": 15, - "Modded": 15 - } }; diff --git a/src/intervals.ts b/src/intervals.ts index e549244..aea2c91 100644 --- a/src/intervals.ts +++ b/src/intervals.ts @@ -1,22 +1,25 @@ import { // Discordeno deps cache, - sendMessage, getMessage, deleteMessage, sendDirectMessage, + deleteMessage, getGuild, - + getMessage, + log, // Log4Deno deps - LT, log -} from "../deps.ts"; + LT, + sendDirectMessage, + sendMessage, +} from '../deps.ts'; -import { jsonStringifyBig } from "./utils.ts"; -import { BuildingLFG, ActiveLFG } from "./mod.d.ts"; +import { jsonStringifyBig } from './utils.ts'; +import { ActiveLFG, BuildingLFG } from './mod.d.ts'; -import config from "../config.ts"; +import config from '../config.ts'; // getRandomStatus() returns status as string // Gets a new random status for the bot const getRandomStatus = (cachedGuilds: number): string => { - let status = ""; + let status = ''; switch (Math.floor((Math.random() * 5) + 1)) { case 1: status = `${config.prefix}help for commands`; @@ -28,35 +31,34 @@ const getRandomStatus = (cachedGuilds: number): string => { status = `${config.prefix}info to learn more`; break; case 4: - status = "Mention me to check my prefix!"; + status = 'Mention me to check my prefix!'; break; default: status = `Running LFGs in ${cachedGuilds + cache.dispatchedGuildIds.size} servers`; break; } - + return status; }; // updateListStatistics(bot ID, current guild count) returns nothing // Sends the current server count to all bot list sites we are listed on const updateListStatistics = (botID: BigInt, serverCount: number): void => { - config.botLists.forEach(async e => { + config.botLists.forEach(async (e) => { if (e.enabled) { log(LT.LOG, `Updating statistics for ${jsonStringifyBig(e)}`); try { const tempHeaders = new Headers(); tempHeaders.append(e.headers[0].header, e.headers[0].value); - tempHeaders.append("Content-Type", "application/json"); + tempHeaders.append('Content-Type', 'application/json'); // ?{} is a template used in config, just need to replace it with the real value - const response = await fetch(e.apiUrl.replace("?{bot_id}", botID.toString()), { - "method": 'POST', - "headers": tempHeaders, - "body": jsonStringifyBig(e.body).replace('"?{server_count}"', serverCount.toString()) // ?{server_count} needs the "" removed from around it aswell to make sure its sent as a number + const response = await fetch(e.apiUrl.replace('?{bot_id}', botID.toString()), { + 'method': 'POST', + 'headers': tempHeaders, + 'body': jsonStringifyBig(e.body).replace('"?{server_count}"', serverCount.toString()), // ?{server_count} needs the "" removed from around it aswell to make sure its sent as a number }); log(LT.INFO, `Posted server count to ${e.name}. Results: ${jsonStringifyBig(response)}`); - } - catch (e) { + } catch (e) { log(LT.WARN, `Failed to post statistics to ${e.name} | ${jsonStringifyBig(e)}`); } } @@ -65,33 +67,31 @@ const updateListStatistics = (botID: BigInt, serverCount: number): void => { const buildingTimeout = async (activeBuilders: Array): Promise => { const currentTime = new Date().getTime(); - for (let i = 0; i < activeBuilders.length; i++) { + for (let i = 0; i < activeBuilders.length; i++) { if (activeBuilders[i].lastTouch.getTime() + (activeBuilders[i].maxIdle * 1000) < currentTime) { - activeBuilders[i].questionMsg.delete().catch(e => { + activeBuilders[i].questionMsg.delete().catch((e) => { log(LT.WARN, `Failed to clean up active builder | edit | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`); }); if (activeBuilders[i].editing) { activeBuilders[i].lfgMsg.edit({ - content: "" - }).catch(e => { + content: '', + }).catch((e) => { log(LT.WARN, `Failed to clean up active builder | edit | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`); }); } else { - activeBuilders[i].lfgMsg.delete().catch(e => { + activeBuilders[i].lfgMsg.delete().catch((e) => { log(LT.WARN, `Failed to clean up active builder | delete | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`); }); } try { - const m = await sendMessage(activeBuilders[i].channelId, `<@${activeBuilders[i].userId}>, your LFG ${activeBuilders[i].editing ? "editing" : "creation"} has timed out. Please try again.`); - - m.delete("Channel Cleanup", 30000).catch(e =>{ + const m = await sendMessage(activeBuilders[i].channelId, `<@${activeBuilders[i].userId}>, your LFG ${activeBuilders[i].editing ? 'editing' : 'creation'} has timed out. Please try again.`); + + m.delete('Channel Cleanup', 30000).catch((e) => { log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(e)}`); }); - } - catch (e) { + } catch (e) { log(LT.WARN, `Failed to clean up active builder | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`); - } - finally { + } finally { activeBuilders.splice(i, 1); i--; } @@ -100,7 +100,7 @@ const buildingTimeout = async (activeBuilders: Array): Promise): Promise => { - log(LT.INFO, "Checking for LFG posts to notify/delete/lock"); + log(LT.INFO, 'Checking for LFG posts to notify/delete/lock'); const tenMin = 10 * 60 * 1000; const now = new Date().getTime(); for (let i = 0; i < activeLFGPosts.length; i++) { @@ -111,12 +111,12 @@ const lfgNotifier = async (activeLFGPosts: Array): Promise => { const message = await getMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId); const lfg = message.embeds[0].fields || []; const lfgActivity = `${lfg[0].name.substr(0, lfg[0].name.length - 1)} - ${lfg[0].value}`; - const guildName = message.guild?.name || (await getGuild(message.guildId, {counts:false, addToCache: false})).name; + const guildName = message.guild?.name || (await getGuild(message.guildId, { counts: false, addToCache: false })).name; const members = lfg[4].value; - let editMsg = ""; - members.split("\n").forEach(async m => { - if (m !== "None") { - const [name, tmpId] = m.split(" - <@"); + let editMsg = ''; + members.split('\n').forEach(async (m) => { + if (m !== 'None') { + const [name, tmpId] = m.split(' - <@'); const userId = BigInt(tmpId.substr(0, tmpId.length - 1)); editMsg += `<@${userId}>, `; await sendDirectMessage(userId, { @@ -125,62 +125,56 @@ const lfgNotifier = async (activeLFGPosts: Array): Promise => { fields: [ lfg[0], { - name: "Please start grouping up with the other members of this activity:", - value: members - } - ] - }] + name: 'Please start grouping up with the other members of this activity:', + value: members, + }, + ], + }], }); } }); editMsg += `your ${lfgActivity} starts in less than 10 minutes.`; await message.edit({ - content: editMsg + content: editMsg, }); activeLFGPosts[i].notified = true; - } - catch (err) { + } catch (err) { log(LT.WARN, `Failed to find LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(err)}`); - + activeLFGPosts.splice(i, 1); i--; } - } - - // Lock LFG from editing/Joining/Leaving + } // Lock LFG from editing/Joining/Leaving else if (!activeLFGPosts[i].locked && activeLFGPosts[i].lfgTime < now) { log(LT.INFO, `Locking LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`); try { const message = await getMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId); await message.edit({ - components: [] + components: [], }); activeLFGPosts[i].locked = true; - } - catch (err) { + } catch (err) { log(LT.WARN, `Failed to find LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(err)}`); - + activeLFGPosts.splice(i, 1); i--; } - } - - // Delete old LFG post + } // Delete old LFG post else if (activeLFGPosts[i].lfgTime < (now - tenMin)) { log(LT.INFO, `Deleting LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`); - await deleteMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId, "LFG post expired").catch(e => { + await deleteMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId, 'LFG post expired').catch((e) => { log(LT.WARN, `Failed to delete LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(e)}`); }); activeLFGPosts.splice(i, 1); i--; } } - - localStorage.setItem("activeLFGPosts", jsonStringifyBig(activeLFGPosts)); + + localStorage.setItem('activeLFGPosts', jsonStringifyBig(activeLFGPosts)); }; export default { getRandomStatus, updateListStatistics, buildingTimeout, lfgNotifier }; diff --git a/src/lfgHandlers.d.ts b/src/lfgHandlers.d.ts index 6ca62bc..9e7bdf8 100644 --- a/src/lfgHandlers.d.ts +++ b/src/lfgHandlers.d.ts @@ -1,16 +1,14 @@ -import { - EmbedField -} from "../deps.ts"; +import { EmbedField } from '../deps.ts'; export type JoinLeaveType = { - embed: EmbedField[], - success: boolean, - full: boolean, - justFilled: boolean -} + embed: EmbedField[]; + success: boolean; + full: boolean; + justFilled: boolean; +}; export type UrlIds = { - guildId: bigint, - channelId: bigint, - messageId: bigint -} + guildId: bigint; + channelId: bigint; + messageId: bigint; +}; diff --git a/src/lfgHandlers.ts b/src/lfgHandlers.ts index 8dd2eca..11a9248 100644 --- a/src/lfgHandlers.ts +++ b/src/lfgHandlers.ts @@ -1,93 +1,89 @@ -import { - ActionRow, ButtonComponent, DiscordButtonStyles, EmbedField, DiscordenoMember, +import { ActionRow, ButtonComponent, DiscordButtonStyles, DiscordenoMember, EmbedField, log, LT } from '../deps.ts'; - LT, log -} from "../deps.ts"; - -import { JoinLeaveType, UrlIds } from "./lfgHandlers.d.ts"; -import { BuildingLFG } from "./mod.d.ts"; -import { LFGActivities } from "./games.ts"; -import { determineTZ } from "./timeUtils.ts"; -import { lfgStepQuestions } from "./constantCmds.ts"; -import { jsonStringifyBig } from "./utils.ts"; +import { JoinLeaveType, UrlIds } from './lfgHandlers.d.ts'; +import { BuildingLFG } from './mod.d.ts'; +import { LFGActivities } from './games.ts'; +import { determineTZ } from './timeUtils.ts'; +import { lfgStepQuestions } from './constantCmds.ts'; +import { jsonStringifyBig } from './utils.ts'; export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise => { const currentLFG = (wipLFG.lfgMsg.embeds[0] || { fields: undefined }).fields || [ { - name: ". . .", - value: ". . .", - inline: true + name: '. . .', + value: '. . .', + inline: true, }, { - name: "Start Time:", - value: ". . .", - inline: true + name: 'Start Time:', + value: '. . .', + inline: true, }, { - name: "Add to Calendar:", - value: ". . .", - inline: true + name: 'Add to Calendar:', + value: '. . .', + inline: true, }, { - name: "Description:", - value: ". . .", - inline: false + name: 'Description:', + value: '. . .', + inline: false, }, { name: `Members Joined: 0/?`, - value: "None", - inline: true + value: 'None', + inline: true, }, { - name: "Alternates:", - value: "None", - inline: true - } + name: 'Alternates:', + value: 'None', + inline: true, + }, ]; - let nextQuestion = ""; + let nextQuestion = ''; const nextComponents: Array = []; let editFlag = true; switch (wipLFG.step) { - case "set_game": { + case 'set_game': { currentLFG[0].name = input.substr(0, 254); if (Object.prototype.hasOwnProperty.call(LFGActivities, input)) { nextQuestion = lfgStepQuestions.set_activity_with_button; let tempObj = {}; - Object.entries(LFGActivities).some(e => { + Object.entries(LFGActivities).some((e) => { if (e[0] === input) { tempObj = e[1]; return true; } }); - const activityButtons: Array = Object.keys(tempObj).map(activity => { + const activityButtons: Array = Object.keys(tempObj).map((activity) => { return { type: 2, label: activity, customId: `building@set_activity#${activity}`, - style: DiscordButtonStyles.Primary + style: DiscordButtonStyles.Primary, }; }); - const temp: Array = []; + const temp: Array = []; activityButtons.forEach((btn, idx) => { - if (!temp[Math.floor(idx/5)]) { - temp[Math.floor(idx/5)] = [btn]; + if (!temp[Math.floor(idx / 5)]) { + temp[Math.floor(idx / 5)] = [btn]; } else { - temp[Math.floor(idx/5)].push(btn); + temp[Math.floor(idx / 5)].push(btn); } }); - temp.forEach(btns => { + temp.forEach((btns) => { if (btns.length && btns.length <= 5) { nextComponents.push({ type: 1, - components: btns + components: btns, }); } }); @@ -95,16 +91,16 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise nextQuestion = lfgStepQuestions.set_activity_with_text; } - wipLFG.step = "set_activity"; + wipLFG.step = 'set_activity'; break; } - case "set_activity": { + case 'set_activity': { const game = currentLFG[0].name; let tempObj; - Object.entries(LFGActivities).some(e => { + Object.entries(LFGActivities).some((e) => { if (e[0] === game) { - Object.entries(e[1]).some(f => { + Object.entries(e[1]).some((f) => { if (f[0] === input) { tempObj = f[1]; return true; @@ -117,67 +113,67 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise currentLFG[0].name = `${game}:`; currentLFG[0].value = input.substr(0, 1023); - if (typeof tempObj === "number") { + if (typeof tempObj === 'number') { // Activity - currentLFG[4].name = `Members Joined: ${currentLFG[4].value === "None" ? 0 : currentLFG[4].value.split("\n").length}/${tempObj}`; + currentLFG[4].name = `Members Joined: ${currentLFG[4].value === 'None' ? 0 : currentLFG[4].value.split('\n').length}/${tempObj}`; nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time; - wipLFG.step = wipLFG.editing ? "done" : "set_time"; + wipLFG.step = wipLFG.editing ? 'done' : 'set_time'; } else if (!tempObj) { // Custom nextQuestion = lfgStepQuestions.set_player_cnt; - wipLFG.step = "set_player_cnt"; + wipLFG.step = 'set_player_cnt'; } else { // Category nextQuestion = lfgStepQuestions.set_activity_from_category; currentLFG[0].name = game; - - const activityButtons: Array = Object.keys(tempObj).map(activity => { + + const activityButtons: Array = Object.keys(tempObj).map((activity) => { return { type: 2, label: activity, customId: `building@set_activity_from_category#${activity}`, - style: DiscordButtonStyles.Primary + style: DiscordButtonStyles.Primary, }; }); - const temp: Array = []; + const temp: Array = []; activityButtons.forEach((btn, idx) => { - if (!temp[Math.floor(idx/5)]) { - temp[Math.floor(idx/5)] = [btn]; + if (!temp[Math.floor(idx / 5)]) { + temp[Math.floor(idx / 5)] = [btn]; } else { - temp[Math.floor(idx/5)].push(btn); + temp[Math.floor(idx / 5)].push(btn); } }); - temp.forEach(btns => { + temp.forEach((btns) => { if (btns.length && btns.length <= 5) { nextComponents.push({ type: 1, - components: btns + components: btns, }); } }); - wipLFG.step = "set_activity_from_category"; + wipLFG.step = 'set_activity_from_category'; } break; } - case "set_activity_from_category": { + case 'set_activity_from_category': { const game = currentLFG[0].name; const category = currentLFG[0].value; let tempObj; - Object.entries(LFGActivities).some(e => { + Object.entries(LFGActivities).some((e) => { if (e[0] === game) { - Object.entries(e[1]).some(f => { + Object.entries(e[1]).some((f) => { if (f[0] === category) { - Object.entries(f[1]).some(g => { + Object.entries(f[1]).some((g) => { if (g[0] === input) { tempObj = g[1]; return true; @@ -194,62 +190,62 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise currentLFG[0].value = input.substr(0, 1023); if (tempObj) { - currentLFG[4].name = `Members Joined: ${currentLFG[4].value === "None" ? 0 : currentLFG[4].value.split("\n").length}/${tempObj}`; - - nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time; - - wipLFG.step = wipLFG.editing ? "done" : "set_time"; - } else { - nextQuestion = lfgStepQuestions.set_player_cnt; - - wipLFG.step = "set_player_cnt"; - } - break; - } - case "set_player_cnt": { - if (parseInt(input)) { - currentLFG[4].name = `Members Joined: ${currentLFG[4].value === "None" ? 0 : currentLFG[4].value.split("\n").length}/${Math.abs(parseInt(input)) || 1}`; + currentLFG[4].name = `Members Joined: ${currentLFG[4].value === 'None' ? 0 : currentLFG[4].value.split('\n').length}/${tempObj}`; nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time; - wipLFG.step = wipLFG.editing ? "done" : "set_time"; + wipLFG.step = wipLFG.editing ? 'done' : 'set_time'; } else { - editFlag = false; + nextQuestion = lfgStepQuestions.set_player_cnt; - nextQuestion = `Input max members "${input}" is invalid, please make sure you are only entering a number.\n\n${lfgStepQuestions.set_player_cnt}` + wipLFG.step = 'set_player_cnt'; } break; } - case "set_time": { + case 'set_player_cnt': { + if (parseInt(input)) { + currentLFG[4].name = `Members Joined: ${currentLFG[4].value === 'None' ? 0 : currentLFG[4].value.split('\n').length}/${Math.abs(parseInt(input)) || 1}`; + + nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time; + + wipLFG.step = wipLFG.editing ? 'done' : 'set_time'; + } else { + editFlag = false; + + nextQuestion = `Input max members "${input}" is invalid, please make sure you are only entering a number.\n\n${lfgStepQuestions.set_player_cnt}`; + } + break; + } + case 'set_time': { const today = new Date(); let lfgDate = `${today.getMonth() + 1}/${today.getDate()}`, - lfgTime = "", - lfgTZ = "", - lfgPeriod = "", + lfgTime = '', + lfgTZ = '', + lfgPeriod = '', overrodeTZ = false; - - input.split(" ").forEach(c => { - if (c.includes("/")) { + + input.split(' ').forEach((c) => { + if (c.includes('/')) { lfgDate = c; - } else if (c.toLowerCase() === "am" || c.toLowerCase() === "pm") { + } else if (c.toLowerCase() === 'am' || c.toLowerCase() === 'pm') { lfgPeriod = c.toLowerCase(); - } else if (c.toLowerCase().includes("am") || c.toLowerCase().includes("pm")) { + } else if (c.toLowerCase().includes('am') || c.toLowerCase().includes('pm')) { lfgTime = c.substr(0, c.length - 2); - lfgPeriod = c.toLowerCase().includes("am") ? "am" : "pm"; - } else if (c.includes(":")) { + lfgPeriod = c.toLowerCase().includes('am') ? 'am' : 'pm'; + } else if (c.includes(':')) { lfgTime = c; - } else if (parseInt(c).toString() === (c.replace(/^0+/, '') || "0")) { + } else if (parseInt(c).toString() === (c.replace(/^0+/, '') || '0')) { if (c.length === 4) { if (parseInt(c) >= 1300) { lfgTime = (parseInt(c) - 1200).toString(); - lfgPeriod = "pm"; + lfgPeriod = 'pm'; } else if (parseInt(c) >= 1200) { lfgTime = c; - lfgPeriod = "pm"; + lfgPeriod = 'pm'; } else { - lfgTime = c.startsWith("00") ? `12${c.substr(2)}` : c; - lfgPeriod = "am"; + lfgTime = c.startsWith('00') ? `12${c.substr(2)}` : c; + lfgPeriod = 'am'; } const hourLen = lfgTime.length === 4 ? 2 : 1; @@ -267,60 +263,62 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise }); if (!lfgTZ) { - [lfgTZ, overrodeTZ] = determineTZ("ET"); + [lfgTZ, overrodeTZ] = determineTZ('ET'); } - if (!lfgTime.includes(":")) { - lfgTime += ":00"; + if (!lfgTime.includes(':')) { + lfgTime += ':00'; } if (!lfgPeriod) { - lfgPeriod = today.getHours() >= 12 ? "pm" : "am"; + lfgPeriod = today.getHours() >= 12 ? 'pm' : 'am'; } lfgPeriod = lfgPeriod.toUpperCase(); lfgTZ = lfgTZ.toUpperCase(); - lfgDate = `${lfgDate.split("/")[0]}/${lfgDate.split("/")[1]}/${today.getFullYear()}`; + lfgDate = `${lfgDate.split('/')[0]}/${lfgDate.split('/')[1]}/${today.getFullYear()}`; log(LT.LOG, `Date Time Debug | ${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}`); const lfgDateTime = new Date(`${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}`); - lfgDate = `${lfgDate.split("/")[0]}/${lfgDate.split("/")[1]}`; + lfgDate = `${lfgDate.split('/')[0]}/${lfgDate.split('/')[1]}`; const lfgDateStr = `[${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}](https://groupup.eanm.dev/tz#${lfgDateTime.getTime()})`; const icsDetails = `${currentLFG[0].name} ${currentLFG[0].value}`; - const icsStr = `[Download ICS File](https://groupup.eanm.dev/ics?t=${lfgDateTime.getTime()}&n=${icsDetails.replaceAll(" ", "+")})` + const icsStr = `[Download ICS File](https://groupup.eanm.dev/ics?t=${lfgDateTime.getTime()}&n=${icsDetails.replaceAll(' ', '+')})`; - currentLFG[1].name = "Start Time (Click for Conversion):"; + currentLFG[1].name = 'Start Time (Click for Conversion):'; currentLFG[1].value = lfgDateStr.substr(0, 1023); currentLFG[2].value = icsStr.substr(0, 1023); if (isNaN(lfgDateTime.getTime())) { - nextQuestion = `Input time "${input}" (parsed as "${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}") is invalid, please make sure you have the timezone set correctly.\n\n${lfgStepQuestions.set_time}`; + nextQuestion = + `Input time "${input}" (parsed as "${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}") is invalid, please make sure you have the timezone set correctly.\n\n${lfgStepQuestions.set_time}`; editFlag = false; } else if (lfgDateTime.getTime() <= today.getTime()) { - nextQuestion = `Input time "${input}" (parsed as "${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}") is in the past, please make sure you are setting up the event to be in the future.\n\n${lfgStepQuestions.set_time}`; + nextQuestion = + `Input time "${input}" (parsed as "${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}") is in the past, please make sure you are setting up the event to be in the future.\n\n${lfgStepQuestions.set_time}`; editFlag = false; } else { nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_desc; - wipLFG.step = wipLFG.editing ? "done" : "set_desc"; + wipLFG.step = wipLFG.editing ? 'done' : 'set_desc'; } break; } - case "set_desc":{ - if (input === "none") { + case 'set_desc': { + if (input === 'none') { input = currentLFG[0].value; } currentLFG[3].value = input.substr(0, 1023); - nextQuestion = lfgStepQuestions.set_done; + nextQuestion = lfgStepQuestions.set_done; - wipLFG.step = "done"; + wipLFG.step = 'done'; break; } default: @@ -331,17 +329,16 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise if (editFlag) { wipLFG.lfgMsg = await wipLFG.lfgMsg.edit({ embeds: [{ - fields: currentLFG - }] + fields: currentLFG, + }], }); } wipLFG.questionMsg = await wipLFG.questionMsg.edit({ content: nextQuestion, - components: nextComponents + components: nextComponents, }); - } - catch (e) { + } catch (e) { log(LT.WARN, `Failed to edit active builder | ${wipLFG.userId}-${wipLFG.channelId} | ${jsonStringifyBig(e)}`); } @@ -351,20 +348,20 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, alternate: boolean): JoinLeaveType => { let success = false; let justFilled = false; - + const userStr = `${member.username} - <@${member.id}>`; - - const tempMembers = lfg[4].name.split(":")[1].split("/"); + + const tempMembers = lfg[4].name.split(':')[1].split('/'); let currentMembers = parseInt(tempMembers[0]); const maxMembers = parseInt(tempMembers[1]); if (alternate && !lfg[5].value.includes(member.id.toString())) { // remove from joined list if (lfg[4].value.includes(member.id.toString())) { - const tempArr = lfg[4].value.split("\n"); - const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString())); - tempArr.splice(memberIdx, 1) - lfg[4].value = tempArr.join("\n") || "None"; + const tempArr = lfg[4].value.split('\n'); + const memberIdx = tempArr.findIndex((m) => m.includes(member.id.toString())); + tempArr.splice(memberIdx, 1); + lfg[4].value = tempArr.join('\n') || 'None'; if (currentMembers) { currentMembers--; @@ -372,7 +369,7 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al lfg[4].name = `Members Joined: ${currentMembers}/${maxMembers}`; } - if (lfg[5].value === "None") { + if (lfg[5].value === 'None') { lfg[5].value = userStr; } else { lfg[5].value += `\n${userStr}`; @@ -382,13 +379,13 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al } else if (!alternate && currentMembers < maxMembers && !lfg[4].value.includes(member.id.toString())) { // remove from alternate list if (lfg[5].value.includes(member.id.toString())) { - const tempArr = lfg[5].value.split("\n"); - const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString())); + const tempArr = lfg[5].value.split('\n'); + const memberIdx = tempArr.findIndex((m) => m.includes(member.id.toString())); tempArr.splice(memberIdx, 1); - lfg[5].value = tempArr.join("\n") || "None"; + lfg[5].value = tempArr.join('\n') || 'None'; } - if (lfg[4].value === "None") { + if (lfg[4].value === 'None') { lfg[4].value = userStr; } else { lfg[4].value += `\n${userStr}`; @@ -402,12 +399,12 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al } else if (!alternate && currentMembers === maxMembers && !lfg[4].value.includes(member.id.toString())) { // update user in alternate list to include the * to make them autojoin if (lfg[5].value.includes(member.id.toString())) { - const tempArr = lfg[5].value.split("\n"); - const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString())); + const tempArr = lfg[5].value.split('\n'); + const memberIdx = tempArr.findIndex((m) => m.includes(member.id.toString())); tempArr[memberIdx] = `${tempArr[memberIdx]} *`; - lfg[5].value = tempArr.join("\n"); + lfg[5].value = tempArr.join('\n'); } else { - if (lfg[5].value === "None") { + if (lfg[5].value === 'None') { lfg[5].value = `${userStr} *`; } else { lfg[5].value += `\n${userStr} *`; @@ -421,7 +418,7 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al embed: lfg, success: success, full: currentMembers === maxMembers, - justFilled: justFilled + justFilled: justFilled, }; }; @@ -430,28 +427,28 @@ export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember): const memberId = member.id.toString(); - const tempMembers = lfg[4].name.split(":")[1].split("/"); + const tempMembers = lfg[4].name.split(':')[1].split('/'); let currentMembers = parseInt(tempMembers[0]); const maxMembers = parseInt(tempMembers[1]); if (lfg[4].value.includes(memberId)) { - const tempArr = lfg[4].value.split("\n"); - const memberIdx = tempArr.findIndex(m => m.includes(memberId)); + const tempArr = lfg[4].value.split('\n'); + const memberIdx = tempArr.findIndex((m) => m.includes(memberId)); tempArr.splice(memberIdx, 1); - lfg[4].value = tempArr.join("\n") || "None"; + lfg[4].value = tempArr.join('\n') || 'None'; - if (lfg[5].value.includes("*")) { + if (lfg[5].value.includes('*')) { // find first * user and move them to the joined list - const tempArr2 = lfg[5].value.split("\n"); - const memberToMoveIdx = tempArr2.findIndex(m => m.includes("*")) + const tempArr2 = lfg[5].value.split('\n'); + const memberToMoveIdx = tempArr2.findIndex((m) => m.includes('*')); let memberToMove = tempArr2[memberToMoveIdx]; memberToMove = memberToMove.substr(0, memberToMove.length - 2); tempArr.push(memberToMove); - lfg[4].value = tempArr.join("\n") || "None"; + lfg[4].value = tempArr.join('\n') || 'None'; // Remove them from the alt list tempArr2.splice(memberToMoveIdx, 1); - lfg[5].value = tempArr2.join("\n") || "None"; + lfg[5].value = tempArr2.join('\n') || 'None'; } else { // update count since no users were marked as * if (currentMembers) { @@ -464,10 +461,10 @@ export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember): } if (lfg[5].value.includes(memberId)) { - const tempArr = lfg[5].value.split("\n"); - const memberIdx = tempArr.findIndex(m => m.includes(memberId)); + const tempArr = lfg[5].value.split('\n'); + const memberIdx = tempArr.findIndex((m) => m.includes(memberId)); tempArr.splice(memberIdx, 1); - lfg[5].value = tempArr.join("\n") || "None"; + lfg[5].value = tempArr.join('\n') || 'None'; success = true; } @@ -476,24 +473,24 @@ export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember): embed: lfg, success: success, full: currentMembers === maxMembers, - justFilled: false + justFilled: false, }; }; export const urlToIds = (url: string): UrlIds => { const strIds = { - guildId: "", - channelId: "", - messageId: "" + guildId: '', + channelId: '', + messageId: '', }; url = url.toLowerCase(); - [strIds.guildId, strIds.channelId, strIds.messageId] = url.substr((url.indexOf("channels") + 9)).split("/"); + [strIds.guildId, strIds.channelId, strIds.messageId] = url.substr(url.indexOf('channels') + 9).split('/'); return { guildId: BigInt(strIds.guildId), channelId: BigInt(strIds.channelId), - messageId: BigInt(strIds.messageId) + messageId: BigInt(strIds.messageId), }; }; diff --git a/src/mod.d.ts b/src/mod.d.ts index 0cd7ab2..eb95b62 100644 --- a/src/mod.d.ts +++ b/src/mod.d.ts @@ -1,39 +1,37 @@ -import { - DiscordenoMessage -} from "../deps.ts"; +import { DiscordenoMessage } from '../deps.ts'; export type BuildingLFG = { - userId: bigint, - channelId: bigint, - step: string, - lfgMsg: DiscordenoMessage, - questionMsg: DiscordenoMessage, - lastTouch: Date, - maxIdle: number, - editing: boolean -} + userId: bigint; + channelId: bigint; + step: string; + lfgMsg: DiscordenoMessage; + questionMsg: DiscordenoMessage; + lastTouch: Date; + maxIdle: number; + editing: boolean; +}; export type ActiveLFG = { - messageId: bigint, - channelId: bigint, - ownerId: bigint, - lfgUid: string, - lfgTime: number, - notified: boolean, - locked: boolean -} + messageId: bigint; + channelId: bigint; + ownerId: bigint; + lfgUid: string; + lfgTime: number; + notified: boolean; + locked: boolean; +}; export type GuildPrefixes = { - guildId: bigint, - prefix: string -} + guildId: bigint; + prefix: string; +}; export type GuildModRoles = { - guildId: bigint, - roleId: bigint -} + guildId: bigint; + roleId: bigint; +}; export type GuildCleanChannels = { - guildId: bigint, - channelId: bigint -} + guildId: bigint; + channelId: bigint; +}; diff --git a/src/timeUtils.ts b/src/timeUtils.ts index 858d54e..7bdde36 100644 --- a/src/timeUtils.ts +++ b/src/timeUtils.ts @@ -2,18 +2,18 @@ export const determineTZ = (tz: string, userOverride = false): [string, boolean] tz = tz.toUpperCase(); let overrode = false; - const shortHandUSTZ = (tz === "ET" || tz === "CT" || tz === "MT" || tz === "PT"); - const fullUSTZ = (tz.length === 3 && (tz.startsWith("E") || tz.startsWith("C") || tz.startsWith("M") || tz.startsWith("P")) && (tz.endsWith("DT") || tz.endsWith("ST"))); + const shortHandUSTZ = (tz === 'ET' || tz === 'CT' || tz === 'MT' || tz === 'PT'); + const fullUSTZ = (tz.length === 3 && (tz.startsWith('E') || tz.startsWith('C') || tz.startsWith('M') || tz.startsWith('P')) && (tz.endsWith('DT') || tz.endsWith('ST'))); if (!userOverride && (shortHandUSTZ || fullUSTZ)) { const today = new Date(); const jan = new Date(today.getFullYear(), 0, 1); const jul = new Date(today.getFullYear(), 6, 1); if (today.getTimezoneOffset() < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset())) { - if (tz.includes("S")) overrode = true; + if (tz.includes('S')) overrode = true; tz = `${tz.substr(0, 1)}DT`; } else { - if (tz.includes("D")) overrode = true; + if (tz.includes('D')) overrode = true; tz = `${tz.substr(0, 1)}ST`; } } diff --git a/src/utils.ts b/src/utils.ts index 33db888..e53e3a5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,6 +1,6 @@ export const jsonParseBig = (input: string) => { return JSON.parse(input, (_key, value) => { - if (typeof value === "string" && /^\d+n$/.test(value)) { + if (typeof value === 'string' && /^\d+n$/.test(value)) { return BigInt(value.substr(0, value.length - 1)); } return value; @@ -8,7 +8,5 @@ export const jsonParseBig = (input: string) => { }; export const jsonStringifyBig = (input: any) => { - return JSON.stringify(input, (_key, value) => - typeof value === "bigint" ? value.toString() + "n" : value - ); + return JSON.stringify(input, (_key, value) => typeof value === 'bigint' ? value.toString() + 'n' : value); };