1
1
mirror of https://github.com/Burn-E99/GroupUp.git synced 2026-01-06 19:37:54 -05:00

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