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. Group Up is a Discord bot built for scheduling events in your Guild.
# Invite Link # Invite Link

View File

@ -1,37 +1,37 @@
export const config = { export const config = {
"name": "Group Up", // Name of the bot 'name': 'Group Up', // Name of the bot
"version": "0.5.6", // Version of the bot 'version': '0.5.6', // Version of the bot
"token": "the_bot_token", // Discord API Token for this 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" '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 '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 '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 '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 '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 '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 '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 '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': '', // 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 '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 '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 '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 '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 'botLists': [ // Array of objects containing all bot lists that stats should be posted to
{ // Bot List object, duplicate for each bot list { // Bot List object, duplicate for each bot list
"name": "Bot List Name", // Name of bot list, not used 'name': 'Bot List Name', // Name of bot list, not used
"enabled": false, // Should statistics be posted to this list? '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 '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 'headers': [ // Array of headers that need to be added to the request
{ // Header Object, duplicate for every header needed { // Header Object, duplicate for every header needed
"header": "header_name", // Name of header needed, usually Authorization is needed 'header': 'header_name', // Name of header needed, usually Authorization is needed
"value": "header_value" // Value for the header '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; export default config;

View File

@ -3,11 +3,11 @@
import { import {
// MySQL deps // MySQL deps
Client Client,
} from "../deps.ts"; } from '../deps.ts';
import { LOCALMODE } from "../flags.ts"; import { LOCALMODE } from '../flags.ts';
import config from "../config.ts"; import config from '../config.ts';
// Log into the MySQL DB // Log into the MySQL DB
const dbClient = await new Client().connect({ const dbClient = await new Client().connect({
@ -17,20 +17,20 @@ const dbClient = await new Client().connect({
password: config.db.password, 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(`CREATE SCHEMA IF NOT EXISTS ${config.db.name};`);
await dbClient.execute(`USE ${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 PROCEDURE IF EXISTS INC_CNT;`);
await dbClient.execute(`DROP TABLE IF EXISTS command_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_prefix;`);
await dbClient.execute(`DROP TABLE IF EXISTS guild_mod_role;`); await dbClient.execute(`DROP TABLE IF EXISTS guild_mod_role;`);
await dbClient.execute(`DROP TABLE IF EXISTS guild_clean_channel;`); 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(` await dbClient.execute(`
CREATE TABLE command_cnt ( CREATE TABLE command_cnt (
command char(20) NOT NULL, command char(20) NOT NULL,
@ -39,9 +39,9 @@ await dbClient.execute(`
UNIQUE KEY command_cnt_command_UNIQUE (command) UNIQUE KEY command_cnt_command_UNIQUE (command)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) 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(` await dbClient.execute(`
CREATE PROCEDURE INC_CNT( CREATE PROCEDURE INC_CNT(
IN cmd CHAR(20) IN cmd CHAR(20)
@ -52,9 +52,9 @@ await dbClient.execute(`
UPDATE command_cnt SET count = oldcnt + 1 WHERE command = cmd; UPDATE command_cnt SET count = oldcnt + 1 WHERE command = cmd;
END 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(` await dbClient.execute(`
CREATE TABLE guild_prefix ( CREATE TABLE guild_prefix (
guildId bigint unsigned NOT NULL, guildId bigint unsigned NOT NULL,
@ -63,9 +63,9 @@ await dbClient.execute(`
UNIQUE KEY guild_prefix_guildid_UNIQUE (guildid) UNIQUE KEY guild_prefix_guildid_UNIQUE (guildid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) 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(` await dbClient.execute(`
CREATE TABLE guild_mod_role ( CREATE TABLE guild_mod_role (
guildId bigint unsigned NOT NULL, guildId bigint unsigned NOT NULL,
@ -74,9 +74,9 @@ await dbClient.execute(`
UNIQUE KEY guild_mod_role_guildid_UNIQUE (guildid) UNIQUE KEY guild_mod_role_guildid_UNIQUE (guildid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) 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(` await dbClient.execute(`
CREATE TABLE guild_clean_channel ( CREATE TABLE guild_clean_channel (
guildId bigint unsigned NOT NULL, guildId bigint unsigned NOT NULL,
@ -84,7 +84,7 @@ await dbClient.execute(`
PRIMARY KEY (guildid, channelId) PRIMARY KEY (guildid, channelId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`); `);
console.log("Table created"); console.log('Table created');
await dbClient.close(); await dbClient.close();
console.log("Done!"); console.log('Done!');

View File

@ -2,11 +2,11 @@
import { import {
// MySQL deps // MySQL deps
Client Client,
} from "../deps.ts"; } from '../deps.ts';
import { LOCALMODE } from "../flags.ts"; import { LOCALMODE } from '../flags.ts';
import config from "../config.ts"; import config from '../config.ts';
// Log into the MySQL DB // Log into the MySQL DB
const dbClient = await new Client().connect({ const dbClient = await new Client().connect({
@ -17,14 +17,14 @@ const dbClient = await new Client().connect({
password: config.db.password, password: config.db.password,
}); });
console.log("Attempting to insert default commands into command_cnt"); console.log('Attempting to insert default commands into command_cnt');
const commands = ["ping", "help", "info", "version", "report", "privacy", "lfg", "prefix"]; const commands = ['ping', 'help', 'info', 'version', 'report', 'privacy', 'lfg', 'prefix'];
for (let i = 0; i < commands.length; i++) { 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(`Failed to insert into database`, e);
}); });
} }
console.log("Insertion done"); console.log('Insertion done');
await dbClient.close(); 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 // All external dependancies are to be loaded here to make updating dependancy versions much easier
export { export {
startBot, editBotStatus, editBotNickname, botId,
Intents, DiscordActivityTypes, DiscordButtonStyles, DiscordInteractionTypes, DiscordInteractionResponseTypes, cache,
sendMessage, sendDirectMessage, sendInteractionResponse, getMessage, deleteMessage, cacheHandlers,
getGuild, getUser, deleteMessage,
DiscordActivityTypes,
DiscordButtonStyles,
DiscordInteractionResponseTypes,
DiscordInteractionTypes,
editBotNickname,
editBotStatus,
getGuild,
getMessage,
getUser,
hasGuildPermissions, hasGuildPermissions,
cache, botId, structures, cacheHandlers Intents,
} from "https://deno.land/x/discordeno@12.0.1/mod.ts"; sendDirectMessage,
sendInteractionResponse,
sendMessage,
startBot,
structures,
} from 'https://deno.land/x/discordeno@12.0.1/mod.ts';
export type { export type {
DiscordenoMessage, DiscordenoMember, DiscordenoGuild, ButtonData, DebugArg, ActionRow,
CreateMessage, Interaction, ButtonComponent, ActionRow, Embed, EmbedField ButtonComponent,
} from "https://deno.land/x/discordeno@12.0.1/mod.ts"; 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';

789
mod.ts

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,6 @@
import { import { ActionRow, DiscordButtonStyles } from '../deps.ts';
DiscordButtonStyles, ActionRow
} from "../deps.ts";
import config from "../config.ts"; import config from '../config.ts';
export const constantCmds = { export const constantCmds = {
help: { help: {
@ -10,49 +8,49 @@ export const constantCmds = {
title: `${config.name} Help`, title: `${config.name} Help`,
fields: [ fields: [
{ {
name: "All commands must have the bot's prefix before them.", name: 'All commands must have the bot\'s prefix before them.',
value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.` value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.`,
}, },
{ {
name: "LFG Commands", name: 'LFG Commands',
value: ` value: `
\`lfg help\` - More detailed help for the LFG commands \`lfg help\` - More detailed help for the LFG commands
\`lfg create\` - Create a new LFG post \`lfg create\` - Create a new LFG post
\`lfg edit\` - Edit an existing LFG post \`lfg edit\` - Edit an existing LFG post
\`lfg delete\` - Delete an existing LFG post \`lfg delete\` - Delete an existing LFG post
` `,
}, },
{ {
name: "Utility Commands", name: 'Utility Commands',
value: ` value: `
\`info\` - Information about the bot \`info\` - Information about the bot
\`ping\` - Pings the bot to check its connection \`ping\` - Pings the bot to check its connection
\`report [TEXT]\` - Report an issue to the developer \`report [TEXT]\` - Report an issue to the developer
\`version\` - Prints the bot's current version \`version\` - Prints the bot's current version
` `,
} },
] ],
}] }],
}, },
lfgHelp: { lfgHelp: {
embeds: [{ embeds: [{
title: `${config.name} LFG Help`, title: `${config.name} LFG Help`,
fields: [ fields: [
{ {
name: "All commands must have the bot's prefix before them.", name: 'All commands must have the bot\'s prefix before them.',
value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.` value: `Default is \`${config.prefix}\`, send <@847256159123013722> to change it.`,
}, },
{ {
name: "lfg create", name: 'lfg create',
value: ` 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. \`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. 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: ` 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. \`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 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. 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: ` value: `
\`lfg delete [id?]\`, alternatively \`lfg d [id?]\`, will delete an existing LFG. You only can delete LFG posts that you own. \`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 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. 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: { info: {
embeds: [{ embeds: [{
fields: [ fields: [
{ {
name: "Group Up, the LFG bot", name: 'Group Up, the LFG bot',
value: `Group Up is developed by Ean AKA Burn_E99. 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). 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: { version: {
embeds: [{ embeds: [{
title: `My current version is ${config.version}` title: `My current version is ${config.version}`,
}] }],
}, },
report: { report: {
embeds: [{ embeds: [{
fields: [ fields: [
{ {
name: "Failed command has been reported to my developer.", 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)." value: 'For more in depth support, and information about planned maintenance, please join the support server [here](https://discord.gg/peHASXMZYv).',
} },
] ],
}] }],
}, },
lfgDelete1: { lfgDelete1: {
embeds: [{ embeds: [{
fields: [ fields: [
{ {
name: "Could not find any LFGs to delete.", 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" value: 'Make sure you are the owner of the LFG and are running this command in the same channel as the LFG',
} },
] ],
}] }],
}, },
lfgDelete2: { lfgDelete2: {
embeds: [{ embeds: [{
fields: [ 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\``, 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: { lfgDelete3: {
embeds: [{ embeds: [{
title: "LFG deleted." title: 'LFG deleted.',
}] }],
}, },
lfgEdit1: { lfgEdit1: {
embeds: [{ embeds: [{
fields: [ fields: [
{ {
name: "Could not find any LFGs to edit.", 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" value: 'Make sure you are the owner of the LFG and are running this command in the same channel as the LFG',
} },
] ],
}] }],
}, },
lfgEdit2: { lfgEdit2: {
embeds: [{ embeds: [{
fields: [ 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\``, 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, type: 2,
label: "Change Game/Activity", label: 'Change Game/Activity',
customId: `editing@set_game`, customId: `editing@set_game`,
style: DiscordButtonStyles.Primary style: DiscordButtonStyles.Primary,
}, },
{ {
type: 2, type: 2,
label: "Change Time", label: 'Change Time',
customId: `editing@set_time`, customId: `editing@set_time`,
style: DiscordButtonStyles.Primary style: DiscordButtonStyles.Primary,
}, },
{ {
type: 2, type: 2,
label: "Change Description", label: 'Change Description',
customId: `editing@set_desc`, customId: `editing@set_desc`,
style: DiscordButtonStyles.Primary style: DiscordButtonStyles.Primary,
} },
]; ];
export const lfgStepQuestions = { export const lfgStepQuestions = {
"set_game": "Please select a game from the list below. If your game is not listed, please type it out:", '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_button':
"set_activity_with_text": "Please type the activity name out:", '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_from_category": "Please select an Activity from the list below.\n\nIf your activity is not listed, please type it out:", 'set_activity_with_text': 'Please type the activity name out:',
"set_player_cnt": "Please enter the max number of members for this activity:", 'set_activity_from_category': 'Please select an Activity from the list below.\n\nIf your activity is not listed, please type it out:',
"set_time": "Please enter the time of the activity:\nRecommended format: `h:mm am/pm tz month/day`", 'set_player_cnt': 'Please enter the max number of members for this activity:',
"set_desc": "Please enter a description for the activity. Enter `none` to skip:", 'set_time': 'Please enter the time of the activity:\nRecommended format: `h:mm am/pm tz month/day`',
"set_done": "Finalizing, please wait. . ." '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 = { export const LFGActivities = {
"Destiny 2": { 'Destiny 2': {
"Raids": { 'Raids': {
"Vow of the Disciple": 6, 'Vow of the Disciple': 6,
"Vault of Glass": 6, 'Vault of Glass': 6,
"Deep Stone Crypt": 6, 'Deep Stone Crypt': 6,
"Garden of Salvation": 6, 'Garden of Salvation': 6,
"Last Wish": 6 'Last Wish': 6,
}, },
"Dungeons": { 'Dungeons': {
"Duality": 3, 'Duality': 3,
"Grasp of Avarice": 3, 'Grasp of Avarice': 3,
"Prophecy": 3, 'Prophecy': 3,
"Pit of Heresy": 3, 'Pit of Heresy': 3,
"Shattered Throne": 3 'Shattered Throne': 3,
}, },
"Crucible": { 'Crucible': {
"Crucible (Control)": 6, 'Crucible (Control)': 6,
"Crucible (Survival)": 3, 'Crucible (Survival)': 3,
"Crucible (Elimination)": 3, 'Crucible (Elimination)': 3,
"Crucible (Private Match)": 12, 'Crucible (Private Match)': 12,
"Iron Banner": 6, 'Iron Banner': 6,
"Trials of Osiris": 3 'Trials of Osiris': 3,
}, },
"Gambit": { 'Gambit': {
"Gambit (Classic)": 4, 'Gambit (Classic)': 4,
"Gambit (Private Match)": 8 'Gambit (Private Match)': 8,
}, },
/* "Exotic Missions": { /* "Exotic Missions": {
// "Presage": 3, // "Presage": 3,
// "Harbinger": 3 // "Harbinger": 3
}, */ }, */
"Nightfall": 3, 'Nightfall': 3,
"Miscellaneous": { 'Miscellaneous': {
"Weekly Witch Queen Campaign Mission": 3, 'Weekly Witch Queen Campaign Mission': 3,
"Wellspring": 6, 'Wellspring': 6,
"Dares of Eternity": 6, 'Dares of Eternity': 6,
// "Astral Alignment": 6, // "Astral Alignment": 6,
// "Shattered Realm": 3, // "Shattered Realm": 3,
// "Override": 6, // "Override": 6,
// "Expunge": 3, // "Expunge": 3,
// "Battlegrounds": 3, // "Battlegrounds": 3,
"Wrathborn Hunt": 3, 'Wrathborn Hunt': 3,
"Empire Hunt": 3, 'Empire Hunt': 3,
"Vanguard Operations": 3 'Vanguard Operations': 3,
// "Nightmare Hunt": 3 // "Nightmare Hunt": 3
}
}, },
"Among Us": { },
"Vanilla": 15, 'Among Us': {
"Modded": 15 'Vanilla': 15,
} 'Modded': 15,
},
}; };

View File

@ -1,22 +1,25 @@
import { import {
// Discordeno deps // Discordeno deps
cache, cache,
sendMessage, getMessage, deleteMessage, sendDirectMessage, deleteMessage,
getGuild, getGuild,
getMessage,
log,
// Log4Deno deps // Log4Deno deps
LT, log LT,
} from "../deps.ts"; sendDirectMessage,
sendMessage,
} from '../deps.ts';
import { jsonStringifyBig } from "./utils.ts"; import { jsonStringifyBig } from './utils.ts';
import { BuildingLFG, ActiveLFG } from "./mod.d.ts"; import { ActiveLFG, BuildingLFG } from './mod.d.ts';
import config from "../config.ts"; import config from '../config.ts';
// getRandomStatus() returns status as string // getRandomStatus() returns status as string
// Gets a new random status for the bot // Gets a new random status for the bot
const getRandomStatus = (cachedGuilds: number): string => { const getRandomStatus = (cachedGuilds: number): string => {
let status = ""; let status = '';
switch (Math.floor((Math.random() * 5) + 1)) { switch (Math.floor((Math.random() * 5) + 1)) {
case 1: case 1:
status = `${config.prefix}help for commands`; status = `${config.prefix}help for commands`;
@ -28,7 +31,7 @@ const getRandomStatus = (cachedGuilds: number): string => {
status = `${config.prefix}info to learn more`; status = `${config.prefix}info to learn more`;
break; break;
case 4: case 4:
status = "Mention me to check my prefix!"; status = 'Mention me to check my prefix!';
break; break;
default: default:
status = `Running LFGs in ${cachedGuilds + cache.dispatchedGuildIds.size} servers`; status = `Running LFGs in ${cachedGuilds + cache.dispatchedGuildIds.size} servers`;
@ -41,22 +44,21 @@ const getRandomStatus = (cachedGuilds: number): string => {
// updateListStatistics(bot ID, current guild count) returns nothing // updateListStatistics(bot ID, current guild count) returns nothing
// Sends the current server count to all bot list sites we are listed on // Sends the current server count to all bot list sites we are listed on
const updateListStatistics = (botID: BigInt, serverCount: number): void => { const updateListStatistics = (botID: BigInt, serverCount: number): void => {
config.botLists.forEach(async e => { config.botLists.forEach(async (e) => {
if (e.enabled) { if (e.enabled) {
log(LT.LOG, `Updating statistics for ${jsonStringifyBig(e)}`); log(LT.LOG, `Updating statistics for ${jsonStringifyBig(e)}`);
try { try {
const tempHeaders = new Headers(); const tempHeaders = new Headers();
tempHeaders.append(e.headers[0].header, e.headers[0].value); 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 // ?{} 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()), { const response = await fetch(e.apiUrl.replace('?{bot_id}', botID.toString()), {
"method": 'POST', 'method': 'POST',
"headers": tempHeaders, '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 '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)}`); 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)}`); log(LT.WARN, `Failed to post statistics to ${e.name} | ${jsonStringifyBig(e)}`);
} }
} }
@ -67,31 +69,29 @@ const buildingTimeout = async (activeBuilders: Array<BuildingLFG>): Promise<void
const currentTime = new Date().getTime(); 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) { 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)}`); log(LT.WARN, `Failed to clean up active builder | edit | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`);
}); });
if (activeBuilders[i].editing) { if (activeBuilders[i].editing) {
activeBuilders[i].lfgMsg.edit({ activeBuilders[i].lfgMsg.edit({
content: "" content: '',
}).catch(e => { }).catch((e) => {
log(LT.WARN, `Failed to clean up active builder | edit | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`); log(LT.WARN, `Failed to clean up active builder | edit | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`);
}); });
} else { } 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)}`); log(LT.WARN, `Failed to clean up active builder | delete | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`);
}); });
} }
try { try {
const m = await sendMessage(activeBuilders[i].channelId, `<@${activeBuilders[i].userId}>, your LFG ${activeBuilders[i].editing ? "editing" : "creation"} has timed out. Please try again.`); 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 =>{ m.delete('Channel Cleanup', 30000).catch((e) => {
log(LT.WARN, `Failed to delete message | ${jsonStringifyBig(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)}`); log(LT.WARN, `Failed to clean up active builder | ${activeBuilders[i].userId}-${activeBuilders[i].channelId} | ${jsonStringifyBig(e)}`);
} } finally {
finally {
activeBuilders.splice(i, 1); activeBuilders.splice(i, 1);
i--; i--;
} }
@ -100,7 +100,7 @@ const buildingTimeout = async (activeBuilders: Array<BuildingLFG>): Promise<void
}; };
const lfgNotifier = async (activeLFGPosts: Array<ActiveLFG>): 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 tenMin = 10 * 60 * 1000;
const now = new Date().getTime(); const now = new Date().getTime();
for (let i = 0; i < activeLFGPosts.length; i++) { for (let i = 0; i < activeLFGPosts.length; i++) {
@ -113,10 +113,10 @@ const lfgNotifier = async (activeLFGPosts: Array<ActiveLFG>): Promise<void> => {
const lfgActivity = `${lfg[0].name.substr(0, lfg[0].name.length - 1)} - ${lfg[0].value}`; 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; const members = lfg[4].value;
let editMsg = ""; let editMsg = '';
members.split("\n").forEach(async m => { members.split('\n').forEach(async (m) => {
if (m !== "None") { if (m !== 'None') {
const [name, tmpId] = m.split(" - <@"); const [name, tmpId] = m.split(' - <@');
const userId = BigInt(tmpId.substr(0, tmpId.length - 1)); const userId = BigInt(tmpId.substr(0, tmpId.length - 1));
editMsg += `<@${userId}>, `; editMsg += `<@${userId}>, `;
await sendDirectMessage(userId, { await sendDirectMessage(userId, {
@ -125,54 +125,48 @@ const lfgNotifier = async (activeLFGPosts: Array<ActiveLFG>): Promise<void> => {
fields: [ fields: [
lfg[0], lfg[0],
{ {
name: "Please start grouping up with the other members of this activity:", name: 'Please start grouping up with the other members of this activity:',
value: members value: members,
} },
] ],
}] }],
}); });
} }
}); });
editMsg += `your ${lfgActivity} starts in less than 10 minutes.`; editMsg += `your ${lfgActivity} starts in less than 10 minutes.`;
await message.edit({ await message.edit({
content: editMsg content: editMsg,
}); });
activeLFGPosts[i].notified = true; activeLFGPosts[i].notified = true;
} } catch (err) {
catch (err) {
log(LT.WARN, `Failed to find LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(err)}`); log(LT.WARN, `Failed to find LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(err)}`);
activeLFGPosts.splice(i, 1); activeLFGPosts.splice(i, 1);
i--; i--;
} }
} } // Lock LFG from editing/Joining/Leaving
// Lock LFG from editing/Joining/Leaving
else if (!activeLFGPosts[i].locked && activeLFGPosts[i].lfgTime < now) { else if (!activeLFGPosts[i].locked && activeLFGPosts[i].lfgTime < now) {
log(LT.INFO, `Locking LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`); log(LT.INFO, `Locking LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`);
try { try {
const message = await getMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId); const message = await getMessage(activeLFGPosts[i].channelId, activeLFGPosts[i].messageId);
await message.edit({ await message.edit({
components: [] components: [],
}); });
activeLFGPosts[i].locked = true; activeLFGPosts[i].locked = true;
} } catch (err) {
catch (err) {
log(LT.WARN, `Failed to find LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(err)}`); log(LT.WARN, `Failed to find LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(err)}`);
activeLFGPosts.splice(i, 1); activeLFGPosts.splice(i, 1);
i--; i--;
} }
} } // Delete old LFG post
// Delete old LFG post
else if (activeLFGPosts[i].lfgTime < (now - tenMin)) { else if (activeLFGPosts[i].lfgTime < (now - tenMin)) {
log(LT.INFO, `Deleting LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid}`); 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)}`); log(LT.WARN, `Failed to delete LFG ${activeLFGPosts[i].ownerId}-${activeLFGPosts[i].lfgUid} | ${jsonStringifyBig(e)}`);
}); });
activeLFGPosts.splice(i, 1); activeLFGPosts.splice(i, 1);
@ -180,7 +174,7 @@ const lfgNotifier = async (activeLFGPosts: Array<ActiveLFG>): Promise<void> => {
} }
} }
localStorage.setItem("activeLFGPosts", jsonStringifyBig(activeLFGPosts)); localStorage.setItem('activeLFGPosts', jsonStringifyBig(activeLFGPosts));
}; };
export default { getRandomStatus, updateListStatistics, buildingTimeout, lfgNotifier }; export default { getRandomStatus, updateListStatistics, buildingTimeout, lfgNotifier };

22
src/lfgHandlers.d.ts vendored
View File

@ -1,16 +1,14 @@
import { import { EmbedField } from '../deps.ts';
EmbedField
} from "../deps.ts";
export type JoinLeaveType = { export type JoinLeaveType = {
embed: EmbedField[], embed: EmbedField[];
success: boolean, success: boolean;
full: boolean, full: boolean;
justFilled: boolean justFilled: boolean;
} };
export type UrlIds = { export type UrlIds = {
guildId: bigint, guildId: bigint;
channelId: bigint, channelId: bigint;
messageId: bigint messageId: bigint;
} };

View File

@ -1,79 +1,75 @@
import { import { ActionRow, ButtonComponent, DiscordButtonStyles, DiscordenoMember, EmbedField, log, LT } from '../deps.ts';
ActionRow, ButtonComponent, DiscordButtonStyles, EmbedField, DiscordenoMember,
LT, log import { JoinLeaveType, UrlIds } from './lfgHandlers.d.ts';
} from "../deps.ts"; import { BuildingLFG } from './mod.d.ts';
import { LFGActivities } from './games.ts';
import { JoinLeaveType, UrlIds } from "./lfgHandlers.d.ts"; import { determineTZ } from './timeUtils.ts';
import { BuildingLFG } from "./mod.d.ts"; import { lfgStepQuestions } from './constantCmds.ts';
import { LFGActivities } from "./games.ts"; import { jsonStringifyBig } from './utils.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> => { export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise<BuildingLFG> => {
const currentLFG = (wipLFG.lfgMsg.embeds[0] || { fields: undefined }).fields || [ const currentLFG = (wipLFG.lfgMsg.embeds[0] || { fields: undefined }).fields || [
{ {
name: ". . .", name: '. . .',
value: ". . .", value: '. . .',
inline: true inline: true,
}, },
{ {
name: "Start Time:", name: 'Start Time:',
value: ". . .", value: '. . .',
inline: true inline: true,
}, },
{ {
name: "Add to Calendar:", name: 'Add to Calendar:',
value: ". . .", value: '. . .',
inline: true inline: true,
}, },
{ {
name: "Description:", name: 'Description:',
value: ". . .", value: '. . .',
inline: false inline: false,
}, },
{ {
name: `Members Joined: 0/?`, name: `Members Joined: 0/?`,
value: "None", value: 'None',
inline: true inline: true,
}, },
{ {
name: "Alternates:", name: 'Alternates:',
value: "None", value: 'None',
inline: true inline: true,
} },
]; ];
let nextQuestion = ""; let nextQuestion = '';
const nextComponents: Array<ActionRow> = []; const nextComponents: Array<ActionRow> = [];
let editFlag = true; let editFlag = true;
switch (wipLFG.step) { switch (wipLFG.step) {
case "set_game": { case 'set_game': {
currentLFG[0].name = input.substr(0, 254); currentLFG[0].name = input.substr(0, 254);
if (Object.prototype.hasOwnProperty.call(LFGActivities, input)) { if (Object.prototype.hasOwnProperty.call(LFGActivities, input)) {
nextQuestion = lfgStepQuestions.set_activity_with_button; nextQuestion = lfgStepQuestions.set_activity_with_button;
let tempObj = {}; let tempObj = {};
Object.entries(LFGActivities).some(e => { Object.entries(LFGActivities).some((e) => {
if (e[0] === input) { if (e[0] === input) {
tempObj = e[1]; tempObj = e[1];
return true; return true;
} }
}); });
const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map(activity => { const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map((activity) => {
return { return {
type: 2, type: 2,
label: activity, label: activity,
customId: `building@set_activity#${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) => { activityButtons.forEach((btn, idx) => {
if (!temp[Math.floor(idx / 5)]) { if (!temp[Math.floor(idx / 5)]) {
@ -83,11 +79,11 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
} }
}); });
temp.forEach(btns => { temp.forEach((btns) => {
if (btns.length && btns.length <= 5) { if (btns.length && btns.length <= 5) {
nextComponents.push({ nextComponents.push({
type: 1, 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; nextQuestion = lfgStepQuestions.set_activity_with_text;
} }
wipLFG.step = "set_activity"; wipLFG.step = 'set_activity';
break; break;
} }
case "set_activity": { case 'set_activity': {
const game = currentLFG[0].name; const game = currentLFG[0].name;
let tempObj; let tempObj;
Object.entries(LFGActivities).some(e => { Object.entries(LFGActivities).some((e) => {
if (e[0] === game) { if (e[0] === game) {
Object.entries(e[1]).some(f => { Object.entries(e[1]).some((f) => {
if (f[0] === input) { if (f[0] === input) {
tempObj = f[1]; tempObj = f[1];
return true; return true;
@ -117,34 +113,34 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
currentLFG[0].name = `${game}:`; currentLFG[0].name = `${game}:`;
currentLFG[0].value = input.substr(0, 1023); currentLFG[0].value = input.substr(0, 1023);
if (typeof tempObj === "number") { if (typeof tempObj === 'number') {
// Activity // 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; 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) { } else if (!tempObj) {
// Custom // Custom
nextQuestion = lfgStepQuestions.set_player_cnt; nextQuestion = lfgStepQuestions.set_player_cnt;
wipLFG.step = "set_player_cnt"; wipLFG.step = 'set_player_cnt';
} else { } else {
// Category // Category
nextQuestion = lfgStepQuestions.set_activity_from_category; nextQuestion = lfgStepQuestions.set_activity_from_category;
currentLFG[0].name = game; currentLFG[0].name = game;
const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map(activity => { const activityButtons: Array<ButtonComponent> = Object.keys(tempObj).map((activity) => {
return { return {
type: 2, type: 2,
label: activity, label: activity,
customId: `building@set_activity_from_category#${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) => { activityButtons.forEach((btn, idx) => {
if (!temp[Math.floor(idx / 5)]) { if (!temp[Math.floor(idx / 5)]) {
@ -154,30 +150,30 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
} }
}); });
temp.forEach(btns => { temp.forEach((btns) => {
if (btns.length && btns.length <= 5) { if (btns.length && btns.length <= 5) {
nextComponents.push({ nextComponents.push({
type: 1, type: 1,
components: btns components: btns,
}); });
} }
}); });
wipLFG.step = "set_activity_from_category"; wipLFG.step = 'set_activity_from_category';
} }
break; break;
} }
case "set_activity_from_category": { case 'set_activity_from_category': {
const game = currentLFG[0].name; const game = currentLFG[0].name;
const category = currentLFG[0].value; const category = currentLFG[0].value;
let tempObj; let tempObj;
Object.entries(LFGActivities).some(e => { Object.entries(LFGActivities).some((e) => {
if (e[0] === game) { if (e[0] === game) {
Object.entries(e[1]).some(f => { Object.entries(e[1]).some((f) => {
if (f[0] === category) { if (f[0] === category) {
Object.entries(f[1]).some(g => { Object.entries(f[1]).some((g) => {
if (g[0] === input) { if (g[0] === input) {
tempObj = g[1]; tempObj = g[1];
return true; return true;
@ -194,62 +190,62 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
currentLFG[0].value = input.substr(0, 1023); currentLFG[0].value = input.substr(0, 1023);
if (tempObj) { if (tempObj) {
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; nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time;
wipLFG.step = wipLFG.editing ? "done" : "set_time"; wipLFG.step = wipLFG.editing ? 'done' : 'set_time';
} else { } else {
nextQuestion = lfgStepQuestions.set_player_cnt; nextQuestion = lfgStepQuestions.set_player_cnt;
wipLFG.step = "set_player_cnt"; wipLFG.step = 'set_player_cnt';
} }
break; break;
} }
case "set_player_cnt": { case 'set_player_cnt': {
if (parseInt(input)) { 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}/${Math.abs(parseInt(input)) || 1}`;
nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time; nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_time;
wipLFG.step = wipLFG.editing ? "done" : "set_time"; wipLFG.step = wipLFG.editing ? 'done' : 'set_time';
} else { } else {
editFlag = false; editFlag = false;
nextQuestion = `Input max members "${input}" is invalid, please make sure you are only entering a number.\n\n${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}`;
} }
break; break;
} }
case "set_time": { case 'set_time': {
const today = new Date(); const today = new Date();
let lfgDate = `${today.getMonth() + 1}/${today.getDate()}`, let lfgDate = `${today.getMonth() + 1}/${today.getDate()}`,
lfgTime = "", lfgTime = '',
lfgTZ = "", lfgTZ = '',
lfgPeriod = "", lfgPeriod = '',
overrodeTZ = false; overrodeTZ = false;
input.split(" ").forEach(c => { input.split(' ').forEach((c) => {
if (c.includes("/")) { if (c.includes('/')) {
lfgDate = c; lfgDate = c;
} else if (c.toLowerCase() === "am" || c.toLowerCase() === "pm") { } else if (c.toLowerCase() === 'am' || c.toLowerCase() === 'pm') {
lfgPeriod = c.toLowerCase(); 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); lfgTime = c.substr(0, c.length - 2);
lfgPeriod = c.toLowerCase().includes("am") ? "am" : "pm"; lfgPeriod = c.toLowerCase().includes('am') ? 'am' : 'pm';
} else if (c.includes(":")) { } else if (c.includes(':')) {
lfgTime = c; 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 (c.length === 4) {
if (parseInt(c) >= 1300) { if (parseInt(c) >= 1300) {
lfgTime = (parseInt(c) - 1200).toString(); lfgTime = (parseInt(c) - 1200).toString();
lfgPeriod = "pm"; lfgPeriod = 'pm';
} else if (parseInt(c) >= 1200) { } else if (parseInt(c) >= 1200) {
lfgTime = c; lfgTime = c;
lfgPeriod = "pm"; lfgPeriod = 'pm';
} else { } else {
lfgTime = c.startsWith("00") ? `12${c.substr(2)}` : c; lfgTime = c.startsWith('00') ? `12${c.substr(2)}` : c;
lfgPeriod = "am"; lfgPeriod = 'am';
} }
const hourLen = lfgTime.length === 4 ? 2 : 1; const hourLen = lfgTime.length === 4 ? 2 : 1;
@ -267,52 +263,54 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
}); });
if (!lfgTZ) { if (!lfgTZ) {
[lfgTZ, overrodeTZ] = determineTZ("ET"); [lfgTZ, overrodeTZ] = determineTZ('ET');
} }
if (!lfgTime.includes(":")) { if (!lfgTime.includes(':')) {
lfgTime += ":00"; lfgTime += ':00';
} }
if (!lfgPeriod) { if (!lfgPeriod) {
lfgPeriod = today.getHours() >= 12 ? "pm" : "am"; lfgPeriod = today.getHours() >= 12 ? 'pm' : 'am';
} }
lfgPeriod = lfgPeriod.toUpperCase(); lfgPeriod = lfgPeriod.toUpperCase();
lfgTZ = lfgTZ.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}`); log(LT.LOG, `Date Time Debug | ${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}`);
const lfgDateTime = new Date(`${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 lfgDateStr = `[${lfgTime} ${lfgPeriod} ${lfgTZ} ${lfgDate}](https://groupup.eanm.dev/tz#${lfgDateTime.getTime()})`;
const icsDetails = `${currentLFG[0].name} ${currentLFG[0].value}`; 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[1].value = lfgDateStr.substr(0, 1023);
currentLFG[2].value = icsStr.substr(0, 1023); currentLFG[2].value = icsStr.substr(0, 1023);
if (isNaN(lfgDateTime.getTime())) { 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; editFlag = false;
} else if (lfgDateTime.getTime() <= today.getTime()) { } 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; editFlag = false;
} else { } else {
nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_desc; nextQuestion = wipLFG.editing ? lfgStepQuestions.set_done : lfgStepQuestions.set_desc;
wipLFG.step = wipLFG.editing ? "done" : "set_desc"; wipLFG.step = wipLFG.editing ? 'done' : 'set_desc';
} }
break; break;
} }
case "set_desc":{ case 'set_desc': {
if (input === "none") { if (input === 'none') {
input = currentLFG[0].value; input = currentLFG[0].value;
} }
@ -320,7 +318,7 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
nextQuestion = lfgStepQuestions.set_done; nextQuestion = lfgStepQuestions.set_done;
wipLFG.step = "done"; wipLFG.step = 'done';
break; break;
} }
default: default:
@ -331,17 +329,16 @@ export const handleLFGStep = async (wipLFG: BuildingLFG, input: string): Promise
if (editFlag) { if (editFlag) {
wipLFG.lfgMsg = await wipLFG.lfgMsg.edit({ wipLFG.lfgMsg = await wipLFG.lfgMsg.edit({
embeds: [{ embeds: [{
fields: currentLFG fields: currentLFG,
}] }],
}); });
} }
wipLFG.questionMsg = await wipLFG.questionMsg.edit({ wipLFG.questionMsg = await wipLFG.questionMsg.edit({
content: nextQuestion, content: nextQuestion,
components: nextComponents components: nextComponents,
}); });
} } catch (e) {
catch (e) {
log(LT.WARN, `Failed to edit active builder | ${wipLFG.userId}-${wipLFG.channelId} | ${jsonStringifyBig(e)}`); log(LT.WARN, `Failed to edit active builder | ${wipLFG.userId}-${wipLFG.channelId} | ${jsonStringifyBig(e)}`);
} }
@ -354,17 +351,17 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al
const userStr = `${member.username} - <@${member.id}>`; 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]); let currentMembers = parseInt(tempMembers[0]);
const maxMembers = parseInt(tempMembers[1]); const maxMembers = parseInt(tempMembers[1]);
if (alternate && !lfg[5].value.includes(member.id.toString())) { if (alternate && !lfg[5].value.includes(member.id.toString())) {
// remove from joined list // remove from joined list
if (lfg[4].value.includes(member.id.toString())) { if (lfg[4].value.includes(member.id.toString())) {
const tempArr = lfg[4].value.split("\n"); const tempArr = lfg[4].value.split('\n');
const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString())); const memberIdx = tempArr.findIndex((m) => m.includes(member.id.toString()));
tempArr.splice(memberIdx, 1) tempArr.splice(memberIdx, 1);
lfg[4].value = tempArr.join("\n") || "None"; lfg[4].value = tempArr.join('\n') || 'None';
if (currentMembers) { if (currentMembers) {
currentMembers--; currentMembers--;
@ -372,7 +369,7 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al
lfg[4].name = `Members Joined: ${currentMembers}/${maxMembers}`; lfg[4].name = `Members Joined: ${currentMembers}/${maxMembers}`;
} }
if (lfg[5].value === "None") { if (lfg[5].value === 'None') {
lfg[5].value = userStr; lfg[5].value = userStr;
} else { } else {
lfg[5].value += `\n${userStr}`; 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())) { } else if (!alternate && currentMembers < maxMembers && !lfg[4].value.includes(member.id.toString())) {
// remove from alternate list // remove from alternate list
if (lfg[5].value.includes(member.id.toString())) { if (lfg[5].value.includes(member.id.toString())) {
const tempArr = lfg[5].value.split("\n"); const tempArr = lfg[5].value.split('\n');
const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString())); const memberIdx = tempArr.findIndex((m) => m.includes(member.id.toString()));
tempArr.splice(memberIdx, 1); 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; lfg[4].value = userStr;
} else { } else {
lfg[4].value += `\n${userStr}`; 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())) { } else if (!alternate && currentMembers === maxMembers && !lfg[4].value.includes(member.id.toString())) {
// update user in alternate list to include the * to make them autojoin // update user in alternate list to include the * to make them autojoin
if (lfg[5].value.includes(member.id.toString())) { if (lfg[5].value.includes(member.id.toString())) {
const tempArr = lfg[5].value.split("\n"); const tempArr = lfg[5].value.split('\n');
const memberIdx = tempArr.findIndex(m => m.includes(member.id.toString())); const memberIdx = tempArr.findIndex((m) => m.includes(member.id.toString()));
tempArr[memberIdx] = `${tempArr[memberIdx]} *`; tempArr[memberIdx] = `${tempArr[memberIdx]} *`;
lfg[5].value = tempArr.join("\n"); lfg[5].value = tempArr.join('\n');
} else { } else {
if (lfg[5].value === "None") { if (lfg[5].value === 'None') {
lfg[5].value = `${userStr} *`; lfg[5].value = `${userStr} *`;
} else { } else {
lfg[5].value += `\n${userStr} *`; lfg[5].value += `\n${userStr} *`;
@ -421,7 +418,7 @@ export const handleMemberJoin = (lfg: EmbedField[], member: DiscordenoMember, al
embed: lfg, embed: lfg,
success: success, success: success,
full: currentMembers === maxMembers, full: currentMembers === maxMembers,
justFilled: justFilled justFilled: justFilled,
}; };
}; };
@ -430,28 +427,28 @@ export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember):
const memberId = member.id.toString(); 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]); let currentMembers = parseInt(tempMembers[0]);
const maxMembers = parseInt(tempMembers[1]); const maxMembers = parseInt(tempMembers[1]);
if (lfg[4].value.includes(memberId)) { if (lfg[4].value.includes(memberId)) {
const tempArr = lfg[4].value.split("\n"); const tempArr = lfg[4].value.split('\n');
const memberIdx = tempArr.findIndex(m => m.includes(memberId)); const memberIdx = tempArr.findIndex((m) => m.includes(memberId));
tempArr.splice(memberIdx, 1); 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 // find first * user and move them to the joined list
const tempArr2 = lfg[5].value.split("\n"); const tempArr2 = lfg[5].value.split('\n');
const memberToMoveIdx = tempArr2.findIndex(m => m.includes("*")) const memberToMoveIdx = tempArr2.findIndex((m) => m.includes('*'));
let memberToMove = tempArr2[memberToMoveIdx]; let memberToMove = tempArr2[memberToMoveIdx];
memberToMove = memberToMove.substr(0, memberToMove.length - 2); memberToMove = memberToMove.substr(0, memberToMove.length - 2);
tempArr.push(memberToMove); tempArr.push(memberToMove);
lfg[4].value = tempArr.join("\n") || "None"; lfg[4].value = tempArr.join('\n') || 'None';
// Remove them from the alt list // Remove them from the alt list
tempArr2.splice(memberToMoveIdx, 1); tempArr2.splice(memberToMoveIdx, 1);
lfg[5].value = tempArr2.join("\n") || "None"; lfg[5].value = tempArr2.join('\n') || 'None';
} else { } else {
// update count since no users were marked as * // update count since no users were marked as *
if (currentMembers) { if (currentMembers) {
@ -464,10 +461,10 @@ export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember):
} }
if (lfg[5].value.includes(memberId)) { if (lfg[5].value.includes(memberId)) {
const tempArr = lfg[5].value.split("\n"); const tempArr = lfg[5].value.split('\n');
const memberIdx = tempArr.findIndex(m => m.includes(memberId)); const memberIdx = tempArr.findIndex((m) => m.includes(memberId));
tempArr.splice(memberIdx, 1); tempArr.splice(memberIdx, 1);
lfg[5].value = tempArr.join("\n") || "None"; lfg[5].value = tempArr.join('\n') || 'None';
success = true; success = true;
} }
@ -476,24 +473,24 @@ export const handleMemberLeave = (lfg: EmbedField[], member: DiscordenoMember):
embed: lfg, embed: lfg,
success: success, success: success,
full: currentMembers === maxMembers, full: currentMembers === maxMembers,
justFilled: false justFilled: false,
}; };
}; };
export const urlToIds = (url: string): UrlIds => { export const urlToIds = (url: string): UrlIds => {
const strIds = { const strIds = {
guildId: "", guildId: '',
channelId: "", channelId: '',
messageId: "" messageId: '',
}; };
url = url.toLowerCase(); 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 { return {
guildId: BigInt(strIds.guildId), guildId: BigInt(strIds.guildId),
channelId: BigInt(strIds.channelId), 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 { import { DiscordenoMessage } from '../deps.ts';
DiscordenoMessage
} from "../deps.ts";
export type BuildingLFG = { export type BuildingLFG = {
userId: bigint, userId: bigint;
channelId: bigint, channelId: bigint;
step: string, step: string;
lfgMsg: DiscordenoMessage, lfgMsg: DiscordenoMessage;
questionMsg: DiscordenoMessage, questionMsg: DiscordenoMessage;
lastTouch: Date, lastTouch: Date;
maxIdle: number, maxIdle: number;
editing: boolean editing: boolean;
} };
export type ActiveLFG = { export type ActiveLFG = {
messageId: bigint, messageId: bigint;
channelId: bigint, channelId: bigint;
ownerId: bigint, ownerId: bigint;
lfgUid: string, lfgUid: string;
lfgTime: number, lfgTime: number;
notified: boolean, notified: boolean;
locked: boolean locked: boolean;
} };
export type GuildPrefixes = { export type GuildPrefixes = {
guildId: bigint, guildId: bigint;
prefix: string prefix: string;
} };
export type GuildModRoles = { export type GuildModRoles = {
guildId: bigint, guildId: bigint;
roleId: bigint roleId: bigint;
} };
export type GuildCleanChannels = { export type GuildCleanChannels = {
guildId: bigint, guildId: bigint;
channelId: bigint channelId: bigint;
} };

View File

@ -2,18 +2,18 @@ export const determineTZ = (tz: string, userOverride = false): [string, boolean]
tz = tz.toUpperCase(); tz = tz.toUpperCase();
let overrode = false; let overrode = false;
const shortHandUSTZ = (tz === "ET" || tz === "CT" || tz === "MT" || tz === "PT"); 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 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)) { if (!userOverride && (shortHandUSTZ || fullUSTZ)) {
const today = new Date(); const today = new Date();
const jan = new Date(today.getFullYear(), 0, 1); const jan = new Date(today.getFullYear(), 0, 1);
const jul = new Date(today.getFullYear(), 6, 1); const jul = new Date(today.getFullYear(), 6, 1);
if (today.getTimezoneOffset() < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset())) { 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`; tz = `${tz.substr(0, 1)}DT`;
} else { } else {
if (tz.includes("D")) overrode = true; if (tz.includes('D')) overrode = true;
tz = `${tz.substr(0, 1)}ST`; tz = `${tz.substr(0, 1)}ST`;
} }
} }

View File

@ -1,6 +1,6 @@
export const jsonParseBig = (input: string) => { export const jsonParseBig = (input: string) => {
return JSON.parse(input, (_key, value) => { 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 BigInt(value.substr(0, value.length - 1));
} }
return value; return value;
@ -8,7 +8,5 @@ export const jsonParseBig = (input: string) => {
}; };
export const jsonStringifyBig = (input: any) => { export const jsonStringifyBig = (input: any) => {
return JSON.stringify(input, (_key, value) => return JSON.stringify(input, (_key, value) => typeof value === 'bigint' ? value.toString() + 'n' : value);
typeof value === "bigint" ? value.toString() + "n" : value
);
}; };