deno fmt this time + readme update

This commit is contained in:
Ean Milligan (Bastion) 2022-07-10 20:48:38 -04:00
parent cc1825fb25
commit 5f4c3b10b1
14 changed files with 850 additions and 863 deletions

View File

@ -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

View File

@ -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;

View File

@ -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!');

View File

@ -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!');

45
deps.ts
View File

@ -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';

831
mod.ts

File diff suppressed because it is too large Load Diff

View File

@ -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. . .',
};

View File

@ -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
}
};

View File

@ -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<BuildingLFG>): Promise<void> => {
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<BuildingLFG>): Promise<void
};
const lfgNotifier = async (activeLFGPosts: Array<ActiveLFG>): Promise<void> => {
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<ActiveLFG>): Promise<void> => {
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<ActiveLFG>): Promise<void> => {
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 };

22
src/lfgHandlers.d.ts vendored
View File

@ -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;
};

View File

@ -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<BuildingLFG> => {
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<ActionRow> = [];
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<ButtonComponent> = Object.keys(tempObj).map(activity => {
const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map((activity) => {
return {
type: 2,
label: activity,
customId: `building@set_activity#${activity}`,
style: DiscordButtonStyles.Primary
style: DiscordButtonStyles.Primary,
};
});
const temp: Array<ActionRow["components"]> = [];
const temp: Array<ActionRow['components']> = [];
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<ButtonComponent> = Object.keys(tempObj).map(activity => {
const activityButtons: Array<ButtonComponent> = 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<ActionRow["components"]> = [];
const temp: Array<ActionRow['components']> = [];
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),
};
};

56
src/mod.d.ts vendored
View File

@ -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;
};

View File

@ -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`;
}
}

View File

@ -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);
};