From e3217fa0e7a952a731c2440d130792fbfa9af16d Mon Sep 17 00:00:00 2001 From: Sven Date: Mon, 5 Sep 2022 23:36:43 +0200 Subject: [PATCH 01/51] feat: start working on /poll --- src/commands/index.ts | 2 + src/commands/util/Poll.ts | 36 ++++++++++++++ src/modals/poll.ts | 98 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+) create mode 100644 src/commands/util/Poll.ts create mode 100644 src/modals/poll.ts diff --git a/src/commands/index.ts b/src/commands/index.ts index e4bcdfc..d9d55bf 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -23,6 +23,7 @@ import { Emoji } from "@commands/util/Emoji"; import { Exec } from "@commands/util/Exec"; import { Help } from "@commands/util/Help"; import { Ping } from "@commands/util/Ping"; +import { Poll } from "@commands/util/Poll"; import { Reminder } from "@commands/util/Reminder"; import { Server } from "@commands/util/Server"; import { Translate } from "@commands/util/Translate"; @@ -82,6 +83,7 @@ export const commands = [ Exec, Help, Ping, + Poll, Reminder, Server, Translate, diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts new file mode 100644 index 0000000..5653384 --- /dev/null +++ b/src/commands/util/Poll.ts @@ -0,0 +1,36 @@ +import { ApplicationCommandOptionType, CommandInteraction } from "discord.js"; +import { Command } from "@src/Command"; +import { CreatePollModal } from "@src/modals/poll"; + +export class Poll extends Command +{ + constructor() + { + super({ + name: "poll", + desc: "This command allows you to create reaction-based polls that users can vote on", + category: "util", + subcommands: [ + { + name: "create", + desc: "Creates a reaction-based poll in this channel", + args: [ + { + name: "headline", + desc: "Enter pings and extra explanatory text to notify users of this poll.", + type: ApplicationCommandOptionType.String, + } + ], + }, + ], + }); + } + + async run(int: CommandInteraction): Promise + { + const headline = int.options.get("headline")?.value as string | undefined; + const modal = new CreatePollModal(true, headline); + + return await int.showModal(modal.getInternalModal()); + } +} diff --git a/src/modals/poll.ts b/src/modals/poll.ts new file mode 100644 index 0000000..0131614 --- /dev/null +++ b/src/modals/poll.ts @@ -0,0 +1,98 @@ +import { EmbedBuilder, Message, MessageOptions, ModalSubmitInteraction, TextInputBuilder, TextInputStyle } from "discord.js"; + +import { Modal } from "@utils/Modal"; +import { settings } from "@src/settings"; +import { embedify } from "@src/utils"; + +export class CreatePollModal extends Modal +{ + private ephemeral; + private headline; + + constructor(ephemeral: boolean, headline?: string) + { + super({ + title: "Create a poll", + inputs: [ + new TextInputBuilder() + .setCustomId("topic") + .setLabel("Topic of the poll") + .setPlaceholder("The topic you want the users to vote on.\nSupports Discord's Markdown.") + .setStyle(TextInputStyle.Paragraph) + .setRequired(true), + new TextInputBuilder() + .setCustomId("expiry_date_time") + .setLabel("Poll end date and time") + .setPlaceholder("The end date and time of the poll in the format YYYY/MM/DD hh:mm:ss UTC") + .setStyle(TextInputStyle.Short) + .setRequired(true), + new TextInputBuilder() + .setCustomId("vote_options") + .setLabel("Vote options") + .setPlaceholder(`The options the users can choose.\n- One option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) + .setStyle(TextInputStyle.Short) + .setRequired(true), + ], + }); + + this.ephemeral = ephemeral; + this.headline = headline; + } + + async submit(int: ModalSubmitInteraction<"cached">): Promise { + const { guild, channel } = int; + + if(!guild || !channel) + return this.reply(int, embedify("Please use this command in a server.", settings.embedColors.error), true); + + const topic = int.fields.getTextInputValue("topic").trim(); + const expiry = int.fields.getTextInputValue("expiry_date_time").trim(); + const voteOptions = int.fields.getTextInputValue("vote_options").trim().split(/\n/gm).filter(v => v.length > 0); + const headline = this.headline; + + if(!expiry.match(/^\s*(\d{4}\/\d{2}\/\d{2})[\s.,_](\d{2}:\d{2}:\d{2})\s*$/)) + return this.reply(int, embedify("Please enter a topic that the users should vote on.", settings.embedColors.error), true); + if(voteOptions.length > settings.emojiList.length) + return this.reply(int, embedify(`Please enter ${settings.emojiList.length} vote options at most.`, settings.embedColors.error), true); + + const descOptions = voteOptions.reduce((a, c, i) => `${a}\n${settings.emojiList[i]} - ${c}`, ""); + + const ebd = new EmbedBuilder() + .setTitle("Poll") + .setDescription(`This poll was created to vote about:\n\`\`\`\n${topic}\`\`\`\n\nYour options are:${descOptions}`) + .setFields() + .setColor(settings.embedColors.default); + + await this.deferReply(int, true); + + // send messages & react + const voteOpts = voteOptions.map((value, i) => ({ emoji: settings.emojiList[i], value })); + const voteRows: Record<"emoji" | "value", string>[][] = []; + + while(voteOptions.length > 0) + voteRows.push(voteOpts.splice(0, 10)); + + const msgs: Message[] = []; + + const firstMsgOpts: MessageOptions = {}; + if(headline) + firstMsgOpts.content = headline; + msgs.push(await channel.send({ ...firstMsgOpts, embeds: [ebd] })); + + for await(const { emoji } of voteRows[0]) + await msgs[0].react(emoji); + + let i = 1; + for await(const row of voteRows) + { + msgs.push(await channel.send({ content: "\u200B" })); + for await(const { emoji } of row) + await msgs[i].react(emoji); + i++; + } + + // TODO: collectors + + return this.editReply(int, embedify("Successfully started a poll in this channel.")); + } +} From b4b7c1de12da8b122e76313c54cebc131df63ff1 Mon Sep 17 00:00:00 2001 From: Sven Date: Mon, 5 Sep 2022 23:47:41 +0200 Subject: [PATCH 02/51] pagarafe --- src/modals/poll.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 0131614..1b987a7 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -30,7 +30,7 @@ export class CreatePollModal extends Modal .setCustomId("vote_options") .setLabel("Vote options") .setPlaceholder(`The options the users can choose.\n- One option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) - .setStyle(TextInputStyle.Short) + .setStyle(TextInputStyle.Paragraph) .setRequired(true), ], }); From 1dc048106d5c432dfaf451e7a73eeaad5d4d91c7 Mon Sep 17 00:00:00 2001 From: Sven Date: Mon, 5 Sep 2022 23:51:17 +0200 Subject: [PATCH 03/51] i am --- src/modals/poll.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 1b987a7..549a982 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -23,13 +23,13 @@ export class CreatePollModal extends Modal new TextInputBuilder() .setCustomId("expiry_date_time") .setLabel("Poll end date and time") - .setPlaceholder("The end date and time of the poll in the format YYYY/MM/DD hh:mm:ss UTC") + .setPlaceholder("YYYY/MM/DD hh:mm:ss (UTC Timezone)") .setStyle(TextInputStyle.Short) .setRequired(true), new TextInputBuilder() .setCustomId("vote_options") .setLabel("Vote options") - .setPlaceholder(`The options the users can choose.\n- One option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) + .setPlaceholder(`The options the users can choose.\nOne option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) .setStyle(TextInputStyle.Paragraph) .setRequired(true), ], @@ -51,7 +51,7 @@ export class CreatePollModal extends Modal const headline = this.headline; if(!expiry.match(/^\s*(\d{4}\/\d{2}\/\d{2})[\s.,_](\d{2}:\d{2}:\d{2})\s*$/)) - return this.reply(int, embedify("Please enter a topic that the users should vote on.", settings.embedColors.error), true); + return this.reply(int, embedify("Please make sure the poll end date and time are formatted like this (in UTC time):\n```YYYY/MM/DD hh:mm:ss```", settings.embedColors.error), true); if(voteOptions.length > settings.emojiList.length) return this.reply(int, embedify(`Please enter ${settings.emojiList.length} vote options at most.`, settings.embedColors.error), true); From c8e23d3b27e4742bc8ce1853a4b8f4d5da2773c7 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 00:23:14 +0200 Subject: [PATCH 04/51] feat: poll db stuff --- prisma/schema.prisma | 15 ++++++++++++++ src/commands/util/Poll.ts | 8 +++++++- src/database/guild.ts | 42 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index be10a6f..fa68672 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -81,6 +81,7 @@ model Guild { premium Boolean? @default(false) lastLogColor String? contests Contest[] + polls Poll[] GuildSettings GuildSettings? @relation(fields: [id], references: [guildId], onDelete: Cascade) } @@ -96,6 +97,20 @@ model GuildSettings { Guild Guild[] } +model Poll { + pollId Int + guildId String + channel String + createdBy String + headline String? + topic String + voteOptions String[] + dueTimestamp DateTime + Guild Guild @relation(fields: [guildId], references: [id]) + + @@id([pollId, guildId]) +} + //#MARKER contest model Contest { id Int diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 5653384..f523f8f 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -19,7 +19,13 @@ export class Poll extends Command name: "headline", desc: "Enter pings and extra explanatory text to notify users of this poll.", type: ApplicationCommandOptionType.String, - } + }, + // TODO: + // { + // name: "allow_rethinking", + // desc: "Set this to false to disallow people to change their mind and choose another option.", + // type: ApplicationCommandOptionType.Boolean, + // }, ], }, ], diff --git a/src/database/guild.ts b/src/database/guild.ts index ea4c92f..9321c01 100644 --- a/src/database/guild.ts +++ b/src/database/guild.ts @@ -1,5 +1,5 @@ import { prisma } from "@database/client"; -import { Guild, GuildSettings } from "@prisma/client"; +import { Guild, GuildSettings, Poll } from "@prisma/client"; //#MARKER guild @@ -96,3 +96,43 @@ export function getMultipleGuildSettings(guildIds: string[]) }, }); } + +export function getPolls(guildId: string) +{ + return prisma.poll.findMany({ + where: { + guildId, + }, + }); +} + +export function getPoll(guildId: string, pollId: number) +{ + return prisma.poll.findUnique({ + where: { + pollId_guildId: { + guildId, + pollId, + }, + }, + }); +} + +export function createNewPoll(poll: Poll) +{ + return prisma.poll.create({ + data: poll, + }); +} + +export function deletePoll(guildId: string, pollId: number) +{ + return prisma.poll.delete({ + where: { + pollId_guildId: { + guildId, + pollId, + }, + }, + }); +} From 0855e4100a1882e48d61dd9943f19d46961938f8 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 00:52:08 +0200 Subject: [PATCH 05/51] refactor: better warning text --- src/commands/mod/Warning.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/mod/Warning.ts b/src/commands/mod/Warning.ts index e628aaa..b65e32f 100644 --- a/src/commands/mod/Warning.ts +++ b/src/commands/mod/Warning.ts @@ -172,7 +172,7 @@ export class Warning extends Command const headerEbd = new EmbedBuilder() .setTitle("You've received a warning") - .setDescription(`You have been warned in the server [${guild.name}](https://discord.com/channels/${guild.id})\n**Reason:** ${reason}\n\nYou have been warned ${allWarnings.length} time${allWarnings.length === 1 ? "" : "s"} in this server.`) + .setDescription(`You have been warned in the server [${guild.name}](https://discord.com/channels/${guild.id})\n**Reason:** ${reason}\n\n${allWarnings.length === 1 ? "This is your first warning" : `You have been warned ${allWarnings.length} times`} in this server.`) .setFooter({ text: "If you have questions, please contact the moderators of the server." }) .setColor(settings.embedColors.warning); From a8e077c707e67e5d5b8ab8e4816e46b33e17fac5 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 00:52:50 +0200 Subject: [PATCH 06/51] feat: /poll list --- src/commands/util/Poll.ts | 84 +++++++++++++++++++++++++++++++++++---- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index f523f8f..c3436d2 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,6 +1,10 @@ -import { ApplicationCommandOptionType, CommandInteraction } from "discord.js"; +import { ApplicationCommandOptionType, CommandInteraction, CommandInteractionOption, EmbedBuilder, PermissionFlagsBits } from "discord.js"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; +import { embedify, PageEmbed, toUnix10, truncStr } from "@src/utils"; +import { settings } from "@src/settings"; +import { getPolls } from "@src/database/guild"; +import { halves } from "svcorelib"; export class Poll extends Command { @@ -13,11 +17,11 @@ export class Poll extends Command subcommands: [ { name: "create", - desc: "Creates a reaction-based poll in this channel", + desc: "Creates a poll in this channel", args: [ { name: "headline", - desc: "Enter pings and extra explanatory text to notify users of this poll.", + desc: "Enter pings (be mindful of who you ping) and extra explanatory text to notify users of this poll.", type: ApplicationCommandOptionType.String, }, // TODO: @@ -28,15 +32,81 @@ export class Poll extends Command // }, ], }, + { + name: "list", + desc: "Lists all polls that are active on this server", + }, + // { + // name: "cancel", + // desc: "Cancels a poll", + // perms: [PermissionFlagsBits.ManageChannels], + // }, ], }); } - async run(int: CommandInteraction): Promise + async run(int: CommandInteraction, opt: CommandInteractionOption): Promise { - const headline = int.options.get("headline")?.value as string | undefined; - const modal = new CreatePollModal(true, headline); + const { guild, channel } = int; + + if(!guild || !channel) + return this.reply(int, embedify("Please use this command in a server.", settings.embedColors.error), true); + + switch(opt.name) + { + case "create": + { + const headline = int.options.get("headline")?.value as string | undefined; + const modal = new CreatePollModal(true, headline); + + return await int.showModal(modal.getInternalModal()); + } + case "list": + { + await this.deferReply(int); + + const polls = await getPolls(guild.id); + + if(!polls || polls.length === 0) + return this.editReply(int, embedify("Currently no polls are active on this server.\nYou can create a new one with `/poll create`", settings.embedColors.error)); + + const pollList = [...polls]; + const pages: EmbedBuilder[] = []; + const pollsPerPage = 20; + const totalPages = Math.ceil(polls.length / pollsPerPage); + + while(pollList.length > 0) + { + const pollSlices = halves(pollList.splice(0, pollsPerPage)); + + const ebd = new EmbedBuilder() + .setTitle("Active polls") + .setColor(settings.embedColors.default) + .addFields(pollSlices.map(sl => + ({ name: "\u200B", value: sl.reduce((a, c) => `${a}\n\n> **${truncStr(c.topic, 32)}**\n> By <@${c.createdBy}> in <#${c.channel}>\nExpires `, "") }) + )); + + totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages})` }); + + pages.push(ebd); + } + + if(pages.length > 1) + { + const pe = new PageEmbed(pages, int.user.id, { + allowAllUsersTimeout: 60 * 1000, + goToPageBtn: pages.length > 5, + }); - return await int.showModal(modal.getInternalModal()); + return pe.useInt(int); + } + else + return this.editReply(int, pages[0]); + } + case "cancel": + { + return; + } + } } } From ce729bcc88f7f613a4ab5e8ccd9d4b2b0a1c3a60 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 01:31:38 +0200 Subject: [PATCH 07/51] feat: more poll stoof --- prisma/schema.prisma | 1 + src/commands/util/Poll.ts | 14 +++++++++++++- src/modals/poll.ts | 30 +++++++++++++++++++++++++++++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index fa68672..334090d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -101,6 +101,7 @@ model Poll { pollId Int guildId String channel String + messages String[] createdBy String headline String? topic String diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index c3436d2..d5deda4 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,4 +1,4 @@ -import { ApplicationCommandOptionType, CommandInteraction, CommandInteractionOption, EmbedBuilder, PermissionFlagsBits } from "discord.js"; +import { ApplicationCommandOptionType, CommandInteraction, CommandInteractionOption, EmbedBuilder } from "discord.js"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; import { embedify, PageEmbed, toUnix10, truncStr } from "@src/utils"; @@ -8,6 +8,8 @@ import { halves } from "svcorelib"; export class Poll extends Command { + private interval: NodeJS.Timer; + constructor() { super({ @@ -43,6 +45,9 @@ export class Poll extends Command // }, ], }); + + this.checkPolls(); + this.interval = setInterval(this.checkPolls, 1000); } async run(int: CommandInteraction, opt: CommandInteractionOption): Promise @@ -105,8 +110,15 @@ export class Poll extends Command } case "cancel": { + // TODO: return; } } } + + async checkPolls() + { + // TODO: check for expired polls + void 0; + } } diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 549a982..0aa9667 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -3,6 +3,7 @@ import { EmbedBuilder, Message, MessageOptions, ModalSubmitInteraction, TextInpu import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; import { embedify } from "@src/utils"; +import { createNewPoll, getPolls } from "@src/database/guild"; export class CreatePollModal extends Modal { @@ -50,11 +51,15 @@ export class CreatePollModal extends Modal const voteOptions = int.fields.getTextInputValue("vote_options").trim().split(/\n/gm).filter(v => v.length > 0); const headline = this.headline; - if(!expiry.match(/^\s*(\d{4}\/\d{2}\/\d{2})[\s.,_](\d{2}:\d{2}:\d{2})\s*$/)) + if(!expiry.match(/^\s*\d{4}\/\d{2}\/\d{2}[\s.,_]\d{2}:\d{2}:\d{2}\s*$/)) return this.reply(int, embedify("Please make sure the poll end date and time are formatted like this (in UTC time):\n```YYYY/MM/DD hh:mm:ss```", settings.embedColors.error), true); if(voteOptions.length > settings.emojiList.length) return this.reply(int, embedify(`Please enter ${settings.emojiList.length} vote options at most.`, settings.embedColors.error), true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, ...rest] = /^\s*(\d{4})\/(\d{2})\/(\d{2})[\s.,_](\d{2}):(\d{2}):(\d{2})\s*$/.exec(expiry) as string[]; + + const dueTimestamp = new Date(...(rest.map(v => parseInt(v))) as [number]); const descOptions = voteOptions.reduce((a, c, i) => `${a}\n${settings.emojiList[i]} - ${c}`, ""); const ebd = new EmbedBuilder() @@ -91,6 +96,29 @@ export class CreatePollModal extends Modal i++; } + const allPolls = await getPolls(guild.id); + + let pollId = 1; + if(allPolls && allPolls.length) + { + allPolls.forEach(p => { + if(p.pollId >= pollId) + pollId = p.pollId + 1; + }); + } + + await createNewPoll({ + pollId, + guildId: guild.id, + channel: channel.id, + messages: msgs.map(m => m.id), + createdBy: int.user.id, + headline: headline ?? null, + topic, + voteOptions, + dueTimestamp, + }); + // TODO: collectors return this.editReply(int, embedify("Successfully started a poll in this channel.")); From 7bdba0c7b54690933d75b56a57ffd7db657c2800 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 02:04:11 +0200 Subject: [PATCH 08/51] feat: more poll stuffs --- src/commands/util/Poll.ts | 20 ++++++++++++++------ src/database/guild.ts | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index d5deda4..0e3e02b 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -3,7 +3,7 @@ import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; import { embedify, PageEmbed, toUnix10, truncStr } from "@src/utils"; import { settings } from "@src/settings"; -import { getPolls } from "@src/database/guild"; +import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import { halves } from "svcorelib"; export class Poll extends Command @@ -87,9 +87,13 @@ export class Poll extends Command const ebd = new EmbedBuilder() .setTitle("Active polls") .setColor(settings.embedColors.default) - .addFields(pollSlices.map(sl => - ({ name: "\u200B", value: sl.reduce((a, c) => `${a}\n\n> **${truncStr(c.topic, 32)}**\n> By <@${c.createdBy}> in <#${c.channel}>\nExpires `, "") }) - )); + .addFields(pollSlices + .filter(sl => sl && sl.length > 0) + .map(sl => ({ + name: "\u200B", + value: sl.reduce((a, c) => `${a}\n\n> **\`${c.pollId}\` - ${truncStr(c.topic.replace(/\n+/gm, " "), 64)}**\n> By <@${c.createdBy}> - **open <:open_in_browser:994648843331309589>**\nPoll ends `, "") + })) + ); totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages})` }); @@ -118,7 +122,11 @@ export class Poll extends Command async checkPolls() { - // TODO: check for expired polls - void 0; + const expPolls = await getExpiredPolls(); + + expPolls.forEach(({ guildId, pollId }) => { + // TODO: display conclusion message & final vote numbers + deletePoll(guildId, pollId); + }); } } diff --git a/src/database/guild.ts b/src/database/guild.ts index 9321c01..ab9f2ba 100644 --- a/src/database/guild.ts +++ b/src/database/guild.ts @@ -97,6 +97,8 @@ export function getMultipleGuildSettings(guildIds: string[]) }); } +//#SECTION polls + export function getPolls(guildId: string) { return prisma.poll.findMany({ @@ -118,6 +120,20 @@ export function getPoll(guildId: string, pollId: number) }); } +export function getExpiredPolls() +{ + return prisma.poll.findMany({ + where: { + dueTimestamp: { + lt: new Date(), + }, + }, + orderBy: { + dueTimestamp: "asc", + }, + }); +} + export function createNewPoll(poll: Poll) { return prisma.poll.create({ From c4dc9fd75e93680cc134f813b9e8323cb3a847cf Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 13:37:29 +0200 Subject: [PATCH 09/51] feat: more poll stuff --- prisma/schema.prisma | 2 +- src/commands/util/Poll.ts | 19 +++-- src/commands/util/Reminder.ts | 2 +- src/modals/poll.ts | 150 ++++++++++++++++++++-------------- 4 files changed, 105 insertions(+), 68 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 334090d..be8e541 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -104,7 +104,7 @@ model Poll { messages String[] createdBy String headline String? - topic String + topic String? voteOptions String[] dueTimestamp DateTime Guild Guild @relation(fields: [guildId], references: [id]) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 0e3e02b..9379024 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -5,10 +5,11 @@ import { embedify, PageEmbed, toUnix10, truncStr } from "@src/utils"; import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import { halves } from "svcorelib"; +import k from "kleur"; export class Poll extends Command { - private interval: NodeJS.Timer; + private interval?: NodeJS.Timer; constructor() { @@ -45,9 +46,16 @@ export class Poll extends Command // }, ], }); + + try { + this.checkPolls(); + this.interval = setInterval(this.checkPolls, 2000); + } + catch(err) { + console.error(k.red("Error while checking polls:"), err); + } - this.checkPolls(); - this.interval = setInterval(this.checkPolls, 1000); + ["SIGINT", "SIGTERM"].forEach(sig => process.on(sig, () => clearInterval(this.interval))); } async run(int: CommandInteraction, opt: CommandInteractionOption): Promise @@ -61,8 +69,7 @@ export class Poll extends Command { case "create": { - const headline = int.options.get("headline")?.value as string | undefined; - const modal = new CreatePollModal(true, headline); + const modal = new CreatePollModal(int.options.get("headline")?.value as string | undefined); return await int.showModal(modal.getInternalModal()); } @@ -91,7 +98,7 @@ export class Poll extends Command .filter(sl => sl && sl.length > 0) .map(sl => ({ name: "\u200B", - value: sl.reduce((a, c) => `${a}\n\n> **\`${c.pollId}\` - ${truncStr(c.topic.replace(/\n+/gm, " "), 64)}**\n> By <@${c.createdBy}> - **open <:open_in_browser:994648843331309589>**\nPoll ends `, "") + value: sl.reduce((a, c) => `${a}\n\n> **\`${c.pollId}\` - ${c.topic ? `${truncStr(c.topic.replace(/\n+/gm, " "), 64)}**\n> ` : ""}By <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - **open <:open_in_browser:994648843331309589>**\nPoll ends `, "") })) ); diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index 9ca3824..7a31cdd 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -104,7 +104,7 @@ export class Reminder extends Command { // since the constructor is called exactly once at startup, this should work just fine this.checkReminders(client); - setInterval(() => this.checkReminders(client), 1000); + setInterval(() => this.checkReminders(client), 2000); } catch(err) { diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 0aa9667..daedb63 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -3,14 +3,13 @@ import { EmbedBuilder, Message, MessageOptions, ModalSubmitInteraction, TextInpu import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; import { embedify } from "@src/utils"; -import { createNewPoll, getPolls } from "@src/database/guild"; +import { createNewGuild, createNewPoll, getGuild, getPolls } from "@src/database/guild"; export class CreatePollModal extends Modal { - private ephemeral; private headline; - constructor(ephemeral: boolean, headline?: string) + constructor(headline?: string) { super({ title: "Create a poll", @@ -18,25 +17,28 @@ export class CreatePollModal extends Modal new TextInputBuilder() .setCustomId("topic") .setLabel("Topic of the poll") - .setPlaceholder("The topic you want the users to vote on.\nSupports Discord's Markdown.") + .setPlaceholder("The topic of the poll.\nLeave empty if you sent your own message.\nSupports Discord's Markdown.") .setStyle(TextInputStyle.Paragraph) - .setRequired(true), + .setMaxLength(250) + .setRequired(false), new TextInputBuilder() .setCustomId("expiry_date_time") .setLabel("Poll end date and time") - .setPlaceholder("YYYY/MM/DD hh:mm:ss (UTC Timezone)") + .setPlaceholder("YYYY-MM-DD hh:mm (24h, UTC, for today remove date)") + .setMinLength(3) + .setMaxLength(16) .setStyle(TextInputStyle.Short) .setRequired(true), new TextInputBuilder() .setCustomId("vote_options") .setLabel("Vote options") .setPlaceholder(`The options the users can choose.\nOne option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) + .setMaxLength(Math.min(settings.emojiList.length * 50, 5000)) .setStyle(TextInputStyle.Paragraph) .setRequired(true), ], }); - this.ephemeral = ephemeral; this.headline = headline; } @@ -44,83 +46,111 @@ export class CreatePollModal extends Modal const { guild, channel } = int; if(!guild || !channel) - return this.reply(int, embedify("Please use this command in a server.", settings.embedColors.error), true); + return; // already handled in the poll command const topic = int.fields.getTextInputValue("topic").trim(); const expiry = int.fields.getTextInputValue("expiry_date_time").trim(); const voteOptions = int.fields.getTextInputValue("vote_options").trim().split(/\n/gm).filter(v => v.length > 0); const headline = this.headline; - if(!expiry.match(/^\s*\d{4}\/\d{2}\/\d{2}[\s.,_]\d{2}:\d{2}:\d{2}\s*$/)) - return this.reply(int, embedify("Please make sure the poll end date and time are formatted like this (in UTC time):\n```YYYY/MM/DD hh:mm:ss```", settings.embedColors.error), true); + const longFmtRe = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}[\s.,_T]\d{1,2}:\d{1,2}(:\d{1,2})?$/, + shortFmtRe = /^\d{1,2}:\d{1,2}(:\d{1,2})?$/; + + if(!expiry.match(longFmtRe) && !expiry.match(shortFmtRe)) + return this.reply(int, embedify("Please make sure the poll end date and time are formatted in one of these formats (24 hours, in UTC / GMT+0 time):\n- `YYYY/MM/DD hh:mm`\n- `hh:mm` (today)", settings.embedColors.error), true); if(voteOptions.length > settings.emojiList.length) return this.reply(int, embedify(`Please enter ${settings.emojiList.length} vote options at most.`, settings.embedColors.error), true); + if(voteOptions.length < 2) + return this.reply(int, embedify("Please enter at least two options to vote on.", settings.embedColors.error), true); // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [_, ...rest] = /^\s*(\d{4})\/(\d{2})\/(\d{2})[\s.,_](\d{2}):(\d{2}):(\d{2})\s*$/.exec(expiry) as string[]; + const [_, ...rest] = (expiry.match(longFmtRe) + ? /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})[\s.,_T](\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) + : /^(\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) + )?.filter(v => v) as string[]; + + const d = new Date(), + today = rest.length > 4 ? [] : [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]; - const dueTimestamp = new Date(...(rest.map(v => parseInt(v))) as [number]); + const timeParts = [...today, ...rest.map(v => parseInt(v))] as [number]; + + const dueTimestamp = new Date(...timeParts); const descOptions = voteOptions.reduce((a, c, i) => `${a}\n${settings.emojiList[i]} - ${c}`, ""); + if(dueTimestamp.getTime() < Date.now() + 1000 * 30) + return this.reply(int, embedify("Please enter a date and time that is at least one minute from now.", settings.embedColors.error), true); + const ebd = new EmbedBuilder() .setTitle("Poll") - .setDescription(`This poll was created to vote about:\n\`\`\`\n${topic}\`\`\`\n\nYour options are:${descOptions}`) + .setDescription(`${topic.length > 0 ? `This poll was created to vote about:\n${topic}\n\nYour options are:\n` : ""}${descOptions}`) .setFields() .setColor(settings.embedColors.default); await this.deferReply(int, true); // send messages & react - const voteOpts = voteOptions.map((value, i) => ({ emoji: settings.emojiList[i], value })); - const voteRows: Record<"emoji" | "value", string>[][] = []; - - while(voteOptions.length > 0) - voteRows.push(voteOpts.splice(0, 10)); - - const msgs: Message[] = []; - - const firstMsgOpts: MessageOptions = {}; - if(headline) - firstMsgOpts.content = headline; - msgs.push(await channel.send({ ...firstMsgOpts, embeds: [ebd] })); - - for await(const { emoji } of voteRows[0]) - await msgs[0].react(emoji); - - let i = 1; - for await(const row of voteRows) + try { - msgs.push(await channel.send({ content: "\u200B" })); - for await(const { emoji } of row) - await msgs[i].react(emoji); - i++; - } - - const allPolls = await getPolls(guild.id); + const voteOpts = voteOptions.map((value, i) => ({ emoji: settings.emojiList[i], value })); + const voteRows: Record<"emoji" | "value", string>[][] = []; + + while(voteOpts.length > 0) + voteRows.push(voteOpts.splice(0, 10)); + + const msgs: Message[] = []; + + const firstMsgOpts: MessageOptions = {}; + if(headline) + firstMsgOpts.content = headline; + msgs.push(await channel.send({ ...firstMsgOpts, embeds: [ebd] })); + + for await(const { emoji } of voteRows.shift()!) + await msgs[0].react(emoji); + + let i = 1; + for(const row of voteRows) + { + channel.send({ content: "\u200B" }).then(async msg => { + msgs.push(msg); + for await(const { emoji } of row) + await msgs[i].react(emoji); + i++; + }); + } + + const dbGld = await getGuild(guild.id); + + if(!dbGld) + await createNewGuild(guild.id); + + const allPolls = await getPolls(guild.id); + + let pollId = 1; + if(allPolls && allPolls.length) + { + allPolls.forEach(p => { + if(p.pollId >= pollId) + pollId = p.pollId + 1; + }); + } + + await createNewPoll({ + pollId, + guildId: guild.id, + channel: channel.id, + messages: msgs.map(m => m.id), + createdBy: int.user.id, + headline: headline ?? null, + topic: topic.length > 0 ? topic : null, + voteOptions, + dueTimestamp, + }); - let pollId = 1; - if(allPolls && allPolls.length) + return this.editReply(int, embedify("Successfully created a poll in this channel.")); + } + catch(err) { - allPolls.forEach(p => { - if(p.pollId >= pollId) - pollId = p.pollId + 1; - }); + return this.editReply(int, embedify(`Couldn't create a poll due to an error: ${err}`, settings.embedColors.error)); } - - await createNewPoll({ - pollId, - guildId: guild.id, - channel: channel.id, - messages: msgs.map(m => m.id), - createdBy: int.user.id, - headline: headline ?? null, - topic, - voteOptions, - dueTimestamp, - }); - - // TODO: collectors - - return this.editReply(int, embedify("Successfully started a poll in this channel.")); } } From 8ca408eb9a8854afebd26ea7adaa8af8ee4929d9 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 6 Sep 2022 15:47:26 +0200 Subject: [PATCH 10/51] lots of shit --- prisma/schema.prisma | 1 + src/commands/util/Poll.ts | 109 ++++++++++++++++++++++++++++------ src/commands/util/Reminder.ts | 15 +---- src/modals/poll.ts | 34 +++++++++-- src/utils/time.ts | 15 +++++ 5 files changed, 137 insertions(+), 37 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index be8e541..35d6c0e 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -106,6 +106,7 @@ model Poll { headline String? topic String? voteOptions String[] + votesPerUser Int dueTimestamp DateTime Guild Guild @relation(fields: [guildId], references: [id]) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 9379024..7c7567f 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,17 +1,17 @@ -import { ApplicationCommandOptionType, CommandInteraction, CommandInteractionOption, EmbedBuilder } from "discord.js"; +import { ApplicationCommandOptionType, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, TextChannel } from "discord.js"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; -import { embedify, PageEmbed, toUnix10, truncStr } from "@src/utils"; +import { embedify, PageEmbed, toUnix10 } from "@src/utils"; import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; -import { halves } from "svcorelib"; import k from "kleur"; export class Poll extends Command { private interval?: NodeJS.Timer; + private client: Client; - constructor() + constructor(client: Client) { super({ name: "poll", @@ -27,6 +27,12 @@ export class Poll extends Command desc: "Enter pings (be mindful of who you ping) and extra explanatory text to notify users of this poll.", type: ApplicationCommandOptionType.String, }, + { + name: "votes_per_user", + desc: "How many times a user is allowed to vote", + type: ApplicationCommandOptionType.Number, + min: 1, + } // TODO: // { // name: "allow_rethinking", @@ -46,6 +52,8 @@ export class Poll extends Command // }, ], }); + + this.client = client; try { this.checkPolls(); @@ -69,7 +77,10 @@ export class Poll extends Command { case "create": { - const modal = new CreatePollModal(int.options.get("headline")?.value as string | undefined); + const headline = int.options.get("headline")?.value as string | undefined; + const votes_per_user = int.options.get("votes_per_user")?.value as number | undefined; + + const modal = new CreatePollModal(headline, votes_per_user); return await int.showModal(modal.getInternalModal()); } @@ -84,25 +95,28 @@ export class Poll extends Command const pollList = [...polls]; const pages: EmbedBuilder[] = []; - const pollsPerPage = 20; + const pollsPerPage = 8; const totalPages = Math.ceil(polls.length / pollsPerPage); while(pollList.length > 0) { - const pollSlices = halves(pollList.splice(0, pollsPerPage)); + const pollSlice = pollList.splice(0, pollsPerPage); const ebd = new EmbedBuilder() .setTitle("Active polls") + .setDescription(polls.length != 1 ? `Currently there's ${polls.length} active polls.` : "Currently there's only 1 active poll.") .setColor(settings.embedColors.default) - .addFields(pollSlices - .filter(sl => sl && sl.length > 0) - .map(sl => ({ - name: "\u200B", - value: sl.reduce((a, c) => `${a}\n\n> **\`${c.pollId}\` - ${c.topic ? `${truncStr(c.topic.replace(/\n+/gm, " "), 64)}**\n> ` : ""}By <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - **open <:open_in_browser:994648843331309589>**\nPoll ends `, "") - })) - ); - - totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages})` }); + .addFields({ + name: "\u200B", + value: pollSlice.reduce((a, c) => ([ + `${a}\n`, + `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show poll <:open_in_browser:994648843331309589>](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, + `> Ends `, + ...(c.topic ? [`> **Topic:**${c.topic.length > 64 ? "\n> " : " "}${c.topic.replace(/[`]{3}\w*/gm, "").replace(/\n+/gm, " ")}`] : []), + ].join("\n")), ""), + }); + + totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages}) - showing ${pollsPerPage}` }); pages.push(ebd); } @@ -131,9 +145,68 @@ export class Poll extends Command { const expPolls = await getExpiredPolls(); - expPolls.forEach(({ guildId, pollId }) => { + for await(const { guildId, pollId, channel, messages, voteOptions } of expPolls) + { + const gui = this.client.guilds.cache.find(g => g.id === guildId); + const chan = gui?.channels.cache.find(c => c.id === channel); + const msgs = (chan as TextChannel | undefined)?.messages.cache + .filter(m => messages.includes(m.id)) + .sort((a, b) => a.createdTimestamp < b.createdTimestamp ? 1 : -1); + + if(msgs) + { + const firstMsg = msgs.at(0)!; + + const finalVotes = await this.accumulateVotes(msgs.reduce((a, c) => { a.push(c as never); return a; }, []), voteOptions); + + const finalVotesFields = CreatePollModal.reduceOptionFields(finalVotes.map(v => `${v.option} - **${v.votes.length}**`)); + + const scoreColl = new Collection(); + finalVotes.forEach(({ votes }) => { + votes.forEach(user => { + if(!scoreColl.has(user)) + scoreColl.set(user, 1); + else + scoreColl.set(user, scoreColl.get(user)! + 1); + }); + }); + + let peopleVoted = 0, totalVotes = 0; + + scoreColl.forEach((score) => { + peopleVoted++; + totalVotes += score; + }); + + const sortedVotes = finalVotes.sort((a, b) => a.votes.length < b.votes.length ? 1 : -1); + const winningOptions = sortedVotes.filter(v => v.votes === sortedVotes[0].votes); + + // can't Promise.all() else the api could rate limit us + await firstMsg.edit({ + embeds: [ + new EmbedBuilder() + .setTitle("Poll (closed)") + .setColor(settings.embedColors.default) + .setDescription(`The poll has ended!\n${peopleVoted} people have voted ${totalVotes} times and this is what they selected:\n\n${winningOptions.reduce((a, c) => `${a}\n\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} votes**` : ""}`, "")}`) + .addFields(finalVotesFields) + ], + }); + } + // TODO: display conclusion message & final vote numbers deletePoll(guildId, pollId); - }); + } + } + + async accumulateVotes(msgs: M[], _voteOpts: O[]): Promise<{ msg: M, emoji: string, option: O, votes: string[] }[]> + { + for(const msg of msgs as unknown as Message[]) + { + const reacts = msg.reactions.cache.entries(); + + console.log(reacts); + } + + return []; } } diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index 7a31cdd..b4babc2 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -5,13 +5,11 @@ import { settings } from "@src/settings"; import { time } from "@discordjs/builders"; import { createNewUser, deleteReminder, deleteReminders, getExpiredReminders, getReminder, getReminders, getUser, setReminder } from "@src/database/users"; import { Reminder as ReminderObj } from "@prisma/client"; -import { BtnMsg, embedify, PageEmbed, toUnix10, useEmbedify } from "@src/utils"; +import { BtnMsg, embedify, PageEmbed, timeToMs, toUnix10, useEmbedify } from "@src/utils"; /** Max reminders per user (global) */ const reminderLimit = 10; -type TimeObj = Record<"days"|"hours"|"minutes"|"seconds"|"months"|"years", number>; - export class Reminder extends Command { constructor(client: Client) @@ -115,15 +113,6 @@ export class Reminder extends Command async run(int: CommandInteraction, opt: CommandInteractionOption<"cached">) { - const getTime = (timeObj: TimeObj) => { - return 1000 * timeObj.seconds - + 1000 * 60 * timeObj.minutes - + 1000 * 60 * 60 * timeObj.hours - + 1000 * 60 * 60 * 24 * timeObj.days - + 1000 * 60 * 60 * 24 * 30 * timeObj.months - + 1000 * 60 * 60 * 24 * 365 * timeObj.years; - }; - const { user, guild, channel } = int; let action = ""; @@ -148,7 +137,7 @@ export class Reminder extends Command const { name, ...timeObj } = args; - const dueInMs = getTime(timeObj); + const dueInMs = timeToMs(timeObj); if(dueInMs < 1000 * 5) return await this.reply(int, embedify("Please enter at least five seconds.", settings.embedColors.error), true); diff --git a/src/modals/poll.ts b/src/modals/poll.ts index daedb63..9bed0f5 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -1,16 +1,19 @@ -import { EmbedBuilder, Message, MessageOptions, ModalSubmitInteraction, TextInputBuilder, TextInputStyle } from "discord.js"; +import { EmbedBuilder, EmbedField, Message, MessageOptions, ModalSubmitInteraction, TextInputBuilder, TextInputStyle } from "discord.js"; import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; import { embedify } from "@src/utils"; import { createNewGuild, createNewPoll, getGuild, getPolls } from "@src/database/guild"; +import { halves } from "svcorelib"; export class CreatePollModal extends Modal { private headline; + private votesPerUser; - constructor(headline?: string) + constructor(headline?: string, votesPerUser = 1) { + // TODO: persist initial value of modal inputs with redis so the data is kept when a user fucks up the time super({ title: "Create a poll", inputs: [ @@ -40,6 +43,22 @@ export class CreatePollModal extends Modal }); this.headline = headline; + this.votesPerUser = votesPerUser; + } + + public static reduceOptionFields(opts: string[], twoFields = true): EmbedField[] + { + // TODO: Fix + return (twoFields ? halves(opts) : [opts]) + .reduce((a, o, i) => { + a.push(o.map(opt => ({ opt, emoji: settings.emojiList[i] })) as never); + return a; + }, []) + .map(() => ({ + name: "\u200B", + value: opts.reduce((a, c, i) => `${a}\n${c.emoji} \u200B ${c.opt}`, ""), + inline: true, + })); } async submit(int: ModalSubmitInteraction<"cached">): Promise { @@ -72,20 +91,22 @@ export class CreatePollModal extends Modal const d = new Date(), today = rest.length > 4 ? [] : [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]; - const timeParts = [...today, ...rest.map(v => parseInt(v))] as [number]; + const timeParts = [...today, ...rest.map((v, i) => i != 0 ? parseInt(v) : parseInt(v) - new Date().getTimezoneOffset() / 60)] as [number]; const dueTimestamp = new Date(...timeParts); - const descOptions = voteOptions.reduce((a, c, i) => `${a}\n${settings.emojiList[i]} - ${c}`, ""); + const optionFields = CreatePollModal.reduceOptionFields(voteOptions); if(dueTimestamp.getTime() < Date.now() + 1000 * 30) return this.reply(int, embedify("Please enter a date and time that is at least one minute from now.", settings.embedColors.error), true); const ebd = new EmbedBuilder() .setTitle("Poll") - .setDescription(`${topic.length > 0 ? `This poll was created to vote about:\n${topic}\n\nYour options are:\n` : ""}${descOptions}`) - .setFields() + .addFields(optionFields) + .setFooter({ text: "Click the reaction emojis under this message to cast a vote." }) .setColor(settings.embedColors.default); + topic.length > 0 && ebd.setDescription(`**Topic of the vote:**\n> ${topic}\n\n**Your options are:**\n`); + await this.deferReply(int, true); // send messages & react @@ -143,6 +164,7 @@ export class CreatePollModal extends Modal headline: headline ?? null, topic: topic.length > 0 ? topic : null, voteOptions, + votesPerUser: this.votesPerUser, dueTimestamp, }); diff --git a/src/utils/time.ts b/src/utils/time.ts index 0211c3b..8c69b00 100644 --- a/src/utils/time.ts +++ b/src/utils/time.ts @@ -24,3 +24,18 @@ export function toUnix10(time: Date | number) { return Math.floor((typeof time === "number" ? time : time.getTime()) / 1000); } + +export type TimeObj = Record<"days"|"hours"|"minutes"|"seconds"|"months"|"years", number>; + +/** Converts a time object into */ +export function timeToMs(timeObj: Partial) +{ + return Math.floor( + 1000 * (timeObj?.seconds ?? 0) + + 1000 * 60 * (timeObj?.minutes ?? 0) + + 1000 * 60 * 60 * (timeObj?.hours ?? 0) + + 1000 * 60 * 60 * 24 * (timeObj?.days ?? 0) + + 1000 * 60 * 60 * 24 * 30.5 * (timeObj?.months ?? 0) + + 1000 * 60 * 60 * 24 * 365 * (timeObj?.years ?? 0) + ); +} From 4bc415e0f4364556141e97b65225dfddf7c5766f Mon Sep 17 00:00:00 2001 From: Sven Date: Wed, 14 Sep 2022 01:26:21 +0200 Subject: [PATCH 11/51] feat: lots more poll stuff --- src/commands/util/Poll.ts | 161 +++++++++++++++++++++++++++----------- src/modals/poll.ts | 38 +++++---- 2 files changed, 138 insertions(+), 61 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 7c7567f..7dac727 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -6,6 +6,13 @@ import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import k from "kleur"; +interface PollVote { + msg: M; + emoji: string; + option: O; + votes: string[] +} + export class Poll extends Command { private interval?: NodeJS.Timer; @@ -24,7 +31,7 @@ export class Poll extends Command args: [ { name: "headline", - desc: "Enter pings (be mindful of who you ping) and extra explanatory text to notify users of this poll.", + desc: "Enter pings (be mindful of who you ping) or extra explanatory text to notify users of this poll", type: ApplicationCommandOptionType.String, }, { @@ -32,7 +39,12 @@ export class Poll extends Command desc: "How many times a user is allowed to vote", type: ApplicationCommandOptionType.Number, min: 1, - } + }, + { + name: "title", + desc: "The title of the poll message", + type: ApplicationCommandOptionType.String, + }, // TODO: // { // name: "allow_rethinking", @@ -79,13 +91,16 @@ export class Poll extends Command { const headline = int.options.get("headline")?.value as string | undefined; const votes_per_user = int.options.get("votes_per_user")?.value as number | undefined; + const title = int.options.get("title")?.value as string | undefined; - const modal = new CreatePollModal(headline, votes_per_user); + const modal = new CreatePollModal(headline, votes_per_user, title); return await int.showModal(modal.getInternalModal()); } case "list": { + // TODO:FIXME: Couldn't run the command due to an error: Received one or more errors + await this.deferReply(int); const polls = await getPolls(guild.id); @@ -145,60 +160,116 @@ export class Poll extends Command { const expPolls = await getExpiredPolls(); - for await(const { guildId, pollId, channel, messages, voteOptions } of expPolls) + for await(const { guildId, pollId, channel, messages, voteOptions, dueTimestamp: endTime } of expPolls) { - const gui = this.client.guilds.cache.find(g => g.id === guildId); - const chan = gui?.channels.cache.find(c => c.id === channel); - const msgs = (chan as TextChannel | undefined)?.messages.cache - .filter(m => messages.includes(m.id)) - .sort((a, b) => a.createdTimestamp < b.createdTimestamp ? 1 : -1); - - if(msgs) + try { - const firstMsg = msgs.at(0)!; + const gui = this.client.guilds.cache.find(g => g.id === guildId); + const chan = gui?.channels.cache.find(c => c.id === channel); + const msgs = (chan as TextChannel | undefined)?.messages.cache + .filter(m => messages.includes(m.id)) + .sort((a, b) => a.createdTimestamp < b.createdTimestamp ? 1 : -1); - const finalVotes = await this.accumulateVotes(msgs.reduce((a, c) => { a.push(c as never); return a; }, []), voteOptions); + if(msgs && msgs.size > 0) + { + const firstMsg = msgs.at(0)!; - const finalVotesFields = CreatePollModal.reduceOptionFields(finalVotes.map(v => `${v.option} - **${v.votes.length}**`)); + const finalVotes = await this.accumulateVotes(msgs.reduce((a, c) => { a.push(c as never); return a; }, []), voteOptions); - const scoreColl = new Collection(); - finalVotes.forEach(({ votes }) => { - votes.forEach(user => { - if(!scoreColl.has(user)) - scoreColl.set(user, 1); - else - scoreColl.set(user, scoreColl.get(user)! + 1); - }); - }); + const startTime = firstMsg.createdAt; - let peopleVoted = 0, totalVotes = 0; + // can't Promise.all() else the api could rate limit us + await firstMsg.edit({ embeds: [ this.getConclusionEmbed(finalVotes, startTime, endTime, guildId, channel, firstMsg.id) ] }); - scoreColl.forEach((score) => { - peopleVoted++; - totalVotes += score; - }); + this.sendConclusion(firstMsg, finalVotes, startTime, endTime); + } - const sortedVotes = finalVotes.sort((a, b) => a.votes.length < b.votes.length ? 1 : -1); - const winningOptions = sortedVotes.filter(v => v.votes === sortedVotes[0].votes); - - // can't Promise.all() else the api could rate limit us - await firstMsg.edit({ - embeds: [ - new EmbedBuilder() - .setTitle("Poll (closed)") - .setColor(settings.embedColors.default) - .setDescription(`The poll has ended!\n${peopleVoted} people have voted ${totalVotes} times and this is what they selected:\n\n${winningOptions.reduce((a, c) => `${a}\n\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} votes**` : ""}`, "")}`) - .addFields(finalVotesFields) - ], - }); + deletePoll(guildId, pollId); + } + catch(err) + { + // TODO: add logging lib + console.error(`Error while checking poll with guildId=${guildId}, pollId=${pollId} and channel=${channel}:\n`, err); } - - // TODO: display conclusion message & final vote numbers - deletePoll(guildId, pollId); } } - async accumulateVotes(msgs: M[], _voteOpts: O[]): Promise<{ msg: M, emoji: string, option: O, votes: string[] }[]> + getConclusionEmbed(finalVotes: PollVote[], startTime: Date, endTime: Date, guildId: string, channelId: string, firstMsgId: string) + { + const { + finalVotesFields, peopleVoted, totalVotes, winningOptions, getReducedWinningOpts + } = this.parseFinalVotes(finalVotes); + + return new EmbedBuilder() + .setTitle("Poll (closed)") + .setColor(settings.embedColors.default) + .setDescription([ + `The poll has ended!\nIt ran from to `, + `${peopleVoted} people have voted ${totalVotes} times and this is what they selected:\n`, + `${getReducedWinningOpts(3)}${winningOptions.length > 3 ? `\n\nAnd ${winningOptions.length - 3} more.` : ""}\n`, + `[Click here](https://discord.com/channels/${guildId}/${channelId}/${firstMsgId}) to view the full poll.`, + ].join("\n")) + .addFields(finalVotesFields); + } + + parseFinalVotes(finalVotes: PollVote[]) + { + const finalVotesFields = CreatePollModal.reduceOptionFields(finalVotes.map(v => `${v.option} - **${v.votes.length}**`, true)); + + const scoreColl = new Collection(); + finalVotes.forEach(({ votes }) => { + votes.forEach(user => { + if(!scoreColl.has(user)) + scoreColl.set(user, 1); + else + scoreColl.set(user, scoreColl.get(user)! + 1); + }); + }); + + let peopleVoted = 0, totalVotes = 0; + + scoreColl.forEach((score) => { + peopleVoted++; + totalVotes += score; + }); + + const sortedVotes = finalVotes.sort((a, b) => a.votes.length < b.votes.length ? 1 : -1); + const winningOptions = sortedVotes.filter(v => v.votes === sortedVotes[0].votes); + + const getReducedWinningOpts = (limit?: number) => + winningOptions.reduce((a, c, i) => `${a}${ + !limit || i < limit + ? `\n\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} votes**` : ""}` + : "" + }`, ""); + + return { + finalVotesFields, + scoreColl, + peopleVoted, + totalVotes, + sortedVotes, + winningOptions, + /** Call to get a markdown string of the winning options. Default limit (undefined) = list all */ + getReducedWinningOpts, + }; + } + + async sendConclusion(msg: Message, finalVotes: PollVote[], startTime: Date, endTime: Date) + { + // TODO: + + const { peopleVoted, getReducedWinningOpts } = this.parseFinalVotes(finalVotes); + + await msg.reply({ embeds: [ + new EmbedBuilder() + .setColor(settings.embedColors.default) + .setTitle("This poll has closed.") + .setDescription(`It ran from to \n${peopleVoted} people have voted and these are the results:\n\n${getReducedWinningOpts()}`) + ]}); + } + + async accumulateVotes(msgs: Message[], _voteOpts: string[]): Promise { for(const msg of msgs as unknown as Message[]) { diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 9bed0f5..ff0224b 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -10,8 +10,9 @@ export class CreatePollModal extends Modal { private headline; private votesPerUser; + private title; - constructor(headline?: string, votesPerUser = 1) + constructor(headline?: string, votesPerUser = 1, title: string | undefined = undefined) { // TODO: persist initial value of modal inputs with redis so the data is kept when a user fucks up the time super({ @@ -44,21 +45,26 @@ export class CreatePollModal extends Modal this.headline = headline; this.votesPerUser = votesPerUser; + this.title = title; } - public static reduceOptionFields(opts: string[], twoFields = true): EmbedField[] + public static reduceOptionFields(opts: string[]): EmbedField[] { - // TODO: Fix - return (twoFields ? halves(opts) : [opts]) - .reduce((a, o, i) => { - a.push(o.map(opt => ({ opt, emoji: settings.emojiList[i] })) as never); - return a; - }, []) - .map(() => ({ - name: "\u200B", - value: opts.reduce((a, c, i) => `${a}\n${c.emoji} \u200B ${c.opt}`, ""), - inline: true, - })); + const optHalves = opts.length > settings.emojiList.length / 3 ? halves(opts) : [opts]; + + const redOpts: { opt: string, emoji: string }[][] = []; + + optHalves.forEach((half, i) => + redOpts.push(half.map((opt, j) => + ({ opt, emoji: settings.emojiList[j + (i === 1 ? optHalves[0].length : 0)] }) + )) + ); + + return redOpts.map((red, i) => ({ + name: i === 0 ? "**Options:**" : "\u200B", + value: red.reduce((a, c) => `${a}\n${c.emoji} \u200B ${c.opt}`, ""), + inline: true, + })); } async submit(int: ModalSubmitInteraction<"cached">): Promise { @@ -100,12 +106,12 @@ export class CreatePollModal extends Modal return this.reply(int, embedify("Please enter a date and time that is at least one minute from now.", settings.embedColors.error), true); const ebd = new EmbedBuilder() - .setTitle("Poll") + .setTitle(this.title ?? "Poll") .addFields(optionFields) - .setFooter({ text: "Click the reaction emojis under this message to cast a vote." }) + .setFooter({ text: `Click the reaction emojis below to cast ${this.votesPerUser === 1 ? "a vote" : "votes"}.` }) .setColor(settings.embedColors.default); - topic.length > 0 && ebd.setDescription(`**Topic of the vote:**\n> ${topic}\n\n**Your options are:**\n`); + topic.length > 0 && ebd.setDescription(`> **Topic:**${topic.length > 64 ? "\n>" : ""} ${topic}\n`); await this.deferReply(int, true); From 9e0d403b3b83ecf5b793c00991907d81a00c90b8 Mon Sep 17 00:00:00 2001 From: Sven Date: Wed, 14 Sep 2022 17:38:53 +0200 Subject: [PATCH 12/51] feat: unfinished poll stuff --- src/commands/util/Poll.ts | 135 ++++++++++++++++++++++---------------- 1 file changed, 78 insertions(+), 57 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 7dac727..68803f9 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,7 +1,7 @@ import { ApplicationCommandOptionType, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, TextChannel } from "discord.js"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; -import { embedify, PageEmbed, toUnix10 } from "@src/utils"; +import { embedify, PageEmbed, toUnix10, useEmbedify } from "@src/utils"; import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import k from "kleur"; @@ -80,79 +80,100 @@ export class Poll extends Command async run(int: CommandInteraction, opt: CommandInteractionOption): Promise { - const { guild, channel } = int; + let action = ""; - if(!guild || !channel) - return this.reply(int, embedify("Please use this command in a server.", settings.embedColors.error), true); - - switch(opt.name) - { - case "create": + try { - const headline = int.options.get("headline")?.value as string | undefined; - const votes_per_user = int.options.get("votes_per_user")?.value as number | undefined; - const title = int.options.get("title")?.value as string | undefined; + const { guild, channel } = int; - const modal = new CreatePollModal(headline, votes_per_user, title); + if(!guild || !channel) + return this.reply(int, embedify("Please use this command in a server.", settings.embedColors.error), true); - return await int.showModal(modal.getInternalModal()); - } - case "list": - { - // TODO:FIXME: Couldn't run the command due to an error: Received one or more errors + switch(opt.name) + { + case "create": + { + action = "creating a new poll"; - await this.deferReply(int); + const headline = int.options.get("headline")?.value as string | undefined; + const votes_per_user = int.options.get("votes_per_user")?.value as number | undefined; + const title = int.options.get("title")?.value as string | undefined; - const polls = await getPolls(guild.id); + const modal = new CreatePollModal(headline, votes_per_user, title); - if(!polls || polls.length === 0) - return this.editReply(int, embedify("Currently no polls are active on this server.\nYou can create a new one with `/poll create`", settings.embedColors.error)); + return await int.showModal(modal.getInternalModal()); + } + case "list": + { + action = "listing polls"; + // TODO:FIXME: Couldn't run the command due to an error: Received one or more errors - const pollList = [...polls]; - const pages: EmbedBuilder[] = []; - const pollsPerPage = 8; - const totalPages = Math.ceil(polls.length / pollsPerPage); + await this.deferReply(int); - while(pollList.length > 0) - { - const pollSlice = pollList.splice(0, pollsPerPage); - - const ebd = new EmbedBuilder() - .setTitle("Active polls") - .setDescription(polls.length != 1 ? `Currently there's ${polls.length} active polls.` : "Currently there's only 1 active poll.") - .setColor(settings.embedColors.default) - .addFields({ - name: "\u200B", - value: pollSlice.reduce((a, c) => ([ - `${a}\n`, - `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show poll <:open_in_browser:994648843331309589>](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, - `> Ends `, - ...(c.topic ? [`> **Topic:**${c.topic.length > 64 ? "\n> " : " "}${c.topic.replace(/[`]{3}\w*/gm, "").replace(/\n+/gm, " ")}`] : []), - ].join("\n")), ""), - }); + const polls = await getPolls(guild.id); - totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages}) - showing ${pollsPerPage}` }); + if(!polls || polls.length === 0) + return this.editReply(int, embedify("Currently no polls are active on this server.\nYou can create a new one with `/poll create`", settings.embedColors.error)); - pages.push(ebd); - } + const pollList = [...polls]; + const pages: EmbedBuilder[] = []; + const pollsPerPage = 8; + const totalPages = Math.ceil(polls.length / pollsPerPage); + + while(pollList.length > 0) + { + const pollSlice = pollList.splice(0, pollsPerPage); + + const ebd = new EmbedBuilder() + .setTitle("Active polls") + .setDescription(polls.length != 1 ? `Currently there's ${polls.length} active polls.` : "Currently there's only 1 active poll.") + .setColor(settings.embedColors.default) + .addFields({ + name: "\u200B", + value: pollSlice.reduce((a, c) => ([ + `${a}\n`, + `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show poll <:open_in_browser:994648843331309589>](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, + `> Ends `, + ...(c.topic ? [`> **Topic:**${c.topic.length > 64 ? "\n> " : " "}${c.topic.replace(/[`]{3}\w*/gm, "").replace(/\n+/gm, " ")}`] : []), + ].join("\n")), ""), + }); + + totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages}) - showing ${pollsPerPage}` }); + + pages.push(ebd); + } + + if(pages.length > 1) + { + const pe = new PageEmbed(pages, int.user.id, { + allowAllUsersTimeout: 60 * 1000, + goToPageBtn: pages.length > 5, + }); - if(pages.length > 1) + return pe.useInt(int); + } + else + return this.editReply(int, pages[0]); + } + case "cancel": { - const pe = new PageEmbed(pages, int.user.id, { - allowAllUsersTimeout: 60 * 1000, - goToPageBtn: pages.length > 5, - }); + action = "canceling a poll"; - return pe.useInt(int); + // TODO: + return; + } } - else - return this.editReply(int, pages[0]); } - case "cancel": + catch(err) { - // TODO: - return; - } + console.log(`Error while ${action}:\n`, err); + + const errReply = useEmbedify(`Error while ${action}: ${err}`, settings.embedColors.error); + + if(int.deferred || int.replied) + int.editReply(errReply); + else + int.reply(errReply); } } From 2d89dfdd64817da30b37ee180f375f1ab7249f22 Mon Sep 17 00:00:00 2001 From: Sven Date: Sat, 17 Sep 2022 17:48:55 +0200 Subject: [PATCH 13/51] hopefully fix: reminder double DM --- src/commands/util/Reminder.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index b4babc2..87fda00 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -12,6 +12,12 @@ const reminderLimit = 10; export class Reminder extends Command { + /** + * Contains all reminders that are currently being checked. + * Format: `userId-reminderId` + */ + private reminderCheckBuffer = new Set(); + constructor(client: Client) { super({ @@ -336,6 +342,11 @@ export class Reminder extends Command if(!expRems || expRems.length === 0) return; + this.reminderCheckBuffer = new Set([ + ...this.reminderCheckBuffer, + ...expRems.map(r => `${r.userId}-${r.reminderId}`), + ]); + const promises: Promise[] = []; const getExpiredEbd = ({ name }: ReminderObj) => new EmbedBuilder() @@ -368,11 +379,15 @@ export class Reminder extends Command finally { deleteReminder(rem.reminderId, rem.userId); + this.reminderCheckBuffer.delete(`${rem.userId}-${rem.reminderId}`); } }; for(const rem of expRems) { + if(this.reminderCheckBuffer.has(`${rem.userId}-${rem.reminderId}`)) + return; + const usr = client.users.cache.find(u => u.id === rem.userId); promises.push((async () => { @@ -389,6 +404,7 @@ export class Reminder extends Command return guildFallback(rem); await deleteReminder(rem.reminderId, rem.userId); + this.reminderCheckBuffer.delete(`${rem.userId}-${rem.reminderId}`); } catch(err) { From ce0f3ffa8937e908ddb1b5a8f904b1e6431a0e9a Mon Sep 17 00:00:00 2001 From: Sven Date: Fri, 23 Sep 2022 23:30:01 +0200 Subject: [PATCH 14/51] feat: private reminders --- prisma/schema.prisma | 1 + src/commands/util/Reminder.ts | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a402b59..cb74c15 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -37,6 +37,7 @@ model Reminder { dueTimestamp DateTime guild String? channel String? + private Boolean @default(false) User User @relation(fields: [userId], references: [id], onDelete: Cascade) @@id([reminderId, userId]) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index 87fda00..25290f6 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -35,6 +35,11 @@ export class Reminder extends Command type: ApplicationCommandOptionType.String, required: true, }, + { + name: "private", + desc: "Set to True to hide this reminder from other people", + type: ApplicationCommandOptionType.Boolean, + }, { name: "seconds", desc: "In how many seconds", @@ -133,6 +138,7 @@ export class Reminder extends Command const args = { name: int.options.get("name", true).value as string, + ephemeral: int.options.get("private")?.value as boolean ?? false, seconds: int.options.get("seconds")?.value as number ?? 0, minutes: int.options.get("minutes")?.value as number ?? 0, hours: int.options.get("hours")?.value as number ?? 0, @@ -141,14 +147,14 @@ export class Reminder extends Command years: int.options.get("years")?.value as number ?? 0, }; - const { name, ...timeObj } = args; + const { name, ephemeral, ...timeObj } = args; const dueInMs = timeToMs(timeObj); if(dueInMs < 1000 * 5) return await this.reply(int, embedify("Please enter at least five seconds.", settings.embedColors.error), true); - await this.deferReply(int, false); + await this.deferReply(int, ephemeral); const reminders = await getReminders(user.id); @@ -171,9 +177,10 @@ export class Reminder extends Command channel: channel?.id ?? null, reminderId, dueTimestamp, + private: ephemeral, }); - return await this.editReply(int, embedify(`I've set a reminder with the name \`${name}\`\nDue: ${time(toUnix10(dueTimestamp), "f")}\n\nTo list your reminders, use \`/reminder list\``, settings.embedColors.success)); + return await this.editReply(int, embedify(`I've set a reminder with the name \`${name}\` (ID \`${reminderId}\`)\nDue: ${time(toUnix10(dueTimestamp), "f")}\n\nTo list your reminders, use \`/reminder list\``, settings.embedColors.success)); } case "list": { @@ -357,10 +364,13 @@ export class Reminder extends Command const guildFallback = (rem: ReminderObj) => { try { + if(rem.private) + return; + const guild = client.guilds.cache.find(g => g.id === rem.guild); const chan = guild?.channels.cache.find(c => c.id === rem.channel); - if(chan && [ChannelType.GuildText, ChannelType.GuildPublicThread, ChannelType.GuildPrivateThread].includes(chan.type)) + if(chan && [ChannelType.GuildText, ChannelType.GuildPublicThread, ChannelType.GuildPrivateThread, ChannelType.GuildForum].includes(chan.type)) { const c = chan as TextBasedChannel; c.send({ embeds: [ getExpiredEbd(rem) ] }); From f54867489dfd93d201d2ed9dcb074c303a2b3824 Mon Sep 17 00:00:00 2001 From: Sven Date: Fri, 23 Sep 2022 23:30:06 +0200 Subject: [PATCH 15/51] fix: random stuff --- src/Command.ts | 4 ++-- src/commands/mod/Log.ts | 21 +++++++++++++-------- src/commands/util/Emoji.ts | 3 ++- src/commands/util/Server.ts | 5 +++-- src/utils/time.ts | 2 +- 5 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/Command.ts b/src/Command.ts index a113c5e..c0e497a 100644 --- a/src/Command.ts +++ b/src/Command.ts @@ -96,7 +96,7 @@ export abstract class Command opt.setName(arg.name) .setDescription(arg.desc) .setRequired(arg.required ?? false) - .addChannelTypes(ChannelType.GuildText, ChannelType.GuildNews, ChannelType.GuildPublicThread) + .addChannelTypes(ChannelType.GuildText, ChannelType.GuildNews, ChannelType.GuildPublicThread, ChannelType.GuildPrivateThread, ChannelType.GuildVoice) ); else if(arg.type === ApplicationCommandOptionType.Role) data.addRoleOption(opt => @@ -187,7 +187,7 @@ export abstract class Command opt.setName(arg.name) .setDescription(arg.desc) .setRequired(arg.required ?? false) - .addChannelTypes(ChannelType.GuildText, ChannelType.GuildNews, ChannelType.GuildPublicThread) + .addChannelTypes(ChannelType.GuildText, ChannelType.GuildNews, ChannelType.GuildPublicThread, ChannelType.GuildPrivateThread, ChannelType.GuildVoice) ); else if(arg.type === ApplicationCommandOptionType.Role) sc.addRoleOption(opt => diff --git a/src/commands/mod/Log.ts b/src/commands/mod/Log.ts index 82a0d8a..838107d 100644 --- a/src/commands/mod/Log.ts +++ b/src/commands/mod/Log.ts @@ -63,8 +63,8 @@ export class Log extends Command { } try { - if (channel?.type === ChannelType.GuildText && typeof(logChannel?.send) === "function") { - + const chanTypes = [ChannelType.GuildText, ChannelType.GuildNews, ChannelType.GuildPublicThread, ChannelType.GuildPrivateThread, ChannelType.GuildVoice]; + if (chanTypes.includes(channel?.type)) { if(!start) { channel.messages.fetch({ limit: 1 }).then(messages => { const lastMessage = messages?.first(); @@ -170,14 +170,19 @@ export class Log extends Command { } }); }).then(async () => { - for await(const embed of messageSet) { - gld.lastLogColor = String(newEmbedColor); + if(logChannel) + { + for await(const embed of messageSet) { + gld.lastLogColor = String(newEmbedColor); - await setGuild(gld); - logChannel.send({ embeds: [embed] }); - } + await setGuild(gld); + logChannel.send({ embeds: [embed] }); + } - return await this.editReply(int, embedify(`Successfully logged **${amount}** message${amount === 1 ? "" : "s"} to **#${logChannel.name}**`, settings.embedColors.default)); + return this.editReply(int, embedify(`Successfully logged **${amount}** message${amount === 1 ? "" : "s"} to **#${logChannel.name}**`, settings.embedColors.default)); + } + // TODO: ". or edit your guild settings in the [control panel.](https://brewbot.co/guild/123/settings)" + return this.editReply(int, embedify("Couldn't find the log channel. Please specify one with the argument `channel`.", settings.embedColors.error)); }); } else diff --git a/src/commands/util/Emoji.ts b/src/commands/util/Emoji.ts index 61b669c..1e52fb4 100644 --- a/src/commands/util/Emoji.ts +++ b/src/commands/util/Emoji.ts @@ -28,8 +28,9 @@ export class Emoji extends Command { const emoji = int.options.get("emoji", true).value as string; + // TODO: make this URL auto download the image somehow const getEmUrl = (id: string, fmt: string) => `https://cdn.discordapp.com/emojis/${id}.${fmt}?size=4096&quality=lossless`; - const trimmed = (str: string) => str.length > 16 ? str.substring(0, 16) + "+" : str; + const trimmed = (str: string) => str.length > 24 ? str.substring(0, 24) + "+" : str; const embeds: EmbedBuilder[] = []; const btns: ButtonBuilder[] = []; diff --git a/src/commands/util/Server.ts b/src/commands/util/Server.ts index 3730111..5f7d540 100644 --- a/src/commands/util/Server.ts +++ b/src/commands/util/Server.ts @@ -1,6 +1,7 @@ import { CommandInteraction, CommandInteractionOption, EmbedField, EmbedBuilder, ChannelType, PermissionFlagsBits } from "discord.js"; import { Command } from "@src/Command"; import { settings } from "@src/settings"; +import { toUnix10 } from "@src/utils"; export class Server extends Command { @@ -57,7 +58,7 @@ export class Server extends Command guild.description && guild.description.length > 0 && fields.push({ name: "Description", value: guild.description, inline: true }); fields.push({ name: "Owner", value: `<@${guild.ownerId}>`, inline: true }); - fields.push({ name: "Created", value: guild.createdAt.toUTCString(), inline: true }); + fields.push({ name: "Created", value: ``, inline: true }); const verifLevel = verifLevelMap[guild.verificationLevel]; fields.push({ name: "Verification level", value: verifLevel, inline: true }); @@ -66,7 +67,7 @@ export class Server extends Command const botMembers = guild.members.cache.filter(m => m.user.bot).size ?? undefined; const onlineMembers = botMembers ? guild.members.cache.filter(m => (!m.user.bot && ["online", "idle", "dnd"].includes(m.presence?.status ?? "_"))).size : undefined; - const publicTxtChannelsAmt = guild.channels.cache.filter(ch => [ChannelType.GuildNews, ChannelType.GuildText].includes(ch.type) && ch.permissionsFor(guild.roles.everyone).has(PermissionFlagsBits.ViewChannel)).size; + const publicTxtChannelsAmt = guild.channels.cache.filter(ch => [ChannelType.GuildText, ChannelType.GuildPublicThread, ChannelType.GuildPrivateThread, ChannelType.GuildForum].includes(ch.type) && ch.permissionsFor(guild.roles.everyone).has(PermissionFlagsBits.ViewChannel)).size; const publicVoiceChannelsAmt = guild.channels.cache.filter(ch => ch.type === ChannelType.GuildVoice && ch.permissionsFor(guild.roles.everyone).has(PermissionFlagsBits.Speak)).size; let memberCount = `Total: ${allMembers}`; diff --git a/src/utils/time.ts b/src/utils/time.ts index 8c69b00..8e0a96e 100644 --- a/src/utils/time.ts +++ b/src/utils/time.ts @@ -27,7 +27,7 @@ export function toUnix10(time: Date | number) export type TimeObj = Record<"days"|"hours"|"minutes"|"seconds"|"months"|"years", number>; -/** Converts a time object into */ +/** Converts a time object into its amount of milliseconds */ export function timeToMs(timeObj: Partial) { return Math.floor( From 65549e3a9d61dba727413945e578bacb5e4222f7 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sat, 24 Sep 2022 17:35:29 +0200 Subject: [PATCH 16/51] fix: don't force DM if reminder not private --- src/commands/util/Reminder.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index 25290f6..ab641b3 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -365,7 +365,7 @@ export class Reminder extends Command try { if(rem.private) - return; + throw new Error("Can't send message in guild as reminder is private."); const guild = client.guilds.cache.find(g => g.id === rem.guild); const chan = guild?.channels.cache.find(c => c.id === rem.channel); @@ -380,9 +380,9 @@ export class Reminder extends Command { // TODO: track reminder "loss rate" // - // I │ I I - // ────┼──── - // I I │ I ⌐¬ + // I │ I I + // ─────┼───── + // I I │ I ⌐¬ void err; } @@ -406,7 +406,7 @@ export class Reminder extends Command try { - const dm = await usr.createDM(true); + const dm = await usr.createDM(rem.private); const msg = await dm.send({ embeds: [ getExpiredEbd(rem) ]}); From 708d169c28588c88c52299a9813efa9531830224 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 27 Sep 2022 14:08:57 +0200 Subject: [PATCH 17/51] chore: add license --- LICENSE.txt | 661 +++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 4 +- 2 files changed, 663 insertions(+), 2 deletions(-) create mode 100644 LICENSE.txt diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/package.json b/package.json index 2ffbe33..8d8c31f 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "type": "git", "url": "git+https://github.com/codedrunks/BrewBot.git" }, - "license": "UNLICENSED", + "license": "AGPL-3.0", "bugs": { "url": "https://github.com/codedrunks/BrewBot/issues" }, @@ -79,4 +79,4 @@ "prisma": { "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts" } -} +} \ No newline at end of file From 2b99046a72a03c576a97da06d97092ed450d1bfa Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 27 Sep 2022 14:16:54 +0200 Subject: [PATCH 18/51] fix: 1 sentence translation --- src/commands/util/Translate.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/commands/util/Translate.ts b/src/commands/util/Translate.ts index 74b8aba..7f4e02f 100644 --- a/src/commands/util/Translate.ts +++ b/src/commands/util/Translate.ts @@ -16,18 +16,18 @@ export class Translate extends Command category: "util", args: [ { - name: "text", - desc: "The text to translate", + name: "language", + desc: "English name of the language to translate to", type: ApplicationCommandOptionType.String, required: true, }, { - name: "language", - desc: "English name of the language to translate to", + name: "text", + desc: "The text to translate", type: ApplicationCommandOptionType.String, required: true, - } - ] + }, + ], }); } @@ -89,7 +89,7 @@ export class Translate extends Command if(trParts.length > 1) trParts = trParts.map((p: string[]) => p?.[0]); else - trParts = [trParts?.[0]]; + trParts = [trParts?.[0]?.[0]]; const translation = trParts .filter((p: unknown) => typeof p === "string") From 22ab6a8250b3a9bbfe93ee7683dfc446b857ac7d Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 27 Sep 2022 16:11:44 +0200 Subject: [PATCH 19/51] feat: lots more unfinished /poll stuff --- src/commands/util/Poll.ts | 149 ++++++++++++++++++++++++++++++-------- 1 file changed, 117 insertions(+), 32 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 68803f9..c7a6bdf 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,9 +1,10 @@ -import { ApplicationCommandOptionType, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, TextChannel } from "discord.js"; +import { ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, PermissionFlagsBits, TextChannel } from "discord.js"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; -import { embedify, PageEmbed, toUnix10, useEmbedify } from "@src/utils"; +import { autoPlural, BtnMsg, embedify, PageEmbed, toUnix10, truncStr, useEmbedify } from "@src/utils"; import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; +import { Poll as PollObj } from "@prisma/client"; import k from "kleur"; interface PollVote { @@ -29,22 +30,22 @@ export class Poll extends Command name: "create", desc: "Creates a poll in this channel", args: [ + { + name: "title", + desc: "The title of the poll message. This is different from the topic of the poll.", + type: ApplicationCommandOptionType.String, + }, { name: "headline", - desc: "Enter pings (be mindful of who you ping) or extra explanatory text to notify users of this poll", + desc: "Enter pings (be mindful of who you ping) or extra explanatory text to notify users of this poll.", type: ApplicationCommandOptionType.String, }, { name: "votes_per_user", - desc: "How many times a user is allowed to vote", + desc: "How many times a user is allowed to vote (1 time by default).", type: ApplicationCommandOptionType.Number, min: 1, }, - { - name: "title", - desc: "The title of the poll message", - type: ApplicationCommandOptionType.String, - }, // TODO: // { // name: "allow_rethinking", @@ -57,11 +58,18 @@ export class Poll extends Command name: "list", desc: "Lists all polls that are active on this server", }, - // { - // name: "cancel", - // desc: "Cancels a poll", - // perms: [PermissionFlagsBits.ManageChannels], - // }, + { + name: "delete", + desc: "Deletes an active poll", + args: [ + { + name: "poll_id", + desc: "The numerical ID of the poll to delete. View IDs with /poll list", + type: ApplicationCommandOptionType.Number, + required: true, + }, + ], + }, ], }); @@ -106,7 +114,6 @@ export class Poll extends Command case "list": { action = "listing polls"; - // TODO:FIXME: Couldn't run the command due to an error: Received one or more errors await this.deferReply(int); @@ -117,7 +124,7 @@ export class Poll extends Command const pollList = [...polls]; const pages: EmbedBuilder[] = []; - const pollsPerPage = 8; + const pollsPerPage = 4; const totalPages = Math.ceil(polls.length / pollsPerPage); while(pollList.length > 0) @@ -126,19 +133,19 @@ export class Poll extends Command const ebd = new EmbedBuilder() .setTitle("Active polls") - .setDescription(polls.length != 1 ? `Currently there's ${polls.length} active polls.` : "Currently there's only 1 active poll.") + .setDescription(polls.length != 1 ? `Currently there's ${polls.length} active ${autoPlural("poll", polls)}.` : "Currently there's only 1 active poll.") .setColor(settings.embedColors.default) .addFields({ name: "\u200B", value: pollSlice.reduce((a, c) => ([ `${a}\n`, - `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show poll <:open_in_browser:994648843331309589>](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, + `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show <:open_in_browser:994648843331309589>](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, + ...(c.topic ? [`> **Topic:** ${truncStr(c.topic.replace(/[`]{3}\w*/gm, "").replace(/\n+/gm, " "), 80)}`] : ["> (no topic)"]), `> Ends `, - ...(c.topic ? [`> **Topic:**${c.topic.length > 64 ? "\n> " : " "}${c.topic.replace(/[`]{3}\w*/gm, "").replace(/\n+/gm, " ")}`] : []), ].join("\n")), ""), }); - totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages}) - showing ${pollsPerPage}` }); + totalPages > 1 && ebd.setFooter({ text: `(${pages.length + 1}/${totalPages}) - showing ${pollsPerPage} of ${polls.length} total ${autoPlural("poll", polls)}` }); pages.push(ebd); } @@ -155,11 +162,81 @@ export class Poll extends Command else return this.editReply(int, pages[0]); } - case "cancel": + case "delete": { - action = "canceling a poll"; + action = "deleting a poll"; + // TODO: display current results to deleter, maybe in the poll itself? + + await this.deferReply(int, true); + + const pollId = int.options.get("poll_id", true).value as number; + + const polls = await getPolls(guild.id); + + const poll = polls.find(p => p.pollId === pollId); + + if(!poll) + return this.editReply(int, embedify("Couldn't find a poll with this ID.\nUse `/poll list` to list all active polls with their IDs.", settings.embedColors.error)); + + const { user, memberPermissions } = int; - // TODO: + if(!memberPermissions?.has(PermissionFlagsBits.ManageChannels) && user.id !== poll.createdBy) + return this.editReply(int, embedify("You are not the author of this poll so you can't delete it.", settings.embedColors.error)); + + const pollMsgs = (await this.getPollMsgs(poll))!; //#DBG + + const finalVotes = await this.accumulateVotes(pollMsgs.reduce((a, c) => { a.push(c as never); return a; }, []), poll.voteOptions); + + const { peopleVoted, getReducedWinningOpts } = this.parseFinalVotes(finalVotes); + + const btns = [ + new ButtonBuilder() + .setStyle(ButtonStyle.Danger) + .setLabel("Delete") + .setEmoji("🗑️"), + new ButtonBuilder() + .setStyle(ButtonStyle.Secondary) + .setLabel("Cancel") + .setEmoji("❌"), + ]; + + const bm = new BtnMsg(embedify(`You are about to delete a poll that ${peopleVoted} ${peopleVoted === 1 ? "person" : "people"} have voted on.\nAre you sure you want to delete the poll? This cannot be undone.`, settings.embedColors.warning), btns, { timeout: 30_000 }); + + bm.on("press", async (btn, btInt) => { + btInt.deferUpdate(); + + let embed: EmbedBuilder | undefined; + + if(btInt.user.id !== int.user.id) + return; + + if(btn.data.label === "Delete") + { + try + { + await Promise.all(pollMsgs.map(m => m.delete())); + + await deletePoll(poll.guildId, poll.pollId); + + embed = embedify(`The poll was successfully deleted.\nThe results were:\n${getReducedWinningOpts()}`); + } + catch(err) + { + embed = embedify("Couldn't delete the poll due to an error."); + } + } + else if(btn.data.label === "Cancel") + embed = embedify("Canceled deletion of the poll."); + + bm.destroy(); + + embed && int.editReply({ + ...bm.getReplyOpts(), + embeds: [embed], + }); + }); + + int.editReply(bm.getReplyOpts()); return; } } @@ -181,15 +258,12 @@ export class Poll extends Command { const expPolls = await getExpiredPolls(); - for await(const { guildId, pollId, channel, messages, voteOptions, dueTimestamp: endTime } of expPolls) + for await(const poll of expPolls) { + const { guildId, pollId, channel, voteOptions, dueTimestamp: endTime } = poll; try { - const gui = this.client.guilds.cache.find(g => g.id === guildId); - const chan = gui?.channels.cache.find(c => c.id === channel); - const msgs = (chan as TextChannel | undefined)?.messages.cache - .filter(m => messages.includes(m.id)) - .sort((a, b) => a.createdTimestamp < b.createdTimestamp ? 1 : -1); + const msgs = await this.getPollMsgs(poll); if(msgs && msgs.size > 0) { @@ -210,11 +284,22 @@ export class Poll extends Command catch(err) { // TODO: add logging lib - console.error(`Error while checking poll with guildId=${guildId}, pollId=${pollId} and channel=${channel}:\n`, err); + console.error(`Error while checking poll with guildId=${guildId} and pollId=${pollId}:\n`, err); } } } + async getPollMsgs({ guildId, channel, messages }: PollObj) + { + const gui = this.client.guilds.cache.find(g => g.id === guildId); + if(!gui) return; + const chan = (await gui.channels.fetch()).find(c => c.id === channel); + + return (chan as TextChannel | undefined)?.messages.cache + .filter(m => messages.includes(m.id)) + .sort((a, b) => a.createdTimestamp < b.createdTimestamp ? 1 : -1); + } + getConclusionEmbed(finalVotes: PollVote[], startTime: Date, endTime: Date, guildId: string, channelId: string, firstMsgId: string) { const { @@ -259,8 +344,8 @@ export class Poll extends Command const getReducedWinningOpts = (limit?: number) => winningOptions.reduce((a, c, i) => `${a}${ - !limit || i < limit - ? `\n\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} votes**` : ""}` + limit === undefined || i < limit + ? `\n\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} ${autoPlural("vote", c.votes)}**` : ""}` : "" }`, ""); From d79412d75390ee1b36cb0505443d4c2ba61f5523 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 27 Sep 2022 16:11:58 +0200 Subject: [PATCH 20/51] feat: poll --- src/commands/util/Translate.ts | 4 ++++ src/modals/poll.ts | 21 +++++++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/commands/util/Translate.ts b/src/commands/util/Translate.ts index 7f4e02f..67ce93b 100644 --- a/src/commands/util/Translate.ts +++ b/src/commands/util/Translate.ts @@ -5,6 +5,7 @@ import { Command } from "@src/Command"; import { axios, embedify } from "@src/utils"; import { settings } from "@src/settings"; import languages from "@assets/languages.json"; +import { isArrayEmpty } from "svcorelib"; export class Translate extends Command { @@ -91,6 +92,9 @@ export class Translate extends Command else trParts = [trParts?.[0]?.[0]]; + if(isArrayEmpty(trParts) === true) + return null; + const translation = trParts .filter((p: unknown) => typeof p === "string") .join("").trim(); diff --git a/src/modals/poll.ts b/src/modals/poll.ts index ff0224b..16facf9 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -2,7 +2,7 @@ import { EmbedBuilder, EmbedField, Message, MessageOptions, ModalSubmitInteracti import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; -import { embedify } from "@src/utils"; +import { embedify, padStart } from "@src/utils"; import { createNewGuild, createNewPoll, getGuild, getPolls } from "@src/database/guild"; import { halves } from "svcorelib"; @@ -14,6 +14,9 @@ export class CreatePollModal extends Modal constructor(headline?: string, votesPerUser = 1, title: string | undefined = undefined) { + const p = padStart, d = new Date(); + const defaultExpiry = `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`; + // TODO: persist initial value of modal inputs with redis so the data is kept when a user fucks up the time super({ title: "Create a poll", @@ -29,13 +32,15 @@ export class CreatePollModal extends Modal .setCustomId("expiry_date_time") .setLabel("Poll end date and time") .setPlaceholder("YYYY-MM-DD hh:mm (24h, UTC, for today remove date)") - .setMinLength(3) + .setMinLength(5) .setMaxLength(16) .setStyle(TextInputStyle.Short) + .setValue(defaultExpiry) .setRequired(true), new TextInputBuilder() .setCustomId("vote_options") .setLabel("Vote options") + // TODO: support custom emojis .setPlaceholder(`The options the users can choose.\nOne option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) .setMaxLength(Math.min(settings.emojiList.length * 50, 5000)) .setStyle(TextInputStyle.Paragraph) @@ -79,7 +84,7 @@ export class CreatePollModal extends Modal const headline = this.headline; const longFmtRe = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}[\s.,_T]\d{1,2}:\d{1,2}(:\d{1,2})?$/, - shortFmtRe = /^\d{1,2}:\d{1,2}(:\d{1,2})?$/; + shortFmtRe = /^\d{1,2}:\d{1,2}$/; if(!expiry.match(longFmtRe) && !expiry.match(shortFmtRe)) return this.reply(int, embedify("Please make sure the poll end date and time are formatted in one of these formats (24 hours, in UTC / GMT+0 time):\n- `YYYY/MM/DD hh:mm`\n- `hh:mm` (today)", settings.embedColors.error), true); @@ -91,18 +96,22 @@ export class CreatePollModal extends Modal // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, ...rest] = (expiry.match(longFmtRe) ? /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})[\s.,_T](\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) - : /^(\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) + : /^(\d{1,2}):(\d{1,2})$/.exec(expiry) )?.filter(v => v) as string[]; + // TODO:FIXME: this shit is utterly broken const d = new Date(), - today = rest.length > 4 ? [] : [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]; + today = rest.length > 2 ? [] : [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]; const timeParts = [...today, ...rest.map((v, i) => i != 0 ? parseInt(v) : parseInt(v) - new Date().getTimezoneOffset() / 60)] as [number]; const dueTimestamp = new Date(...timeParts); const optionFields = CreatePollModal.reduceOptionFields(voteOptions); - if(dueTimestamp.getTime() < Date.now() + 1000 * 30) + const dueTs = dueTimestamp.getTime(); + const nowTs = new Date().getTime() + 30_000; + + if(dueTs < nowTs) return this.reply(int, embedify("Please enter a date and time that is at least one minute from now.", settings.embedColors.error), true); const ebd = new EmbedBuilder() From b288634d6ff0ab71715994bf941fc30a6928d83b Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 27 Sep 2022 16:13:29 +0200 Subject: [PATCH 21/51] fix: small type issues --- src/types/index.d.ts | 12 ++++++++---- src/utils/PageEmbed.ts | 6 +++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/types/index.d.ts b/src/types/index.d.ts index 3380025..6c03c60 100644 --- a/src/types/index.d.ts +++ b/src/types/index.d.ts @@ -1,12 +1,10 @@ -import { ClientEvents, ApplicationCommandOptionType, BufferResolvable, JSONEncodable, APIAttachment, Attachment, AttachmentBuilder, AttachmentPayload } from "discord.js"; +import { ClientEvents, ApplicationCommandOptionType, BufferResolvable, JSONEncodable, APIAttachment, Attachment, AttachmentBuilder, AttachmentPayload, CommandInteraction, ButtonInteraction, ModalSubmitInteraction, ContextMenuCommandInteraction } from "discord.js"; import { PermissionFlagsBits } from "discord-api-types/v10"; import { ContextMenuCommandType } from "@discordjs/builders"; import { Stream } from "node:stream"; //#MARKER commands -export type AnyCmdInteraction = CommandInteraction | ButtonInteraction | ModalSubmitInteraction | ContextMenuInteraction; - /** A single argument of a slash command */ type CommandArg = BaseCommandArg & (StringCommandArg | NumberCommandArg | IntegerCommandArg | BooleanCommandArg | UserCommandArg | ChannelCommandArg | RoleCommandArg | AttachmentCommandArg); @@ -70,8 +68,12 @@ interface CmdMetaBase { name: string; /** Description that's displayed when typing the command in chat */ desc: string; + // TODO: + // /** Whether this is a global or guild command */ + // type: "guild" | "global"; + /** If this is used, the command is still displayed but errors on use. Only use this in subcommands. */ perms?: PermissionFlagsBits[]; - /** Default member permissions needed to view and use this command */ + /** (for guild commands) member permissions needed to view and use this command */ memberPerms?: PermissionFlagsBits[]; /** Category of the command */ category: CommandCategory; @@ -130,3 +132,5 @@ export interface CtxMeta { //#MARKER discord types export type DiscordAPIFile = BufferResolvable | Stream | JSONEncodable | Attachment | AttachmentBuilder | AttachmentPayload; + +export type AnyInteraction = CommandInteraction | ButtonInteraction | ModalSubmitInteraction | ContextMenuCommandInteraction; diff --git a/src/utils/PageEmbed.ts b/src/utils/PageEmbed.ts index b50eb37..edc0353 100644 --- a/src/utils/PageEmbed.ts +++ b/src/utils/PageEmbed.ts @@ -8,7 +8,7 @@ import { Command } from "@src/Command"; import { btnListener } from "@src/registry"; import { useEmbedify } from "./embedify"; import { settings } from "@src/settings"; -import { AnyCmdInteraction, DiscordAPIFile } from "@src/types"; +import { AnyInteraction, DiscordAPIFile } from "@src/types"; type BtnType = "first" | "prev" | "next" | "last"; @@ -57,7 +57,7 @@ export class PageEmbed extends EmitterBase private readonly settings: PageEmbedSettings; private msg?: Message; - private int?: AnyCmdInteraction; + private int?: AnyInteraction; private btns: ButtonBuilder[]; private pages: APIEmbed[] = []; @@ -481,7 +481,7 @@ export class PageEmbed extends EmitterBase } /** Call this function once to reply to or edit an interaction with this PageEmbed. This is the interactions' equivalent of `sendIn()` */ - public async useInt(int: AnyCmdInteraction, ephemeral = false) + public async useInt(int: AnyInteraction, ephemeral = false) { if(!int.deferred) await int.deferReply(); From b90604e3341f812c94662aba6cf887fc890e6076 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 27 Sep 2022 16:13:44 +0200 Subject: [PATCH 22/51] feat: some util funcs --- src/modals/poll.ts | 4 ++-- src/utils/misc.ts | 12 ++++++++++++ src/utils/time.ts | 14 +++++++++++++- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 16facf9..e868439 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -2,7 +2,7 @@ import { EmbedBuilder, EmbedField, Message, MessageOptions, ModalSubmitInteracti import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; -import { embedify, padStart } from "@src/utils"; +import { embedify, zeroPad } from "@src/utils"; import { createNewGuild, createNewPoll, getGuild, getPolls } from "@src/database/guild"; import { halves } from "svcorelib"; @@ -14,7 +14,7 @@ export class CreatePollModal extends Modal constructor(headline?: string, votesPerUser = 1, title: string | undefined = undefined) { - const p = padStart, d = new Date(); + const p = zeroPad, d = new Date(); const defaultExpiry = `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`; // TODO: persist initial value of modal inputs with redis so the data is kept when a user fucks up the time diff --git a/src/utils/misc.ts b/src/utils/misc.ts index a932528..3d204e7 100644 --- a/src/utils/misc.ts +++ b/src/utils/misc.ts @@ -8,3 +8,15 @@ export function truncField(content: string, endStr = "...") { return truncStr(content, 1024 - endStr.length, endStr); } + +/** + * Automatically appends an `s` to the passed `word`, if `num` is not equal to 1 + * @param word A word in singular form, to auto-convert to plural + * @param num If this is an array, the amount of items is used + */ +export function autoPlural(word: string, num: number | unknown[]) +{ + if(Array.isArray(num)) + num = num.length; + return `${word}${num === 1 ? "" : "s"}`; +} diff --git a/src/utils/time.ts b/src/utils/time.ts index 8e0a96e..e3638c8 100644 --- a/src/utils/time.ts +++ b/src/utils/time.ts @@ -1,4 +1,4 @@ -import { ParseDurationResult } from "svcorelib"; +import { ParseDurationResult, Stringifiable } from "svcorelib"; export function formatSeconds(seconds: number): string { const date = new Date(1970, 0, 1); @@ -39,3 +39,15 @@ export function timeToMs(timeObj: Partial) + 1000 * 60 * 60 * 24 * 365 * (timeObj?.years ?? 0) ); } + +/** + * Pads a passed value with leading zeroes until a length is reached. Examples: + * `zeroPad(9)` -> `09` + * `zeroPad(99)` -> `99` + * `zeroPad(99, 5)` -> `00099` + * @param value Any stringifiable value to pad with zeroes + * @param padLength The desired length to pad to - default is 2 + */ +export function zeroPad(value: Stringifiable, padLength = 2) { + return String(value).padStart(padLength, "0"); +} From e12b8176a46f3dc4a4ff80be34f9cd57860fb7d1 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sat, 1 Oct 2022 01:01:23 +0200 Subject: [PATCH 23/51] I will actually end someone --- src/commands/util/Reminder.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index ab641b3..95e8a66 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -255,7 +255,7 @@ export class Reminder extends Command return await int.editReply(useEmbedify(`Successfully deleted the reminder \`${name}\``, settings.embedColors.default)); }; - if(remIdent.match(/d+/)) + if(remIdent.match(/\d+/)) { const remId = parseInt(remIdent); const rem = await getReminder(remId, user.id); From 9b3853f40f11a0a874bd6363ce17f0e3ffa9a51c Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sat, 1 Oct 2022 01:01:39 +0200 Subject: [PATCH 24/51] fix: steam error logging cause i cant code for shit --- src/commands/fun/Steam.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/commands/fun/Steam.ts b/src/commands/fun/Steam.ts index d691c20..666e1c5 100644 --- a/src/commands/fun/Steam.ts +++ b/src/commands/fun/Steam.ts @@ -206,6 +206,7 @@ export class Steam extends Command } catch(err) { + console.error("/steam error:", err); await this.editReply(int, embedify("Can't connect to the Steam API. Please try again later.", settings.embedColors.error)); } } From ba03b7f4cb7cde7697cad7a48c8f3df47c5447f8 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Tue, 4 Oct 2022 00:20:36 +0200 Subject: [PATCH 25/51] fix: update api urls --- package-lock.json | 2 +- src/commands/fun/Cat.ts | 2 +- src/commands/fun/Cheese.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index ab8583b..972c9fa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "brewbot", "version": "0.2.0", - "license": "UNLICENSED", + "license": "AGPL-3.0", "dependencies": { "@discordjs/rest": "^0.5.0", "@prisma/client": "^4.3.1", diff --git a/src/commands/fun/Cat.ts b/src/commands/fun/Cat.ts index 86658ea..e165f0f 100644 --- a/src/commands/fun/Cat.ts +++ b/src/commands/fun/Cat.ts @@ -8,7 +8,7 @@ import { settings } from "@src/settings"; const apiInfo = { illusion: { name: "KotAPI", - url: "https://api.illusionman1212.tech/kotapi", + url: "https://api.illusionman1212.com/kotapi", embedFooter: "https://github.com/IllusionMan1212/kotAPI" }, }; diff --git a/src/commands/fun/Cheese.ts b/src/commands/fun/Cheese.ts index c314dfc..2c2663e 100644 --- a/src/commands/fun/Cheese.ts +++ b/src/commands/fun/Cheese.ts @@ -85,7 +85,7 @@ export class Cheese extends Command ebdTitle = "**{NAME}**:"; } - const { data, status, statusText } = await axios.get(`https://api.illusionman1212.tech/cheese${urlPath}${urlParams}`, { timeout: 10000 }); + const { data, status, statusText } = await axios.get(`https://api.illusionman1212.com/cheese${urlPath}${urlParams}`, { timeout: 10000 }); if(status < 200 || status >= 300) return await this.editReply(int, embedify(`Say Cheese is currently unreachable. Please try again later.\nStatus: ${status} - ${statusText}`, settings.embedColors.error)); From 8dbae03b0efd5ecb74f98002aa3992f4526ccb0d Mon Sep 17 00:00:00 2001 From: Sv443 Date: Tue, 4 Oct 2022 00:20:50 +0200 Subject: [PATCH 26/51] fix: reminder improvements --- src/commands/util/Reminder.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index 95e8a66..43f3cfa 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -5,7 +5,7 @@ import { settings } from "@src/settings"; import { time } from "@discordjs/builders"; import { createNewUser, deleteReminder, deleteReminders, getExpiredReminders, getReminder, getReminders, getUser, setReminder } from "@src/database/users"; import { Reminder as ReminderObj } from "@prisma/client"; -import { BtnMsg, embedify, PageEmbed, timeToMs, toUnix10, useEmbedify } from "@src/utils"; +import { autoPlural, BtnMsg, embedify, PageEmbed, timeToMs, toUnix10, useEmbedify } from "@src/utils"; /** Max reminders per user (global) */ const reminderLimit = 10; @@ -255,13 +255,15 @@ export class Reminder extends Command return await int.editReply(useEmbedify(`Successfully deleted the reminder \`${name}\``, settings.embedColors.default)); }; + const notFound = () => int.editReply(useEmbedify("Couldn't find a reminder with this name.\nUse `/reminder list` to list all your reminders and their IDs.", settings.embedColors.error)); + if(remIdent.match(/\d+/)) { const remId = parseInt(remIdent); const rem = await getReminder(remId, user.id); if(!rem) - return await int.editReply(useEmbedify("Couldn't find a reminder with this ID.\nUse `/reminder list` to list all your reminders and their IDs.", settings.embedColors.error)); + return notFound(); return deleteRem(rem); } @@ -269,8 +271,6 @@ export class Reminder extends Command { const rems = await getReminders(user.id); - const notFound = () => int.editReply(useEmbedify("Couldn't find a reminder with this name.\nUse `/reminder list` to list all your reminders and their IDs.", settings.embedColors.error)); - if(!rems || rems.length === 0) return notFound(); @@ -302,8 +302,8 @@ export class Reminder extends Command const cont = embedify(`Are you sure you want to delete ${rems.length > 1 ? `all ${rems.length} reminders` : "your 1 reminder"}?\nThis action cannot be undone.`, settings.embedColors.warning); const btns: ButtonBuilder[] = [ - new ButtonBuilder().setLabel("Delete all").setStyle(ButtonStyle.Danger).setEmoji("🗑️"), - new ButtonBuilder().setLabel("Cancel").setStyle(ButtonStyle.Secondary).setEmoji("❌"), + new ButtonBuilder().setLabel(`Delete ${autoPlural("reminder", rems.length)}`).setStyle(ButtonStyle.Danger).setEmoji("🗑️"), + new ButtonBuilder().setLabel("Cancel").setStyle(ButtonStyle.Secondary), ]; const bm = new BtnMsg(cont, btns, { @@ -314,7 +314,7 @@ export class Reminder extends Command if(bt.data.label === btns.find(b => b.data.label)?.data.label) { await deleteReminders(rems.map(r => r.reminderId), user.id); - await btInt.reply({ ...useEmbedify("Deleted all reminders.", settings.embedColors.default), ephemeral: true }); + await btInt.reply({ ...useEmbedify(`${rems.length > 1 ? `All ${rems.length} reminders have` : "Your 1 reminder has"} been deleted successfully.`, settings.embedColors.default), ephemeral: true }); } else await btInt.reply({ ...useEmbedify("Canceled deletion.", settings.embedColors.default), ephemeral: true }); From 3e7e0e21a722ffd54cc99f3e7ce0accc286a2a43 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 4 Oct 2022 15:10:40 +0200 Subject: [PATCH 27/51] fix: truncField error --- src/commands/util/Reminder.ts | 2 +- src/modals/exec.ts | 218 ++++++++++++++++++---------------- 2 files changed, 116 insertions(+), 104 deletions(-) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index 43f3cfa..f7c878f 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -359,7 +359,7 @@ export class Reminder extends Command const getExpiredEbd = ({ name }: ReminderObj) => new EmbedBuilder() .setTitle("Reminder") .setColor(settings.embedColors.default) - .setDescription(`Your reminder with the name \`${name}\` has expired!`); + .setDescription(`The following reminder has expired:\n>>> ${name}`); const guildFallback = (rem: ReminderObj) => { try diff --git a/src/modals/exec.ts b/src/modals/exec.ts index aaa97b2..7d3abb2 100644 --- a/src/modals/exec.ts +++ b/src/modals/exec.ts @@ -4,7 +4,7 @@ import { transpile } from "typescript"; import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; -import { truncField, } from "@src/utils"; +import { embedify, truncField } from "@src/utils"; export class ExecModal extends Modal { @@ -28,112 +28,124 @@ export class ExecModal extends Modal } async submit(int: ModalSubmitInteraction<"cached">): Promise { - const { channel, user, guild, client } = int; - - unused(channel, user, guild, client); - - const code = int.fields.getTextInputValue("code").trim(); - - await this.deferReply(int, this.ephemeral); - - let result, error; - try - { - const lines = [ - "import { EmbedBuilder, ButtonBuilder, Colors, CommandInteraction, ButtonInteraction, Collection, User, Member, Guild } from \"discord.js\";", - "import { BtnMsg, PageEmbed, embedify, useEmbedify, toUnix10, truncStr, truncField } from \"../utils/\";", - "(async () => {", - code, - "})();", - ]; - - const jsCode = transpile(lines.join("\n"), { - allowJs: true, - allowSyntheticDefaultImports: true, - allowUnreachableCode: true, - esModuleInterop: true, - experimentalDecorators: true, - importHelpers: true, - resolveJsonModule: true, - strict: false, - }); - - result = eval(jsCode); - - if(result instanceof Promise) - result = await result; + try { + const { channel, user, guild, client } = int; + + unused(channel, user, guild, client); + + const code = int.fields.getTextInputValue("code").trim(); + + await this.deferReply(int, this.ephemeral); + + let result, error; + try + { + const lines = [ + "import { EmbedBuilder, ButtonBuilder, Colors, CommandInteraction, ButtonInteraction, Collection, User, Member, Guild } from \"discord.js\";", + "import { BtnMsg, PageEmbed, embedify, useEmbedify, toUnix10, truncStr, truncField } from \"../utils/\";", + "(async () => {", + code, + "})();", + ]; + + const jsCode = transpile(lines.join("\n"), { + allowJs: true, + allowSyntheticDefaultImports: true, + allowUnreachableCode: true, + esModuleInterop: true, + experimentalDecorators: true, + importHelpers: true, + resolveJsonModule: true, + strict: false, + }); + + result = eval(jsCode); + + if(result instanceof Promise) + result = await result; + } + catch(err) + { + if(err instanceof Error) + error = `${err.name}: ${err.message}\n${err.stack}`; + else + error = String(err); + } + + const ebd = new EmbedBuilder() + .setTitle(`Execution ${error ? "Error" : "Result"}`) + .setColor(error ? settings.embedColors.error : settings.embedColors.success); + + if(!error) + { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const findType = (val: any) => { + const primitives = [ "bigint", "boolean", "function", "number", "object", "string", "symbol", "undefined" ]; + + const cName = val?.constructor?.name; + + for(const pr of primitives) + if(typeof val === pr) + return primitives.includes(cName?.toLowerCase() ?? "_") ? pr : cName; + + return "unknown"; + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const transformRes = (result: any) => { + const bufTruncLen = 16; + + if(result instanceof Buffer) + result = ` i < bufTruncLen ? + (a + ((i > 0 ? " " : "") + c.toString(16))) + : (i === bufTruncLen ? a + " ..." : a), + "") + }>\n\nStringified:\n${result.toString()}`; + + if(typeof result === "string" || String(result).length > 1000) + return truncField(String(result)); + else return result; + }; + + const resStr = String(result).trim(); + + ebd.addFields([ + { + name: `Result <\`${findType(result)}\`>:`, + value: `\`\`\`\n${resStr.length > 0 ? transformRes(result) : "(empty)"}\n\`\`\``, + inline: false + }, + { + name: "Code:", + value: `\`\`\`ts\n${code}\n\`\`\``, + inline: false + } + ]); + } + else + ebd.addFields([ + { + name: "Error:", + value: `\`\`\`\n${truncField(String(error))}\n\`\`\``, + inline: false + }, + { + name: "Code:", + value: `\`\`\`ts\n${code}\n\`\`\``, + inline: false + } + ]); + + await this.editReply(int, ebd); } catch(err) { - if(err instanceof Error) - error = `${err.name}: ${err.message}\n${err.stack}`; - else - error = String(err); - } + const ebd = embedify(`Couldn't exec due to an error: ${err}`, settings.embedColors.error); - const ebd = new EmbedBuilder() - .setTitle(`Execution ${error ? "Error" : "Result"}`) - .setColor(error ? settings.embedColors.error : settings.embedColors.success); - - if(!error) - { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const findType = (val: any) => { - const primitives = [ "bigint", "boolean", "function", "number", "object", "string", "symbol", "undefined" ]; - - const cName = val?.constructor?.name; - - for(const pr of primitives) - if(typeof val === pr) - return primitives.includes(cName?.toLowerCase() ?? "_") ? pr : cName; - - return "unknown"; - }; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const transformRes = (result: any) => { - const bufTruncLen = 16; - - if(result instanceof Buffer) - result = ` i < bufTruncLen ? - (a + ((i > 0 ? " " : "") + c.toString(16))) - : (i === bufTruncLen ? a + " ..." : a), - "") - }>\n\nStringified:\n${result.toString()}`; - - return truncField(result); - }; - - const resStr = String(result).trim(); - - ebd.addFields([ - { - name: `Result <\`${findType(result)}\`>:`, - value: `\`\`\`\n${resStr.length > 0 ? transformRes(result) : "(empty)"}\n\`\`\``, - inline: false - }, - { - name: "Code:", - value: `\`\`\`ts\n${code}\n\`\`\``, - inline: false - } - ]); + if(int.replied || int.deferred) + return this.editReply(int, ebd); + return this.reply(int, ebd); } - else - ebd.addFields([ - { - name: "Error:", - value: `\`\`\`\n${truncField(error)}\n\`\`\``, - inline: false - }, - { - name: "Code:", - value: `\`\`\`ts\n${code}\n\`\`\``, - inline: false - } - ]); - - await this.editReply(int, ebd); } } From ae971c2ad5fc32c4dbe8511e7bc166a5a2cf9bb0 Mon Sep 17 00:00:00 2001 From: Sven Date: Wed, 5 Oct 2022 21:25:04 +0200 Subject: [PATCH 28/51] I am about to commit multiple counts of arson --- src/commands/util/Reminder.ts | 46 +++++++++++++++++------------------ 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index f7c878f..35f965b 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -9,11 +9,12 @@ import { autoPlural, BtnMsg, embedify, PageEmbed, timeToMs, toUnix10, useEmbedif /** Max reminders per user (global) */ const reminderLimit = 10; +const reminderCheckInterval = 2000; export class Reminder extends Command { /** - * Contains all reminders that are currently being checked. + * Contains all compound keys of reminders that are currently being checked. * Format: `userId-reminderId` */ private reminderCheckBuffer = new Set(); @@ -109,14 +110,12 @@ export class Reminder extends Command if(client instanceof Client) { - try - { + try { // since the constructor is called exactly once at startup, this should work just fine this.checkReminders(client); - setInterval(() => this.checkReminders(client), 2000); + setInterval(() => this.checkReminders(client), reminderCheckInterval); } - catch(err) - { + catch(err) { console.error(k.red("Error while checking reminders:"), err); } } @@ -159,7 +158,7 @@ export class Reminder extends Command const reminders = await getReminders(user.id); if(reminders && reminders.length >= reminderLimit) - return await int.editReply(useEmbedify("Sorry, but you can't set more than 10 reminders.\nPlease free up some space with `/reminder delete`", settings.embedColors.error)); + return await int.editReply(useEmbedify("Sorry, but you can't set more than 10 reminders.\nPlease wait until a reminder expires or free up some space with `/reminder delete`", settings.embedColors.error)); const reminderId = reminders && reminders.length > 0 && reminders.at(-1) ? reminders.at(-1)!.reminderId + 1 @@ -177,7 +176,7 @@ export class Reminder extends Command channel: channel?.id ?? null, reminderId, dueTimestamp, - private: ephemeral, + private: guild?.id ? ephemeral : true, }); return await this.editReply(int, embedify(`I've set a reminder with the name \`${name}\` (ID \`${reminderId}\`)\nDue: ${time(toUnix10(dueTimestamp), "f")}\n\nTo list your reminders, use \`/reminder list\``, settings.embedColors.success)); @@ -349,11 +348,6 @@ export class Reminder extends Command if(!expRems || expRems.length === 0) return; - this.reminderCheckBuffer = new Set([ - ...this.reminderCheckBuffer, - ...expRems.map(r => `${r.userId}-${r.reminderId}`), - ]); - const promises: Promise[] = []; const getExpiredEbd = ({ name }: ReminderObj) => new EmbedBuilder() @@ -361,9 +355,8 @@ export class Reminder extends Command .setColor(settings.embedColors.default) .setDescription(`The following reminder has expired:\n>>> ${name}`); - const guildFallback = (rem: ReminderObj) => { - try - { + const guildFallback = async (rem: ReminderObj) => { + try { if(rem.private) throw new Error("Can't send message in guild as reminder is private."); @@ -376,8 +369,7 @@ export class Reminder extends Command c.send({ embeds: [ getExpiredEbd(rem) ] }); } } - catch(err) - { + catch(err) { // TODO: track reminder "loss rate" // // I │ I I @@ -386,17 +378,25 @@ export class Reminder extends Command void err; } - finally - { - deleteReminder(rem.reminderId, rem.userId); - this.reminderCheckBuffer.delete(`${rem.userId}-${rem.reminderId}`); + finally { + try { + await deleteReminder(rem.reminderId, rem.userId); + } + catch(err) { + // TODO: see above + } + finally { + this.reminderCheckBuffer.delete(`${rem.userId}-${rem.reminderId}`); + } } }; for(const rem of expRems) { if(this.reminderCheckBuffer.has(`${rem.userId}-${rem.reminderId}`)) - return; + continue; + + this.reminderCheckBuffer.add(`${rem.userId}-${rem.reminderId}`); const usr = client.users.cache.find(u => u.id === rem.userId); From 8f339d15ebbb60cd258bccad386d4c35df102cd7 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 11 Oct 2022 16:31:05 +0200 Subject: [PATCH 29/51] chore: update SCL --- package-lock.json | 77 +++++++++++++++++++++++------------------------ package.json | 4 +-- 2 files changed, 39 insertions(+), 42 deletions(-) diff --git a/package-lock.json b/package-lock.json index 972c9fa..7c45f15 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,7 +26,7 @@ "redis": "^4.2.0", "simple-statistics": "^7.7.5", "steamapi": "^2.2.0", - "svcorelib": "^1.16.0", + "svcorelib": "^1.18.0", "yargs": "^17.5.1" }, "bin": { @@ -806,14 +806,6 @@ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, - "node_modules/at-least-node": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", - "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", - "engines": { - "node": ">= 4.0.0" - } - }, "node_modules/axios": { "version": "0.27.2", "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", @@ -3424,28 +3416,33 @@ } }, "node_modules/svcorelib": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.16.0.tgz", - "integrity": "sha512-fUd47yM8R5KY8LkrGqvUSYeQZtnlcbjuOHbOuLS3ItasavLZoP9Weg3BW4ZuPUjSAmf+zrH7rVzhONMzmOsZUw==", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.18.0.tgz", + "integrity": "sha512-enBkQvnpNDlyfWSOjciZlx9xpz2a4tImqehb49bG9WGdMzZTzDLEgEeHYYb+Zt5F8JLy1o1WmHetZYfuI8zysA==", "dependencies": { "deep-diff": "^1.0.2", - "fs-extra": "^9.0.1", + "fs-extra": "^10.1.0", "keypress": "^0.2.1", - "minimatch": "^3.0.4" + "minimatch": "^5.1.0" }, "optionalDependencies": { "mysql": "^2.18.1" } }, - "node_modules/svcorelib/node_modules/fs-extra": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", - "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "node_modules/svcorelib/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", "dependencies": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" + "balanced-match": "^1.0.0" + } + }, + "node_modules/svcorelib/node_modules/minimatch": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz", + "integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==", + "dependencies": { + "brace-expansion": "^2.0.1" }, "engines": { "node": ">=10" @@ -4487,11 +4484,6 @@ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, - "at-least-node": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", - "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==" - }, "axios": { "version": "0.27.2", "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", @@ -6420,26 +6412,31 @@ } }, "svcorelib": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.16.0.tgz", - "integrity": "sha512-fUd47yM8R5KY8LkrGqvUSYeQZtnlcbjuOHbOuLS3ItasavLZoP9Weg3BW4ZuPUjSAmf+zrH7rVzhONMzmOsZUw==", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.18.0.tgz", + "integrity": "sha512-enBkQvnpNDlyfWSOjciZlx9xpz2a4tImqehb49bG9WGdMzZTzDLEgEeHYYb+Zt5F8JLy1o1WmHetZYfuI8zysA==", "requires": { "deep-diff": "^1.0.2", - "fs-extra": "^9.0.1", + "fs-extra": "^10.1.0", "keypress": "^0.2.1", - "minimatch": "^3.0.4", + "minimatch": "^5.1.0", "mysql": "^2.18.1" }, "dependencies": { - "fs-extra": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", - "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "requires": { + "balanced-match": "^1.0.0" + } + }, + "minimatch": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz", + "integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==", "requires": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" + "brace-expansion": "^2.0.1" } } } diff --git a/package.json b/package.json index 8d8c31f..0012235 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,7 @@ "redis": "^4.2.0", "simple-statistics": "^7.7.5", "steamapi": "^2.2.0", - "svcorelib": "^1.16.0", + "svcorelib": "^1.18.0", "yargs": "^17.5.1" }, "bin": { @@ -79,4 +79,4 @@ "prisma": { "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts" } -} \ No newline at end of file +} From 632693c86ffa09c73f06114d5bd0f5a90f456dbb Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 11 Oct 2022 17:20:09 +0200 Subject: [PATCH 30/51] chore: bump SCL --- package-lock.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7c45f15..ca1878a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,7 +26,7 @@ "redis": "^4.2.0", "simple-statistics": "^7.7.5", "steamapi": "^2.2.0", - "svcorelib": "^1.18.0", + "svcorelib": "^1.18.1", "yargs": "^17.5.1" }, "bin": { @@ -3416,9 +3416,9 @@ } }, "node_modules/svcorelib": { - "version": "1.18.0", - "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.18.0.tgz", - "integrity": "sha512-enBkQvnpNDlyfWSOjciZlx9xpz2a4tImqehb49bG9WGdMzZTzDLEgEeHYYb+Zt5F8JLy1o1WmHetZYfuI8zysA==", + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.18.1.tgz", + "integrity": "sha512-OJBg7OAX75v3aPKzOwSlj9KSvdorXm65SSsSxlTSf1ZLE6Mn6LjXLDfPd09pEZrFlm8bMBsiDmAE1P0woA6J0A==", "dependencies": { "deep-diff": "^1.0.2", "fs-extra": "^10.1.0", @@ -6412,9 +6412,9 @@ } }, "svcorelib": { - "version": "1.18.0", - "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.18.0.tgz", - "integrity": "sha512-enBkQvnpNDlyfWSOjciZlx9xpz2a4tImqehb49bG9WGdMzZTzDLEgEeHYYb+Zt5F8JLy1o1WmHetZYfuI8zysA==", + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/svcorelib/-/svcorelib-1.18.1.tgz", + "integrity": "sha512-OJBg7OAX75v3aPKzOwSlj9KSvdorXm65SSsSxlTSf1ZLE6Mn6LjXLDfPd09pEZrFlm8bMBsiDmAE1P0woA6J0A==", "requires": { "deep-diff": "^1.0.2", "fs-extra": "^10.1.0", diff --git a/package.json b/package.json index 0012235..532b85a 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,7 @@ "redis": "^4.2.0", "simple-statistics": "^7.7.5", "steamapi": "^2.2.0", - "svcorelib": "^1.18.0", + "svcorelib": "^1.18.1", "yargs": "^17.5.1" }, "bin": { From 3cb91e19602dab661c4751d133215935d25535e5 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 11 Oct 2022 17:20:24 +0200 Subject: [PATCH 31/51] fix: random poll stuff --- src/commands/util/Poll.ts | 41 +++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index c7a6bdf..1b3a121 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -7,10 +7,10 @@ import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import { Poll as PollObj } from "@prisma/client"; import k from "kleur"; -interface PollVote { - msg: M; +interface PollVote { + msg: Message; emoji: string; - option: O; + option: string; votes: string[] } @@ -18,6 +18,8 @@ export class Poll extends Command { private interval?: NodeJS.Timer; private client: Client; + /** Format: `guildId-pollId` */ + private checkPollsBuffer = new Set(); constructor(client: Client) { @@ -183,7 +185,10 @@ export class Poll extends Command if(!memberPermissions?.has(PermissionFlagsBits.ManageChannels) && user.id !== poll.createdBy) return this.editReply(int, embedify("You are not the author of this poll so you can't delete it.", settings.embedColors.error)); - const pollMsgs = (await this.getPollMsgs(poll))!; //#DBG + const pollMsgs = await this.getPollMsgs(poll); + + if(!pollMsgs) + return this.editReply(int, embedify("You can only use this command in a server.", settings.embedColors.error)); const finalVotes = await this.accumulateVotes(pollMsgs.reduce((a, c) => { a.push(c as never); return a; }, []), poll.voteOptions); @@ -258,15 +263,19 @@ export class Poll extends Command { const expPolls = await getExpiredPolls(); - for await(const poll of expPolls) - { + for await(const poll of expPolls) { const { guildId, pollId, channel, voteOptions, dueTimestamp: endTime } = poll; - try - { + const bufferKey = `${guildId}-${pollId}`; + + if(this.checkPollsBuffer.has(bufferKey)) + continue; + + this.checkPollsBuffer.add(bufferKey); + + try { const msgs = await this.getPollMsgs(poll); - if(msgs && msgs.size > 0) - { + if(msgs && msgs.size > 0) { const firstMsg = msgs.at(0)!; const finalVotes = await this.accumulateVotes(msgs.reduce((a, c) => { a.push(c as never); return a; }, []), voteOptions); @@ -281,11 +290,13 @@ export class Poll extends Command deletePoll(guildId, pollId); } - catch(err) - { + catch(err) { // TODO: add logging lib console.error(`Error while checking poll with guildId=${guildId} and pollId=${pollId}:\n`, err); } + finally { + this.checkPollsBuffer.delete(bufferKey); + } } } @@ -361,13 +372,13 @@ export class Poll extends Command }; } - async sendConclusion(msg: Message, finalVotes: PollVote[], startTime: Date, endTime: Date) + sendConclusion(msg: Message, finalVotes: PollVote[], startTime: Date, endTime: Date) { // TODO: const { peopleVoted, getReducedWinningOpts } = this.parseFinalVotes(finalVotes); - await msg.reply({ embeds: [ + return msg.reply({ embeds: [ new EmbedBuilder() .setColor(settings.embedColors.default) .setTitle("This poll has closed.") @@ -377,7 +388,7 @@ export class Poll extends Command async accumulateVotes(msgs: Message[], _voteOpts: string[]): Promise { - for(const msg of msgs as unknown as Message[]) + for await(const msg of msgs) { const reacts = msg.reactions.cache.entries(); From b6d0b2d5567178fbeb9f1fbfde37c21ef5813711 Mon Sep 17 00:00:00 2001 From: Sven Date: Tue, 11 Oct 2022 17:30:51 +0200 Subject: [PATCH 32/51] fix: use redis instead of Set cause node hates it --- src/commands/util/Poll.ts | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 1b3a121..313e886 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,11 +1,14 @@ import { ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, PermissionFlagsBits, TextChannel } from "discord.js"; +import k from "kleur"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; import { autoPlural, BtnMsg, embedify, PageEmbed, toUnix10, truncStr, useEmbedify } from "@src/utils"; import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import { Poll as PollObj } from "@prisma/client"; -import k from "kleur"; +import { getRedis } from "@src/redis"; + +const redis = getRedis(); interface PollVote { msg: Message; @@ -16,10 +19,7 @@ interface PollVote { export class Poll extends Command { - private interval?: NodeJS.Timer; private client: Client; - /** Format: `guildId-pollId` */ - private checkPollsBuffer = new Set(); constructor(client: Client) { @@ -79,13 +79,11 @@ export class Poll extends Command try { this.checkPolls(); - this.interval = setInterval(this.checkPolls, 2000); + setInterval(this.checkPolls, 2000); } catch(err) { console.error(k.red("Error while checking polls:"), err); } - - ["SIGINT", "SIGTERM"].forEach(sig => process.on(sig, () => clearInterval(this.interval))); } async run(int: CommandInteraction, opt: CommandInteractionOption): Promise @@ -265,12 +263,12 @@ export class Poll extends Command for await(const poll of expPolls) { const { guildId, pollId, channel, voteOptions, dueTimestamp: endTime } = poll; - const bufferKey = `${guildId}-${pollId}`; + const redisKey = `check_poll_${guildId}-${pollId}`; - if(this.checkPollsBuffer.has(bufferKey)) + if(!(await redis.get(redisKey))) continue; - this.checkPollsBuffer.add(bufferKey); + await redis.set(redisKey, 1); try { const msgs = await this.getPollMsgs(poll); @@ -295,7 +293,7 @@ export class Poll extends Command console.error(`Error while checking poll with guildId=${guildId} and pollId=${pollId}:\n`, err); } finally { - this.checkPollsBuffer.delete(bufferKey); + await redis.del(redisKey); } } } From ed1f3a8a57385daeab7f72f0da052c794bffbb04 Mon Sep 17 00:00:00 2001 From: Sven Date: Wed, 12 Oct 2022 14:32:57 +0200 Subject: [PATCH 33/51] fix: timeouts of btnmsg and pageembed --- src/utils/BtnMsg.ts | 2 +- src/utils/PageEmbed.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/BtnMsg.ts b/src/utils/BtnMsg.ts index 145c545..c0fafba 100644 --- a/src/utils/BtnMsg.ts +++ b/src/utils/BtnMsg.ts @@ -59,7 +59,7 @@ export class BtnMsg extends EmitterBase }); const defaultOpts: BtnMsgOpts = { - timeout: 1000 * 60 * 30, + timeout: 14 * 60 * 1000, }; this.opts = { ...defaultOpts, ...options }; diff --git a/src/utils/PageEmbed.ts b/src/utils/PageEmbed.ts index edc0353..e710137 100644 --- a/src/utils/PageEmbed.ts +++ b/src/utils/PageEmbed.ts @@ -92,7 +92,7 @@ export class PageEmbed extends EmitterBase const defSett: PageEmbedSettings = { firstLastBtns: true, goToPageBtn: true, - timeout: 30 * 60 * 1000, + timeout: 14 * 60 * 1000, overflow: true, allowAllUsersTimeout: -1, }; From 4a458f1952988cf8f011e4faac1385072ce76be0 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Thu, 13 Oct 2022 17:45:59 +0200 Subject: [PATCH 34/51] fix: when want GET HEAD --- src/commands/util/Avatar.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/util/Avatar.ts b/src/commands/util/Avatar.ts index 5fab5fc..cc5aecc 100644 --- a/src/commands/util/Avatar.ts +++ b/src/commands/util/Avatar.ts @@ -49,7 +49,7 @@ export class Avatar extends Command try { if(requestedAvUrl) - status = (await axios.get(requestedAvUrl)).status; + status = (await axios.head(requestedAvUrl)).status; } catch(err) { From 665b3212d2e02261bfa912df85ba7b7c2ecded3a Mon Sep 17 00:00:00 2001 From: Sven Date: Fri, 21 Oct 2022 00:51:44 +0200 Subject: [PATCH 35/51] still unfinished poll shit ngl --- src/commands/util/Poll.ts | 16 ++++++--- src/modals/poll.ts | 70 +++++++++++++++++++++++++++++---------- 2 files changed, 64 insertions(+), 22 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 313e886..47d352c 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -50,8 +50,8 @@ export class Poll extends Command }, // TODO: // { - // name: "allow_rethinking", - // desc: "Set this to false to disallow people to change their mind and choose another option.", + // name: "allow_changing", + // desc: "Set this to False to disallow people to change their mind and choose another option.", // type: ApplicationCommandOptionType.Boolean, // }, ], @@ -107,7 +107,14 @@ export class Poll extends Command const votes_per_user = int.options.get("votes_per_user")?.value as number | undefined; const title = int.options.get("title")?.value as string | undefined; - const modal = new CreatePollModal(headline, votes_per_user, title); + const redisKey = `poll-modal-data_${guild.id}_${int.user.id}`; + + const modalData = await redis.get(redisKey); + const modal = new CreatePollModal(headline, votes_per_user, title, modalData ? JSON.parse(modalData) : undefined); + + modal.on("invalid", (data) => redis.set(redisKey, JSON.stringify(data))); + modal.on("deleteCachedData", () => redis.del(redisKey)); + setTimeout(() => redis.del(redisKey), 1000 * 60 * 5); return await int.showModal(modal.getInternalModal()); } @@ -165,9 +172,8 @@ export class Poll extends Command case "delete": { action = "deleting a poll"; - // TODO: display current results to deleter, maybe in the poll itself? - await this.deferReply(int, true); + await this.deferReply(int); const pollId = int.options.get("poll_id", true).value as number; diff --git a/src/modals/poll.ts b/src/modals/poll.ts index e868439..887dd98 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -6,18 +6,34 @@ import { embedify, zeroPad } from "@src/utils"; import { createNewGuild, createNewPoll, getGuild, getPolls } from "@src/database/guild"; import { halves } from "svcorelib"; +interface PollModalData { + topic: string | null; + expiry: string; + voteOptions: string[]; +} + +export interface CreatePollModal { + /** Emitted on error and unhandled Promise rejection */ + on(event: "error", listener: (err: Error) => void): this; + /** Gets emitted when this modal has finished submitting and needs to be deleted from the registry */ + on(event: "destroy", listener: (btnIds: string[]) => void): this; + /** Emitted when the user submits the modal but it is invalid */ + on(evt: "invalid", listener: (modalData: PollModalData, pollId: string) => void): this; + /** Emitted when the cached modal data should be deleted */ + on(evt: "deleteCachedData", listener: () => void): this; +} + export class CreatePollModal extends Modal { private headline; private votesPerUser; private title; - constructor(headline?: string, votesPerUser = 1, title: string | undefined = undefined) + constructor(headline?: string, votesPerUser = 1, title?: string, modalData?: PollModalData) { const p = zeroPad, d = new Date(); const defaultExpiry = `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`; - // TODO: persist initial value of modal inputs with redis so the data is kept when a user fucks up the time super({ title: "Create a poll", inputs: [ @@ -27,11 +43,12 @@ export class CreatePollModal extends Modal .setPlaceholder("The topic of the poll.\nLeave empty if you sent your own message.\nSupports Discord's Markdown.") .setStyle(TextInputStyle.Paragraph) .setMaxLength(250) - .setRequired(false), + .setRequired(false) + .setValue(modalData?.topic ?? ""), new TextInputBuilder() .setCustomId("expiry_date_time") - .setLabel("Poll end date and time") - .setPlaceholder("YYYY-MM-DD hh:mm (24h, UTC, for today remove date)") + .setLabel("Poll end date and time (24h, UTC)") + .setPlaceholder("YYYY-MM-DD hh:mm (for today, remove date)") .setMinLength(5) .setMaxLength(16) .setStyle(TextInputStyle.Short) @@ -44,7 +61,8 @@ export class CreatePollModal extends Modal .setPlaceholder(`The options the users can choose.\nOne option per line, ${settings.emojiList.length} max.\nSupports Discord's Markdown.`) .setMaxLength(Math.min(settings.emojiList.length * 50, 5000)) .setStyle(TextInputStyle.Paragraph) - .setRequired(true), + .setRequired(true) + .setValue(modalData?.voteOptions.join("\n") ?? ""), ], }); @@ -78,7 +96,9 @@ export class CreatePollModal extends Modal if(!guild || !channel) return; // already handled in the poll command - const topic = int.fields.getTextInputValue("topic").trim(); + const topicRaw = int.fields.getTextInputValue("topic").trim(); + + const topic = topicRaw.length === 0 ? undefined : topicRaw; const expiry = int.fields.getTextInputValue("expiry_date_time").trim(); const voteOptions = int.fields.getTextInputValue("vote_options").trim().split(/\n/gm).filter(v => v.length > 0); const headline = this.headline; @@ -86,12 +106,17 @@ export class CreatePollModal extends Modal const longFmtRe = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}[\s.,_T]\d{1,2}:\d{1,2}(:\d{1,2})?$/, shortFmtRe = /^\d{1,2}:\d{1,2}$/; + const modalInvalid = (msg: string) => { + this.emit("invalid", { topic: topic ?? null, expiry, voteOptions }); + return this.reply(int, embedify(msg, settings.embedColors.error), true); + }; + if(!expiry.match(longFmtRe) && !expiry.match(shortFmtRe)) - return this.reply(int, embedify("Please make sure the poll end date and time are formatted in one of these formats (24 hours, in UTC / GMT+0 time):\n- `YYYY/MM/DD hh:mm`\n- `hh:mm` (today)", settings.embedColors.error), true); + return modalInvalid("Please make sure the poll end date and time are formatted in one of these formats (24 hours, in UTC / GMT+0 time):\n- `YYYY/MM/DD hh:mm`\n- `hh:mm` (today)"); if(voteOptions.length > settings.emojiList.length) - return this.reply(int, embedify(`Please enter ${settings.emojiList.length} vote options at most.`, settings.embedColors.error), true); + return modalInvalid(`Please enter ${settings.emojiList.length} vote options at most.`); if(voteOptions.length < 2) - return this.reply(int, embedify("Please enter at least two options to vote on.", settings.embedColors.error), true); + return modalInvalid("Please enter at least two options to vote on."); // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, ...rest] = (expiry.match(longFmtRe) @@ -100,19 +125,26 @@ export class CreatePollModal extends Modal )?.filter(v => v) as string[]; // TODO:FIXME: this shit is utterly broken - const d = new Date(), - today = rest.length > 2 ? [] : [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]; + const d = new Date(); + let dateParts: number[] = []; - const timeParts = [...today, ...rest.map((v, i) => i != 0 ? parseInt(v) : parseInt(v) - new Date().getTimezoneOffset() / 60)] as [number]; + if(rest.length === 5) + dateParts = rest.map(v => parseInt(v)); + else + dateParts = [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), ...rest.map(v => parseInt(v))]; - const dueTimestamp = new Date(...timeParts); + // parseInt(v) - new Date().getTimezoneOffset() / 60 + + const dueTimestamp = new Date(...<[number]>dateParts); const optionFields = CreatePollModal.reduceOptionFields(voteOptions); const dueTs = dueTimestamp.getTime(); const nowTs = new Date().getTime() + 30_000; + const due = new Date(dueTs), now = new Date(nowTs); + if(dueTs < nowTs) - return this.reply(int, embedify("Please enter a date and time that is at least one minute from now.", settings.embedColors.error), true); + return modalInvalid("Please enter a date and time that is at least one minute from now."); const ebd = new EmbedBuilder() .setTitle(this.title ?? "Poll") @@ -120,10 +152,14 @@ export class CreatePollModal extends Modal .setFooter({ text: `Click the reaction emojis below to cast ${this.votesPerUser === 1 ? "a vote" : "votes"}.` }) .setColor(settings.embedColors.default); - topic.length > 0 && ebd.setDescription(`> **Topic:**${topic.length > 64 ? "\n>" : ""} ${topic}\n`); + topic && topic.length > 0 && ebd.setDescription(`> **Topic:**${topic.length > 64 ? "\n>" : ""} ${topic}\n`); + + this.emit("deleteCachedData"); await this.deferReply(int, true); + console.log(); + // send messages & react try { @@ -177,7 +213,7 @@ export class CreatePollModal extends Modal messages: msgs.map(m => m.id), createdBy: int.user.id, headline: headline ?? null, - topic: topic.length > 0 ? topic : null, + topic: topic && topic.length > 0 ? topic : null, voteOptions, votesPerUser: this.votesPerUser, dueTimestamp, From 18610002c6c7f636e20878372ab021765ee44f21 Mon Sep 17 00:00:00 2001 From: Sven Date: Fri, 21 Oct 2022 00:55:31 +0200 Subject: [PATCH 36/51] fix: implement btnmsg tuple --- src/commands/util/Poll.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 47d352c..8c287ff 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -7,6 +7,7 @@ import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import { Poll as PollObj } from "@prisma/client"; import { getRedis } from "@src/redis"; +import { Tuple } from "@src/types"; const redis = getRedis(); @@ -198,7 +199,7 @@ export class Poll extends Command const { peopleVoted, getReducedWinningOpts } = this.parseFinalVotes(finalVotes); - const btns = [ + const btns: Tuple, 1> = [[ new ButtonBuilder() .setStyle(ButtonStyle.Danger) .setLabel("Delete") @@ -207,7 +208,7 @@ export class Poll extends Command .setStyle(ButtonStyle.Secondary) .setLabel("Cancel") .setEmoji("❌"), - ]; + ]]; const bm = new BtnMsg(embedify(`You are about to delete a poll that ${peopleVoted} ${peopleVoted === 1 ? "person" : "people"} have voted on.\nAre you sure you want to delete the poll? This cannot be undone.`, settings.embedColors.warning), btns, { timeout: 30_000 }); From 65718edb5a4fa1421caeca57b2fe2d04052eab61 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sat, 22 Oct 2022 16:35:07 +0200 Subject: [PATCH 37/51] fix: change casing of jobs --- src/commands/economy/Job.ts | 2 +- src/commands/economy/Jobs.ts | 104 ----------------------------------- src/commands/economy/Work.ts | 2 +- 3 files changed, 2 insertions(+), 106 deletions(-) delete mode 100644 src/commands/economy/Jobs.ts diff --git a/src/commands/economy/Job.ts b/src/commands/economy/Job.ts index cfab2e0..1e8f32c 100644 --- a/src/commands/economy/Job.ts +++ b/src/commands/economy/Job.ts @@ -3,7 +3,7 @@ import { Command } from "@src/Command"; import { getTotalWorks } from "@database/economy"; import { settings } from "@src/settings"; import { embedify } from "@utils/embedify"; -import { Levels, totalWorksToLevel, baseAward } from "@commands/economy/Jobs"; +import { Levels, totalWorksToLevel, baseAward } from "@src/commands/economy/jobs"; export class Job extends Command { constructor() { diff --git a/src/commands/economy/Jobs.ts b/src/commands/economy/Jobs.ts deleted file mode 100644 index 0c0132e..0000000 --- a/src/commands/economy/Jobs.ts +++ /dev/null @@ -1,104 +0,0 @@ -export interface ILevel { - [key: number]: { - name: string, - multiplier: number, - phrases: string[] - } -} - -export const Levels: ILevel = { - 1: { - name: "Beggar", - multiplier: .1, - phrases: [ - "begging for a few hours on the street corner", - "selling your kidney", - "eating a worm", - "singing on the subway", - "doing drugs", - "sleeping" - ] - }, - 2: { - name: "McDonald's Employee", - multiplier: .4, - phrases: [ - "flipping patties", - "getting beaten by your manager", - "getting berated by customers", - ] - }, - 3: { - name: "ShitCoin Trader", - multiplier: .8, - phrases: [ - "selling some doge", - "foreseeing the future", - "trading some CarenCoin for BirbCoin" - ] - }, - 4: { - name: "Twitch Streamer", - multiplier: 1, - phrases: [ - "destroying some 12 year olds", - "playing some fortnite", - "losing in Mario Kart", - "dying to 12 year olds" - ] - }, - 5: { - name: "E-Thot", - multiplier: 1.5, - phrases: [ - "selling feet pics", - "enticing men", - "doing nothing", - "contributing nothing to society" - ] - }, - 6: { - name: "CEO of FartBux", - multiplier: 2.2, - phrases: [ - "providing value to your company", - "adding to the price of FartBux", - "getting new investors", - "stealing from retail investors" - ] - }, - 7: { - name: "Jeff Bezos Jr.", - multiplier: 3, - phrases: [ - "consuming the blood of children", - "using your dad's wealth to build your own", - "\"inventing\" something that was already in use", - "yelling at factory workers for several hours" - ] - }, - 8: { - name: "Elon Musk, Lord and King of Mars", - multiplier: 5, - phrases: [ - "inventing new particles such as Assium and Coomium", - "stealing your employees' ideas", - "harnessing the power of the sun", - "watching over your fellow rich folk on Mars" - ] - } -}; - -export const totalWorksToLevel = (works: number): number => { - // let worksMap = [0, 10, 25, 50, 100, 200, 300, 500]; - if(works >= 500) return 8; - else if(works >= 300) return 7; - else if(works >= 200) return 6; - else if(works >= 100) return 5; - else if(works >= 50) return 4; - else if(works >= 25) return 3; - else if(works >= 10) return 2; - else return 1; -}; - -export const baseAward = 50; diff --git a/src/commands/economy/Work.ts b/src/commands/economy/Work.ts index 46ae98f..4157714 100644 --- a/src/commands/economy/Work.ts +++ b/src/commands/economy/Work.ts @@ -3,7 +3,7 @@ import { Command } from "@src/Command"; import { embedify, formatSeconds, nowInSeconds } from "@utils/index"; import { addCoins, getLastWork, getTotalWorks, incrementTotalWorks, setLastWork } from "@database/economy"; import { createNewMember, getMember } from "@database/users"; -import { Levels, totalWorksToLevel, baseAward } from "@commands/economy/Jobs"; +import { Levels, totalWorksToLevel, baseAward } from "@src/commands/economy/jobs"; import { randomItem } from "svcorelib"; const secs4hours = 14400; From fbf661cd1168bed325adcd0de7349a04b1c8bc39 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sat, 22 Oct 2022 16:35:20 +0200 Subject: [PATCH 38/51] ite --- src/commands/economy/jobs.ts | 104 +++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 src/commands/economy/jobs.ts diff --git a/src/commands/economy/jobs.ts b/src/commands/economy/jobs.ts new file mode 100644 index 0000000..0c0132e --- /dev/null +++ b/src/commands/economy/jobs.ts @@ -0,0 +1,104 @@ +export interface ILevel { + [key: number]: { + name: string, + multiplier: number, + phrases: string[] + } +} + +export const Levels: ILevel = { + 1: { + name: "Beggar", + multiplier: .1, + phrases: [ + "begging for a few hours on the street corner", + "selling your kidney", + "eating a worm", + "singing on the subway", + "doing drugs", + "sleeping" + ] + }, + 2: { + name: "McDonald's Employee", + multiplier: .4, + phrases: [ + "flipping patties", + "getting beaten by your manager", + "getting berated by customers", + ] + }, + 3: { + name: "ShitCoin Trader", + multiplier: .8, + phrases: [ + "selling some doge", + "foreseeing the future", + "trading some CarenCoin for BirbCoin" + ] + }, + 4: { + name: "Twitch Streamer", + multiplier: 1, + phrases: [ + "destroying some 12 year olds", + "playing some fortnite", + "losing in Mario Kart", + "dying to 12 year olds" + ] + }, + 5: { + name: "E-Thot", + multiplier: 1.5, + phrases: [ + "selling feet pics", + "enticing men", + "doing nothing", + "contributing nothing to society" + ] + }, + 6: { + name: "CEO of FartBux", + multiplier: 2.2, + phrases: [ + "providing value to your company", + "adding to the price of FartBux", + "getting new investors", + "stealing from retail investors" + ] + }, + 7: { + name: "Jeff Bezos Jr.", + multiplier: 3, + phrases: [ + "consuming the blood of children", + "using your dad's wealth to build your own", + "\"inventing\" something that was already in use", + "yelling at factory workers for several hours" + ] + }, + 8: { + name: "Elon Musk, Lord and King of Mars", + multiplier: 5, + phrases: [ + "inventing new particles such as Assium and Coomium", + "stealing your employees' ideas", + "harnessing the power of the sun", + "watching over your fellow rich folk on Mars" + ] + } +}; + +export const totalWorksToLevel = (works: number): number => { + // let worksMap = [0, 10, 25, 50, 100, 200, 300, 500]; + if(works >= 500) return 8; + else if(works >= 300) return 7; + else if(works >= 200) return 6; + else if(works >= 100) return 5; + else if(works >= 50) return 4; + else if(works >= 25) return 3; + else if(works >= 10) return 2; + else return 1; +}; + +export const baseAward = 50; From ce0d5d8cf6b43f661a7378a1f732b9edca671324 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sat, 22 Oct 2022 17:07:00 +0200 Subject: [PATCH 39/51] refactor: sorry couldnt resist it --- src/commands/economy/Job.ts | 4 +- src/commands/economy/Work.ts | 6 +-- src/commands/economy/jobs/index.ts | 1 + src/commands/economy/{ => jobs}/jobs.ts | 52 ++++++++++++++++--------- src/modals/exec.ts | 2 +- 5 files changed, 40 insertions(+), 25 deletions(-) create mode 100644 src/commands/economy/jobs/index.ts rename src/commands/economy/{ => jobs}/jobs.ts (73%) diff --git a/src/commands/economy/Job.ts b/src/commands/economy/Job.ts index 1e8f32c..117f598 100644 --- a/src/commands/economy/Job.ts +++ b/src/commands/economy/Job.ts @@ -3,7 +3,7 @@ import { Command } from "@src/Command"; import { getTotalWorks } from "@database/economy"; import { settings } from "@src/settings"; import { embedify } from "@utils/embedify"; -import { Levels, totalWorksToLevel, baseAward } from "@src/commands/economy/jobs"; +import { jobLevels, totalWorksToLevel, baseAward } from "@src/commands/economy/jobs"; export class Job extends Command { constructor() { @@ -26,7 +26,7 @@ export class Job extends Command { if(!totalworks || totalworks == 0) return this.reply(int, embedify("We have no job records for you, ya bum! Consider doing something using `/work`"), true); const jobidx = totalWorksToLevel(totalworks); - const job = Levels[jobidx as keyof typeof Levels]; + const job = jobLevels[jobidx as keyof typeof jobLevels]; const { name, multiplier } = job; diff --git a/src/commands/economy/Work.ts b/src/commands/economy/Work.ts index 4157714..df85ec3 100644 --- a/src/commands/economy/Work.ts +++ b/src/commands/economy/Work.ts @@ -3,7 +3,7 @@ import { Command } from "@src/Command"; import { embedify, formatSeconds, nowInSeconds } from "@utils/index"; import { addCoins, getLastWork, getTotalWorks, incrementTotalWorks, setLastWork } from "@database/economy"; import { createNewMember, getMember } from "@database/users"; -import { Levels, totalWorksToLevel, baseAward } from "@src/commands/economy/jobs"; +import { jobLevels, totalWorksToLevel, baseAward } from "@src/commands/economy/jobs"; import { randomItem } from "svcorelib"; const secs4hours = 14400; @@ -41,7 +41,7 @@ export class Work extends Command { await setLastWork(userid, guildid); const jobidx = totalWorksToLevel(totalworks); - const job = Levels[jobidx as keyof typeof Levels]; + const job = jobLevels[jobidx as keyof typeof jobLevels]; const payout = Math.round(job.multiplier * baseAward); @@ -60,7 +60,7 @@ export class Work extends Command { await setLastWork(userid, guildid); const jobidx = totalWorksToLevel(totalworks); - const job = Levels[jobidx as keyof typeof Levels]; + const job = jobLevels[jobidx as keyof typeof jobLevels]; const payout = Math.round(job.multiplier * baseAward); diff --git a/src/commands/economy/jobs/index.ts b/src/commands/economy/jobs/index.ts new file mode 100644 index 0000000..7af5bbb --- /dev/null +++ b/src/commands/economy/jobs/index.ts @@ -0,0 +1 @@ +export * from "./jobs"; diff --git a/src/commands/economy/jobs.ts b/src/commands/economy/jobs/jobs.ts similarity index 73% rename from src/commands/economy/jobs.ts rename to src/commands/economy/jobs/jobs.ts index 0c0132e..0ddeb93 100644 --- a/src/commands/economy/jobs.ts +++ b/src/commands/economy/jobs/jobs.ts @@ -1,15 +1,18 @@ -export interface ILevel { - [key: number]: { - name: string, - multiplier: number, - phrases: string[] - } +interface JobLevelObj { + name: string; + multiplier: number; + worksRequired: number; + phrases: string[]; } -export const Levels: ILevel = { + +const baseAward = 50; + +const jobLevels: Record = { 1: { name: "Beggar", multiplier: .1, + worksRequired: 0, phrases: [ "begging for a few hours on the street corner", "selling your kidney", @@ -22,6 +25,7 @@ export const Levels: ILevel = { 2: { name: "McDonald's Employee", multiplier: .4, + worksRequired: 10, phrases: [ "flipping patties", "getting beaten by your manager", @@ -31,6 +35,7 @@ export const Levels: ILevel = { 3: { name: "ShitCoin Trader", multiplier: .8, + worksRequired: 25, phrases: [ "selling some doge", "foreseeing the future", @@ -40,6 +45,7 @@ export const Levels: ILevel = { 4: { name: "Twitch Streamer", multiplier: 1, + worksRequired: 50, phrases: [ "destroying some 12 year olds", "playing some fortnite", @@ -50,6 +56,7 @@ export const Levels: ILevel = { 5: { name: "E-Thot", multiplier: 1.5, + worksRequired: 100, phrases: [ "selling feet pics", "enticing men", @@ -60,6 +67,7 @@ export const Levels: ILevel = { 6: { name: "CEO of FartBux", multiplier: 2.2, + worksRequired: 200, phrases: [ "providing value to your company", "adding to the price of FartBux", @@ -70,6 +78,7 @@ export const Levels: ILevel = { 7: { name: "Jeff Bezos Jr.", multiplier: 3, + worksRequired: 300, phrases: [ "consuming the blood of children", "using your dad's wealth to build your own", @@ -80,6 +89,7 @@ export const Levels: ILevel = { 8: { name: "Elon Musk, Lord and King of Mars", multiplier: 5, + worksRequired: 500, phrases: [ "inventing new particles such as Assium and Coomium", "stealing your employees' ideas", @@ -89,16 +99,20 @@ export const Levels: ILevel = { } }; -export const totalWorksToLevel = (works: number): number => { - // let worksMap = [0, 10, 25, 50, 100, 200, 300, 500]; - if(works >= 500) return 8; - else if(works >= 300) return 7; - else if(works >= 200) return 6; - else if(works >= 100) return 5; - else if(works >= 50) return 4; - else if(works >= 25) return 3; - else if(works >= 10) return 2; - else return 1; -}; +function totalWorksToLevel(works: number) { + const entries = Object.entries(jobLevels) + .reverse() + .map(([l, o]) => ([Number(l), o])) as [number, JobLevelObj][]; -export const baseAward = 50; + for(const [lvl, { worksRequired }] of entries) { + if(works >= worksRequired) + return lvl; + } + return 1; +} + +export { + baseAward, + jobLevels, + totalWorksToLevel, +}; diff --git a/src/modals/exec.ts b/src/modals/exec.ts index 7d3abb2..f077a4a 100644 --- a/src/modals/exec.ts +++ b/src/modals/exec.ts @@ -18,7 +18,7 @@ export class ExecModal extends Modal new TextInputBuilder() .setCustomId("code") .setLabel("Code") - .setPlaceholder("Any TS or CJS code\n(Vars: channel, user, guild, client, and important stuff from D.JS and utils)") + .setPlaceholder("Any TS or CJS code\nImport with \"await import()\", relative to src/modals\nReturn to display result") .setStyle(TextInputStyle.Paragraph) .setRequired(true), ] From 382aa65d9785228aec5e4b9b426d047468ddf4d7 Mon Sep 17 00:00:00 2001 From: Sven Date: Thu, 3 Nov 2022 10:40:03 +0100 Subject: [PATCH 40/51] fix: refactor code & fix poll time parsing --- src/modals/poll.ts | 113 +++++++++++++++++++++++++++------------------ 1 file changed, 69 insertions(+), 44 deletions(-) diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 887dd98..8232ab7 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -5,6 +5,7 @@ import { settings } from "@src/settings"; import { embedify, zeroPad } from "@src/utils"; import { createNewGuild, createNewPoll, getGuild, getPolls } from "@src/database/guild"; import { halves } from "svcorelib"; +import { Tuple } from "@src/types"; interface PollModalData { topic: string | null; @@ -93,8 +94,9 @@ export class CreatePollModal extends Modal async submit(int: ModalSubmitInteraction<"cached">): Promise { const { guild, channel } = int; + // already handled in the poll command if(!guild || !channel) - return; // already handled in the poll command + return; const topicRaw = int.fields.getTextInputValue("topic").trim(); @@ -103,48 +105,18 @@ export class CreatePollModal extends Modal const voteOptions = int.fields.getTextInputValue("vote_options").trim().split(/\n/gm).filter(v => v.length > 0); const headline = this.headline; - const longFmtRe = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}[\s.,_T]\d{1,2}:\d{1,2}(:\d{1,2})?$/, - shortFmtRe = /^\d{1,2}:\d{1,2}$/; - - const modalInvalid = (msg: string) => { - this.emit("invalid", { topic: topic ?? null, expiry, voteOptions }); - return this.reply(int, embedify(msg, settings.embedColors.error), true); - }; - - if(!expiry.match(longFmtRe) && !expiry.match(shortFmtRe)) - return modalInvalid("Please make sure the poll end date and time are formatted in one of these formats (24 hours, in UTC / GMT+0 time):\n- `YYYY/MM/DD hh:mm`\n- `hh:mm` (today)"); - if(voteOptions.length > settings.emojiList.length) - return modalInvalid(`Please enter ${settings.emojiList.length} vote options at most.`); - if(voteOptions.length < 2) - return modalInvalid("Please enter at least two options to vote on."); - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [_, ...rest] = (expiry.match(longFmtRe) - ? /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})[\s.,_T](\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) - : /^(\d{1,2}):(\d{1,2})$/.exec(expiry) - )?.filter(v => v) as string[]; - - // TODO:FIXME: this shit is utterly broken - const d = new Date(); - let dateParts: number[] = []; - - if(rest.length === 5) - dateParts = rest.map(v => parseInt(v)); - else - dateParts = [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), ...rest.map(v => parseInt(v))]; - - // parseInt(v) - new Date().getTimezoneOffset() / 60 - - const dueTimestamp = new Date(...<[number]>dateParts); - const optionFields = CreatePollModal.reduceOptionFields(voteOptions); + const parsed = this.parsePollVals({ + int, + topic: topic ?? null, + expiry, + voteOptions, + }); - const dueTs = dueTimestamp.getTime(); - const nowTs = new Date().getTime() + 30_000; + // is already handled in parsePollVals() + if(!parsed) + return; - const due = new Date(dueTs), now = new Date(nowTs); - - if(dueTs < nowTs) - return modalInvalid("Please enter a date and time that is at least one minute from now."); + const { dueTime, optionFields } = parsed; const ebd = new EmbedBuilder() .setTitle(this.title ?? "Poll") @@ -158,8 +130,6 @@ export class CreatePollModal extends Modal await this.deferReply(int, true); - console.log(); - // send messages & react try { @@ -216,7 +186,7 @@ export class CreatePollModal extends Modal topic: topic && topic.length > 0 ? topic : null, voteOptions, votesPerUser: this.votesPerUser, - dueTimestamp, + dueTimestamp: dueTime, }); return this.editReply(int, embedify("Successfully created a poll in this channel.")); @@ -226,4 +196,59 @@ export class CreatePollModal extends Modal return this.editReply(int, embedify(`Couldn't create a poll due to an error: ${err}`, settings.embedColors.error)); } } + + parsePollVals({ int, topic, expiry, voteOptions }: { int: ModalSubmitInteraction } & PollModalData) + { + const longFmtRe = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}[\s.,_T]\d{1,2}:\d{1,2}(:\d{1,2})?$/, + shortFmtRe = /^\d{1,2}:\d{1,2}$/; + + const modalInvalid = (msg: string) => { + this.emit("invalid", { topic: topic ?? null, expiry, voteOptions }); + this.reply(int, embedify(msg, settings.embedColors.error), true); + return null; + }; + + if(!expiry.match(longFmtRe) && !expiry.match(shortFmtRe)) + return modalInvalid("Please make sure the poll end date and time are formatted in one of these formats (24 hours, in UTC / GMT+0 time):\n- `YYYY/MM/DD hh:mm`\n- `hh:mm` (today)"); + if(voteOptions.length > settings.emojiList.length) + return modalInvalid(`Please enter ${settings.emojiList.length} vote options at most.`); + if(voteOptions.length < 2) + return modalInvalid("Please enter at least two options to vote on."); + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, ...rest] = (expiry.match(longFmtRe) + ? /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})[\s.,_T](\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) + : /^(\d{1,2}):(\d{1,2})$/.exec(expiry) + )?.filter(v => v) as string[]; + + const d = new Date(); + let dateParts: number[] = []; + + if(rest.length === 5) + dateParts = rest.map(v => parseInt(v)); + else + dateParts = [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), ...rest.map(v => parseInt(v))]; + + // for some reason only months in JS are 0-indexed + dateParts[1]--; + + // parseInt(v) - new Date().getTimezoneOffset() / 60 + + const dueTs = Date.UTC(...>dateParts); + const nowTs = Date.now(); + + const optionFields = CreatePollModal.reduceOptionFields(voteOptions); + + const due = new Date(dueTs), now = new Date(nowTs); + console.log("due", due); + console.log("now", now); + + if(dueTs < nowTs + 30_000) + return modalInvalid("Please enter a date and time that is at least one minute from now."); + + return { + dueTime: new Date(dueTs), + optionFields, + }; + } } From e02bbb1e84c2ee837f64b74594cd9bee311363ff Mon Sep 17 00:00:00 2001 From: Sven Date: Thu, 3 Nov 2022 11:23:53 +0100 Subject: [PATCH 41/51] fix: ci: remove node-canvas deps condition --- .github/workflows/node.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/node.yml b/.github/workflows/node.yml index a692f7b..65839d8 100644 --- a/.github/workflows/node.yml +++ b/.github/workflows/node.yml @@ -23,7 +23,6 @@ jobs: run: | sudo apt update sudo apt install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev - if: matrix.node-version == '18.x' - name: Install npm dependencies run: | From b8dc63e920ce775f477b7632e2728d9763c5a64b Mon Sep 17 00:00:00 2001 From: Sven Date: Thu, 3 Nov 2022 11:31:09 +0100 Subject: [PATCH 42/51] just to be safe --- .github/workflows/node.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/node.yml b/.github/workflows/node.yml index 65839d8..e21e0cd 100644 --- a/.github/workflows/node.yml +++ b/.github/workflows/node.yml @@ -22,13 +22,14 @@ jobs: - name: Install node-canvas dependencies run: | sudo apt update - sudo apt install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev + sudo apt install -y build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev - name: Install npm dependencies run: | - npm install -g tsc - npm install + npm i -g tsc + npm ci - - run: npm run lint + - name: Run ESLint + run: npm run lint From ed74eb2240c512a0f3d4c24ad49b2d6a939b11ac Mon Sep 17 00:00:00 2001 From: Sv443 Date: Tue, 8 Nov 2022 16:27:48 +0100 Subject: [PATCH 43/51] refactor: unify emojis --- src/commands/mod/Log.ts | 6 +++--- src/commands/music/NowPlaying.ts | 4 ++-- src/commands/music/Queue.ts | 2 +- src/commands/util/Define.ts | 4 ++-- src/commands/util/Poll.ts | 4 ++-- src/lavalink/lib/trackStart.ts | 3 ++- src/utils/emojis.ts | 3 +++ src/utils/index.ts | 1 + 8 files changed, 16 insertions(+), 11 deletions(-) create mode 100644 src/utils/emojis.ts diff --git a/src/commands/mod/Log.ts b/src/commands/mod/Log.ts index 838107d..74b5077 100644 --- a/src/commands/mod/Log.ts +++ b/src/commands/mod/Log.ts @@ -4,7 +4,7 @@ import { Command } from "@src/Command"; import { settings } from "@src/settings"; import { PermissionFlagsBits } from "discord-api-types/v10"; import { createGuildSettings, createNewGuild, getGuild, getGuildSettings, setGuild } from "@src/database/guild"; -import { embedify, toUnix10 } from "@src/utils"; +import { embedify, toUnix10, emojis } from "@src/utils"; export class Log extends Command { constructor() { @@ -135,14 +135,14 @@ export class Log extends Command { <@${message.author.id}> - ${message.embeds.length > 0 ? "(embed)" : (messageAttachmentString.length > 0 ? messageAttachmentString : "(other)")} - > [show message <:open_in_browser:994648843331309589>](${message.url})`); + > [show message ${emojis.openInBrowser}](${message.url})`); } else { messageEmbedString += (`\ <@${message.author.id}> - > ${message.embeds.length > 0 ? "(embed)" : (message.content && message.content.length > 0 ? message.content : "(other)")} - > [show message <:open_in_browser:994648843331309589>](${message.url})`); + > [show message ${emojis.openInBrowser}](${message.url})`); } if(i === 10 || (10 * setNum) + i === messages.size) { diff --git a/src/commands/music/NowPlaying.ts b/src/commands/music/NowPlaying.ts index 5ea43d8..09c9608 100644 --- a/src/commands/music/NowPlaying.ts +++ b/src/commands/music/NowPlaying.ts @@ -1,7 +1,7 @@ import { CommandInteraction, GuildMemberRoleManager, ButtonBuilder, User, ButtonStyle } from "discord.js"; import { Command } from "@src/Command"; import { getMusicManager } from "@src/lavalink/client"; -import { embedify, musicReadableTimeString, BtnMsg } from "@src/utils"; +import { embedify, musicReadableTimeString, BtnMsg, emojis } from "@src/utils"; import { formatDuration, parseDuration } from "svcorelib"; import { getPremium, isDJOnlyandhasDJRole } from "@src/database/music"; import { fetchSongInfo, resolveTitle } from "./global.music"; @@ -44,7 +44,7 @@ export class NowPlaying extends Command { if(await getPremium(int.guild.id)) { if(info?.url) - lyricsLink = `Lyrics: [click to open <:open_in_browser:994648843331309589>](${info.url})\n`; + lyricsLink = `Lyrics: [click to open ${emojis.openInBrowser}](${info.url})\n`; } const embed = embedify(`Artist: \`${info?.meta.artists ?? current.author}\`\n${lyricsLink}\n\`${current.isStream ? formatDuration(player.position, "%h:%m:%s", true) : readableTime}\`\nRequested by: <@${(current.requester as User).id}>`) diff --git a/src/commands/music/Queue.ts b/src/commands/music/Queue.ts index ee67305..dd5f31b 100644 --- a/src/commands/music/Queue.ts +++ b/src/commands/music/Queue.ts @@ -56,7 +56,7 @@ export class Queue extends Command { // return ""; // const lyricsUrl = await fetchLyricsUrl(title); // if(lyricsUrl) - // return ` - [lyrics <:open_in_browser:994648843331309589>](${lyricsUrl})\n`; + // return ` - [lyrics ${emojis.openInBrowser}](${lyricsUrl})\n`; // return ""; // }; diff --git a/src/commands/util/Define.ts b/src/commands/util/Define.ts index 20ff24f..9da38d6 100644 --- a/src/commands/util/Define.ts +++ b/src/commands/util/Define.ts @@ -2,7 +2,7 @@ import { CommandInteraction, ButtonBuilder, EmbedBuilder, ButtonStyle, Applicati import { embedify, useEmbedify } from "@utils/embedify"; import { Command } from "@src/Command"; import { settings } from "@src/settings"; -import { followRedirects, rankVotes, axios } from "@src/utils"; +import { followRedirects, rankVotes, axios, emojis } from "@src/utils"; import { Tuple } from "@src/types"; type WikiArticle = { @@ -278,7 +278,7 @@ export class Define extends Command /** Returns an embed description for an emoji-choice-dialog */ emojiChoiceDesc(choices: { name: string, url?: string }[]): string { - return choices.map((a, i) => `${settings.emojiList[i]} **${a.name}**${a.url ? ` - [open <:open_in_browser:994648843331309589>](${a.url})` : ""}`).join("\n"); + return choices.map((a, i) => `${settings.emojiList[i]} **${a.name}**${a.url ? ` - [open ${emojis.openInBrowser}](${a.url})` : ""}`).join("\n"); } async findWikiArticle(int: CommandInteraction, articles: WikiArticle[]) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index 8c287ff..e9b1016 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -2,7 +2,7 @@ import { ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, Client, Colle import k from "kleur"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; -import { autoPlural, BtnMsg, embedify, PageEmbed, toUnix10, truncStr, useEmbedify } from "@src/utils"; +import { autoPlural, BtnMsg, embedify, emojis, PageEmbed, toUnix10, truncStr, useEmbedify } from "@src/utils"; import { settings } from "@src/settings"; import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; import { Poll as PollObj } from "@prisma/client"; @@ -147,7 +147,7 @@ export class Poll extends Command name: "\u200B", value: pollSlice.reduce((a, c) => ([ `${a}\n`, - `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show <:open_in_browser:994648843331309589>](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, + `> **\`${c.pollId}\`** - by <@${c.createdBy}>${c.topic ? "" : ` in <#${c.channel}>`} - [show ${emojis.openInBrowser}](https://discord.com/channels/${c.guildId}/${c.channel}/${c.messages[0]})`, ...(c.topic ? [`> **Topic:** ${truncStr(c.topic.replace(/[`]{3}\w*/gm, "").replace(/\n+/gm, " "), 80)}`] : ["> (no topic)"]), `> Ends `, ].join("\n")), ""), diff --git a/src/lavalink/lib/trackStart.ts b/src/lavalink/lib/trackStart.ts index 6527759..99ebf03 100644 --- a/src/lavalink/lib/trackStart.ts +++ b/src/lavalink/lib/trackStart.ts @@ -3,6 +3,7 @@ import { Player, Track } from "erela.js"; import { embedify } from "@utils/embedify"; import { fetchSongInfo, formatTitle, resolveTitle } from "@src/commands/music/global.music"; import { getPremium } from "@src/database/music"; +import { emojis } from "@src/utils"; export async function trackStart(player: Player, track: Track, client: Client) { if(!player.textChannel || !player.voiceChannel) return; @@ -18,7 +19,7 @@ export async function trackStart(player: Player, track: Track, client: Client) { { const lyrics = await fetchSongInfo(resolveTitle(track.title)); if(lyrics?.url) - lyricsLink = `Lyrics: [click to open <:open_in_browser:994648843331309589>](${lyrics.url})\n`; + lyricsLink = `Lyrics: [click to open ${emojis.openInBrowser}](${lyrics.url})\n`; } (channel as TextChannel).send({ diff --git a/src/utils/emojis.ts b/src/utils/emojis.ts new file mode 100644 index 0000000..0f9d5eb --- /dev/null +++ b/src/utils/emojis.ts @@ -0,0 +1,3 @@ +export const emojis = { + openInBrowser: "<:open_in_browser:994648843331309589>", +}; diff --git a/src/utils/index.ts b/src/utils/index.ts index 749e252..68d8af6 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,6 +1,7 @@ export * from "./@TryCatchMethod"; export * from "./BtnMsg"; export * from "./embedify"; +export * from "./emojis"; export * from "./misc"; export * from "./Modal"; export * from "./PageEmbed"; From a766ef35b23c36a16771f16514e51c334d72bf4c Mon Sep 17 00:00:00 2001 From: Sv443 Date: Tue, 8 Nov 2022 16:36:15 +0100 Subject: [PATCH 44/51] feat: fix poll time parsing --- src/commands/fun/Cat.ts | 4 ++-- src/commands/fun/Mock.ts | 3 ++- src/commands/mod/Warning.ts | 4 ++-- src/modals/poll.ts | 12 +++--------- src/types/index.d.ts | 2 +- src/utils/emojis.ts | 7 +++++++ 6 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/commands/fun/Cat.ts b/src/commands/fun/Cat.ts index e165f0f..b664285 100644 --- a/src/commands/fun/Cat.ts +++ b/src/commands/fun/Cat.ts @@ -1,7 +1,7 @@ import { CommandInteraction, EmbedBuilder } from "discord.js"; import { randomItem } from "svcorelib"; import { AxiosError } from "axios"; -import { axios } from "@src/utils"; +import { axios, emojis } from "@src/utils"; import { Command } from "@src/Command"; import { settings } from "@src/settings"; @@ -18,7 +18,7 @@ const embedTitles = [ "Good cat", "Aww, look at it", "What a cutie", - "<:qt_cett:610817939276562433>", + emojis.qtCett, ]; export class Cat extends Command diff --git a/src/commands/fun/Mock.ts b/src/commands/fun/Mock.ts index 55e5347..acab096 100644 --- a/src/commands/fun/Mock.ts +++ b/src/commands/fun/Mock.ts @@ -1,5 +1,6 @@ import { ApplicationCommandOptionType, CommandInteraction } from "discord.js"; import { Command } from "@src/Command"; +import { emojis } from "@src/utils"; export class Mock extends Command { @@ -41,7 +42,7 @@ export class Mock extends Command if(ephemeral) return await this.reply(int, mockified, ephemeral); - await channel.send(`<:mock:506303207400669204> ${mockified}`); + await channel.send(`${emojis.mock} ${mockified}`); await this.reply(int, "Sent the message.", true); } diff --git a/src/commands/mod/Warning.ts b/src/commands/mod/Warning.ts index 0f057f0..e18a36b 100644 --- a/src/commands/mod/Warning.ts +++ b/src/commands/mod/Warning.ts @@ -2,7 +2,7 @@ import { CommandInteraction, GuildMember, EmbedBuilder, ApplicationCommandOption import { Command } from "@src/Command"; import { settings } from "@src/settings"; import { PermissionFlagsBits } from "discord-api-types/v10"; -import { BtnMsg, embedify, PageEmbed, toUnix10, useEmbedify } from "@src/utils"; +import { BtnMsg, embedify, emojis, PageEmbed, toUnix10, useEmbedify } from "@src/utils"; import { addWarning, createNewMember, deleteWarnings, getMember, getWarnings } from "@src/database/users"; import { Warning as WarningObj } from "@prisma/client"; import { allOfType } from "svcorelib"; @@ -240,7 +240,7 @@ export class Warning extends Command bm.on("destroy", () => alertMsg.edit(bm.getMsgOpts())); - alertMsg.react("<:banhammer:1015632683096871055>"); + alertMsg.react(emojis.banHammer); const coll = alertMsg.createReactionCollector({ filter: (re, usr) => { diff --git a/src/modals/poll.ts b/src/modals/poll.ts index 8232ab7..fcec681 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -124,7 +124,7 @@ export class CreatePollModal extends Modal .setFooter({ text: `Click the reaction emojis below to cast ${this.votesPerUser === 1 ? "a vote" : "votes"}.` }) .setColor(settings.embedColors.default); - topic && topic.length > 0 && ebd.setDescription(`> **Topic:**${topic.length > 64 ? "\n>" : ""} ${topic}\n`); + topic && topic.length > 0 && ebd.setDescription(`> ${topic.length > 64 ? "\n>" : ""} ${topic}\n`); this.emit("deleteCachedData"); @@ -199,7 +199,7 @@ export class CreatePollModal extends Modal parsePollVals({ int, topic, expiry, voteOptions }: { int: ModalSubmitInteraction } & PollModalData) { - const longFmtRe = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}[\s.,_T]\d{1,2}:\d{1,2}(:\d{1,2})?$/, + const longFmtRe = /^\d{4}[./-]\d{1,2}[./-]\d{1,2}[\s.,_T]+\d{1,2}:\d{1,2}(:\d{1,2})?$/, shortFmtRe = /^\d{1,2}:\d{1,2}$/; const modalInvalid = (msg: string) => { @@ -217,7 +217,7 @@ export class CreatePollModal extends Modal // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, ...rest] = (expiry.match(longFmtRe) - ? /^(\d{4})[/-](\d{1,2})[/-](\d{1,2})[\s.,_T](\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) + ? /^(\d{4})[./-](\d{1,2})[./-](\d{1,2})[\s.,_T]+(\d{1,2}):(\d{1,2}):?(\d{1,2})?$/.exec(expiry) : /^(\d{1,2}):(\d{1,2})$/.exec(expiry) )?.filter(v => v) as string[]; @@ -232,17 +232,11 @@ export class CreatePollModal extends Modal // for some reason only months in JS are 0-indexed dateParts[1]--; - // parseInt(v) - new Date().getTimezoneOffset() / 60 - const dueTs = Date.UTC(...>dateParts); const nowTs = Date.now(); const optionFields = CreatePollModal.reduceOptionFields(voteOptions); - const due = new Date(dueTs), now = new Date(nowTs); - console.log("due", due); - console.log("now", now); - if(dueTs < nowTs + 30_000) return modalInvalid("Please enter a date and time that is at least one minute from now."); diff --git a/src/types/index.d.ts b/src/types/index.d.ts index fbcde51..1573d8c 100644 --- a/src/types/index.d.ts +++ b/src/types/index.d.ts @@ -154,5 +154,5 @@ export type AnyInteraction = CommandInteraction | ButtonInteraction | ModalSubmi //#MARKER utils // The tuple type allows us to create arrays with certain lengths that are type-safe (doesn't protect from push()ing over N elements) -type Tuple = N extends N ? number extends N ? T[] : _TupleOf : never; +export type Tuple = N extends N ? number extends N ? T[] : _TupleOf : never; type _TupleOf = R["length"] extends N ? R : _TupleOf; diff --git a/src/utils/emojis.ts b/src/utils/emojis.ts index 0f9d5eb..7ff8288 100644 --- a/src/utils/emojis.ts +++ b/src/utils/emojis.ts @@ -1,3 +1,10 @@ export const emojis = { + /** ![open_in_browser](https://cdn.discordapp.com/emojis/994648843331309589.png?size=64) */ openInBrowser: "<:open_in_browser:994648843331309589>", + /** ![qt_cett](https://cdn.discordapp.com/emojis/610817939276562433.png?size=64) */ + qtCett: "<:qt_cett:610817939276562433>", + /** ![mock](https://cdn.discordapp.com/emojis/506303207400669204.png?size=64) */ + mock: "<:mock:506303207400669204>", + /** ![banhammer](https://cdn.discordapp.com/emojis/1015632683096871055.png?size=64) */ + banHammer: "<:banhammer:1015632683096871055>", }; From 6d357bb5f2154b4c37b0aea65b9e8e60190232aa Mon Sep 17 00:00:00 2001 From: Sv443 Date: Wed, 16 Nov 2022 23:46:52 +0100 Subject: [PATCH 45/51] ngl poll stuff --- src/commands/util/Define.ts | 8 +------ src/commands/util/Poll.ts | 23 +++++++++++++++++--- src/database/guild.ts | 14 +++++++++++++ src/modals/poll.ts | 42 ++++++++++++++++++++++++++++++++++++- 4 files changed, 76 insertions(+), 11 deletions(-) diff --git a/src/commands/util/Define.ts b/src/commands/util/Define.ts index 9da38d6..045a6d6 100644 --- a/src/commands/util/Define.ts +++ b/src/commands/util/Define.ts @@ -126,7 +126,7 @@ export class Define extends Command author && thumbs_up && thumbs_down && embed.setFooter({ - text: `By ${trimLength(author, 32)} - 👍 ${thumbs_up} 👎 ${thumbs_down}`, + text: `👍 ${thumbs_up} 👎 ${thumbs_down}`, iconURL: icons.urbandictionary, }); @@ -360,9 +360,3 @@ export class Define extends Command } } } - -/** Trims a `str`ing if it's longer than `len` (32 by default) and adds `trimChar` (`…` by default) */ -function trimLength(str: string, len = 32, trimChar = "…") -{ - return str.length > len ? str.substring(0, len) + trimChar : str; -} diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index e9b1016..bba01f1 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -1,10 +1,10 @@ -import { ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, PermissionFlagsBits, TextChannel } from "discord.js"; +import { ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, Client, Collection, CommandInteraction, CommandInteractionOption, EmbedBuilder, Message, PermissionFlagsBits, ReactionCollector, TextChannel } from "discord.js"; import k from "kleur"; import { Command } from "@src/Command"; import { CreatePollModal } from "@src/modals/poll"; import { autoPlural, BtnMsg, embedify, emojis, PageEmbed, toUnix10, truncStr, useEmbedify } from "@src/utils"; import { settings } from "@src/settings"; -import { deletePoll, getExpiredPolls, getPolls } from "@src/database/guild"; +import { deletePoll, getActivePolls, getExpiredPolls, getPolls } from "@src/database/guild"; import { Poll as PollObj } from "@prisma/client"; import { getRedis } from "@src/redis"; import { Tuple } from "@src/types"; @@ -21,6 +21,7 @@ interface PollVote { export class Poll extends Command { private client: Client; + private reactionCollectors = new Collection<{ pollId: number, guildId: string }, ReactionCollector>; constructor(client: Client) { @@ -77,7 +78,9 @@ export class Poll extends Command }); this.client = client; - + + this.setupActivePolls(); + try { this.checkPolls(); setInterval(this.checkPolls, 2000); @@ -87,6 +90,18 @@ export class Poll extends Command } } + /** Run once at startup to set up the reaction collectors */ + async setupActivePolls() + { + const polls = await getActivePolls(); + polls.forEach(async (poll) => { + const { votesPerUser, guildId, pollId, voteOptions } = poll; + const msgs = (await this.getPollMsgs(poll))?.map(m => m); + msgs && CreatePollModal.watchReactions(msgs, voteOptions, votesPerUser) + .forEach(coll => this.reactionCollectors.set({ guildId, pollId }, coll)); + }); + } + async run(int: CommandInteraction, opt: CommandInteractionOption): Promise { let action = ""; @@ -272,6 +287,8 @@ export class Poll extends Command const { guildId, pollId, channel, voteOptions, dueTimestamp: endTime } = poll; const redisKey = `check_poll_${guildId}-${pollId}`; + this.reactionCollectors.delete({ pollId, guildId }); + if(!(await redis.get(redisKey))) continue; diff --git a/src/database/guild.ts b/src/database/guild.ts index ab9f2ba..d38c900 100644 --- a/src/database/guild.ts +++ b/src/database/guild.ts @@ -120,6 +120,20 @@ export function getPoll(guildId: string, pollId: number) }); } +export function getActivePolls() +{ + return prisma.poll.findMany({ + where: { + dueTimestamp: { + gt: new Date(), + }, + }, + orderBy: { + dueTimestamp: "asc", + }, + }); +} + export function getExpiredPolls() { return prisma.poll.findMany({ diff --git a/src/modals/poll.ts b/src/modals/poll.ts index fcec681..ea34290 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -1,4 +1,4 @@ -import { EmbedBuilder, EmbedField, Message, MessageOptions, ModalSubmitInteraction, TextInputBuilder, TextInputStyle } from "discord.js"; +import { EmbedBuilder, EmbedField, Message, MessageOptions, ModalSubmitInteraction, ReactionCollector, TextInputBuilder, TextInputStyle } from "discord.js"; import { Modal } from "@utils/Modal"; import { settings } from "@src/settings"; @@ -30,6 +30,8 @@ export class CreatePollModal extends Modal private votesPerUser; private title; + public reactionCollectors: ReactionCollector[] = []; + constructor(headline?: string, votesPerUser = 1, title?: string, modalData?: PollModalData) { const p = zeroPad, d = new Date(); @@ -72,6 +74,13 @@ export class CreatePollModal extends Modal this.title = title; } + destroy() + { + this.reactionCollectors.forEach(c => c.stop()); + this.reactionCollectors = []; + this._destroy(); + } + public static reduceOptionFields(opts: string[]): EmbedField[] { const optHalves = opts.length > settings.emojiList.length / 3 ? halves(opts) : [opts]; @@ -91,6 +100,35 @@ export class CreatePollModal extends Modal })); } + // TODO: this might get costly if the bot grows + /** + * Watches for extraneous reactions on the passed poll messages + * @param msgs Messages to watch + * @param voteOptions The options users can vote on + * @static This function is static so it can be reused in @commands/Poll.ts + */ + public static watchReactions(msgs: Message[], voteOptions: string[], votesPerUser: number) + { + const colls: ReactionCollector[] = []; + const pollEmojis = settings.emojiList.slice(0, voteOptions.length); + + msgs.forEach(msg => { + colls.push(msg.createReactionCollector({ + // TODO: check + filter: (re, user) => { + if(msgs.reduce( + (a, c) => a + c.reactions.cache.filter(r => r.users.cache.has(user.id)).size, 0 + ) <= votesPerUser) + re.remove(); + if(!pollEmojis.includes(re.emoji.name ?? "_")) + re.remove(); + return true; // collector doesn't actually do anything besides remove extraneous reactions + }, + })); + }); + return colls; + } + async submit(int: ModalSubmitInteraction<"cached">): Promise { const { guild, channel } = int; @@ -160,6 +198,8 @@ export class CreatePollModal extends Modal }); } + this.reactionCollectors = CreatePollModal.watchReactions(msgs, voteOptions, this.votesPerUser); + const dbGld = await getGuild(guild.id); if(!dbGld) From d6eea70c88afd676011cbf0770475710eec0f8e9 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Wed, 16 Nov 2022 23:56:37 +0100 Subject: [PATCH 46/51] stuff n shid --- src/commands/util/Poll.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index bba01f1..ef200ac 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -21,7 +21,7 @@ interface PollVote { export class Poll extends Command { private client: Client; - private reactionCollectors = new Collection<{ pollId: number, guildId: string }, ReactionCollector>; + private reactionCollectors: { pollId: number, guildId: string, collectors: ReactionCollector[] }[] = []; constructor(client: Client) { @@ -83,7 +83,7 @@ export class Poll extends Command try { this.checkPolls(); - setInterval(this.checkPolls, 2000); + setInterval(() => this.checkPolls(), 2000); } catch(err) { console.error(k.red("Error while checking polls:"), err); @@ -97,8 +97,11 @@ export class Poll extends Command polls.forEach(async (poll) => { const { votesPerUser, guildId, pollId, voteOptions } = poll; const msgs = (await this.getPollMsgs(poll))?.map(m => m); - msgs && CreatePollModal.watchReactions(msgs, voteOptions, votesPerUser) - .forEach(coll => this.reactionCollectors.set({ guildId, pollId }, coll)); + if(msgs) + { + const collectors = CreatePollModal.watchReactions(msgs, voteOptions, votesPerUser); + this.reactionCollectors.push({ guildId, pollId, collectors }); + } }); } @@ -287,7 +290,13 @@ export class Poll extends Command const { guildId, pollId, channel, voteOptions, dueTimestamp: endTime } = poll; const redisKey = `check_poll_${guildId}-${pollId}`; - this.reactionCollectors.delete({ pollId, guildId }); + // idk how to do this better + let remIdx: undefined | number = undefined; + this.reactionCollectors.forEach((c, i) => { + if(c.guildId === guildId && c.pollId === pollId) + remIdx = i; + }); + typeof remIdx === "number" && this.reactionCollectors.splice(remIdx, 1); if(!(await redis.get(redisKey))) continue; From 82ad79e2a81561f0affd3cad6543d83a0de835e0 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sun, 20 Nov 2022 17:46:51 +0100 Subject: [PATCH 47/51] feat: command prefix env var --- .env.template | 1 + src/Command.ts | 13 +++++++++---- src/commands/util/Reminder.ts | 6 ++++++ src/settings.ts | 15 ++++++++++++--- 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/.env.template b/.env.template index 2e236a4..413f244 100644 --- a/.env.template +++ b/.env.template @@ -10,6 +10,7 @@ SPOTIFY_CLIENT_ID=123123123 # https://developer.spotify.com/dashboard/ SPOTIFY_CLIENT_SECRET=123123123 # Settings +COMMAND_PREFIX="" # Set to something like an abbreviation of the client's name so all commands have that prefix and can be distinguished better - empty for none DEV_IDS="123,456" # All user IDs that should have dev perms BELL_ON_READY=false # Set to true to send a console bell sound when the client is ready EXEC_CMD_ENABLED=true # Set to false to disable the /exec command diff --git a/src/Command.ts b/src/Command.ts index 6de2e7a..7271b39 100644 --- a/src/Command.ts +++ b/src/Command.ts @@ -46,7 +46,7 @@ export abstract class Command this.meta = { ...fallbackMeta, ...cmdMeta }; const { name, desc, args } = this.meta; - data.setName(name) + data.setName(this.getCmdName(name)) .setDescription(desc); Array.isArray(args) && args.forEach(arg => { @@ -121,7 +121,7 @@ export abstract class Command return opt; }); else - throw new Error("Unimplemented option type"); + throw new Error(`Unimplemented argument type in /${cmdMeta.name}`); }); } else @@ -129,7 +129,7 @@ export abstract class Command // subcommands this.meta = { ...fallbackMeta, ...cmdMeta }; - data.setName(cmdMeta.name) + data.setName(this.getCmdName(cmdMeta.name)) .setDescription(cmdMeta.desc); cmdMeta.subcommands.forEach(scmd => { @@ -212,7 +212,7 @@ export abstract class Command return opt; }); else - throw new Error("Unimplemented option"); + throw new Error(`Unimplemented argument type in /${cmdMeta.name} ${scmd.name}`); }); return sc; @@ -224,6 +224,11 @@ export abstract class Command this.slashCmdJson = data.toJSON(); } + private getCmdName(name: string) + { + return settings.client.commandPrefix ? `${settings.client.commandPrefix}_${name}` : name; + } + //#SECTION public /** Called when a user tries to run this command (if the user doesn't have perms this resolves null) */ diff --git a/src/commands/util/Reminder.ts b/src/commands/util/Reminder.ts index d1b4c46..8d77458 100644 --- a/src/commands/util/Reminder.ts +++ b/src/commands/util/Reminder.ts @@ -356,6 +356,8 @@ export class Reminder extends Command .setColor(settings.embedColors.default) .setDescription(`The following reminder has expired:\n>>> ${name}`); + const reminderError = (err: Error) => console.error(k.red("Error while checking reminders:\n"), err); + const guildFallback = async (rem: ReminderObj) => { try { if(rem.private) @@ -377,6 +379,8 @@ export class Reminder extends Command // ─────┼───── // I I │ I ⌐¬ + err instanceof Error && reminderError(err); + void err; } finally { @@ -385,6 +389,8 @@ export class Reminder extends Command } catch(err) { // TODO: see above + + err instanceof Error && reminderError(err); } finally { this.reminderCheckBuffer.delete(`${rem.userId}-${rem.reminderId}`); diff --git a/src/settings.ts b/src/settings.ts index 1f08354..5685c2c 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -41,6 +41,8 @@ export const settings: Settings = Object.freeze({ Intents.GuildMessageReactions, Intents.DirectMessages, ], + /** Optional prefix to better distinguish commands of specific clients */ + commandPrefix: getEnvVar("COMMAND_PREFIX", "stringNoEmpty"), }, embedColors: { default: getEnvVar("EMBED_COLOR_DEFAULT") ?? 0xfaba05, @@ -58,12 +60,16 @@ export const settings: Settings = Object.freeze({ }, }) as Settings; -/** Tests if the environment variable `varName` equals `value` casted to string - both params are case insensitive */ -function envVarEquals(varName: string, value: Stringifiable) +/** Tests if the environment variable `varName` equals `value` casted to string */ +function envVarEquals(varName: string, value: Stringifiable, caseSensitive = false) { - return process.env[varName]?.toLowerCase() === value.toString().toLowerCase(); + const envVal = process.env[varName]; + const val = String(value); + return (caseSensitive ? envVal : envVal?.toLowerCase()) === (caseSensitive ? String(val) : String(val).toLowerCase()); } +/** Grabs an environment variable's value, and casts it to a `string` - however if the string is empty (unset), undefined is returned */ +export function getEnvVar(varName: string, asType?: "stringNoEmpty"): undefined | string /** Grabs an environment variable's value, and casts it to a `string` */ export function getEnvVar(varName: string, asType?: "string"): undefined | string /** Grabs an environment variable's value, and casts it to a `number` */ @@ -95,6 +101,8 @@ export function getEnvVar v.split(commasRegex).map(n => parseInt(n.trim())); break; + case "stringNoEmpty": + transform = v => String(v).trim().length == 0 ? undefined : String(v).trim(); } return transform(val) as string; // I'm lazy and ts is happy, so we can all be happy and pretend this doesn't exist @@ -111,6 +119,7 @@ interface Settings { } client: { intents: GatewayIntentBits[]; + commandPrefix?: string; } embedColors: { default: ColorResolvable; From 19095f2929219841417b90a0a444ac762a42dd0d Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sun, 20 Nov 2022 18:01:07 +0100 Subject: [PATCH 48/51] fix: remove underscore in cmd prefix --- src/Command.ts | 13 +++++++------ src/bot.ts | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Command.ts b/src/Command.ts index 7271b39..1b8af5d 100644 --- a/src/Command.ts +++ b/src/Command.ts @@ -46,7 +46,7 @@ export abstract class Command this.meta = { ...fallbackMeta, ...cmdMeta }; const { name, desc, args } = this.meta; - data.setName(this.getCmdName(name)) + data.setName(this.getFullCmdName(name)) .setDescription(desc); Array.isArray(args) && args.forEach(arg => { @@ -129,7 +129,7 @@ export abstract class Command // subcommands this.meta = { ...fallbackMeta, ...cmdMeta }; - data.setName(this.getCmdName(cmdMeta.name)) + data.setName(this.getFullCmdName(cmdMeta.name)) .setDescription(cmdMeta.desc); cmdMeta.subcommands.forEach(scmd => { @@ -224,13 +224,14 @@ export abstract class Command this.slashCmdJson = data.toJSON(); } - private getCmdName(name: string) + //#SECTION public + + /** Returns the full name of the given command name, including optional prefix */ + public getFullCmdName(cmdName: string) { - return settings.client.commandPrefix ? `${settings.client.commandPrefix}_${name}` : name; + return `${settings.client.commandPrefix ?? ""}${cmdName}`; } - //#SECTION public - /** Called when a user tries to run this command (if the user doesn't have perms this resolves null) */ public async tryRun(int: CommandInteraction, opt?: CommandInteractionOption<"cached">): Promise { diff --git a/src/bot.ts b/src/bot.ts index fc8c5f1..93f6e5b 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -153,7 +153,7 @@ async function registerCommands(client: Client) const opts = options.data && options.data.length > 0 ? options.data : undefined; - const cmd = cmds.find(({ meta }) => meta.name === commandName); + const cmd = cmds.find((cmd) => cmd.getFullCmdName(cmd.meta.name) === commandName); if(!cmd || !cmd.enabled) return; From abe9ca332120760ce3a25865ffc8f7901b7148fd Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sun, 20 Nov 2022 19:02:42 +0100 Subject: [PATCH 49/51] this shit aint working --- src/commands/util/Poll.ts | 110 +++++++++++++++++++++++-------------- src/commands/util/Whois.ts | 2 - src/modals/poll.ts | 36 +++++++----- 3 files changed, 91 insertions(+), 57 deletions(-) diff --git a/src/commands/util/Poll.ts b/src/commands/util/Poll.ts index ef200ac..7242a6a 100644 --- a/src/commands/util/Poll.ts +++ b/src/commands/util/Poll.ts @@ -11,11 +11,13 @@ import { Tuple } from "@src/types"; const redis = getRedis(); -interface PollVote { +/** Object that keeps track of one poll option's votes */ +interface PollOptionVotes { msg: Message; emoji: string; option: string; - votes: string[] + /** user ids that voted for this option */ + votes: string[]; } export class Poll extends Command @@ -83,7 +85,8 @@ export class Poll extends Command try { this.checkPolls(); - setInterval(() => this.checkPolls(), 2000); + // setInterval(() => this.checkPolls(), 2000); + setInterval(() => this.checkPolls(), 20000); //#DEBUG } catch(err) { console.error(k.red("Error while checking polls:"), err); @@ -96,10 +99,10 @@ export class Poll extends Command const polls = await getActivePolls(); polls.forEach(async (poll) => { const { votesPerUser, guildId, pollId, voteOptions } = poll; - const msgs = (await this.getPollMsgs(poll))?.map(m => m); + const msgs = (await this.fetchPollMsgs(poll))?.map(m => m); if(msgs) { - const collectors = CreatePollModal.watchReactions(msgs, voteOptions, votesPerUser); + const collectors = CreatePollModal.watchReactions(this.client.user!.id, msgs, voteOptions, votesPerUser); this.reactionCollectors.push({ guildId, pollId, collectors }); } }); @@ -129,7 +132,7 @@ export class Poll extends Command const redisKey = `poll-modal-data_${guild.id}_${int.user.id}`; const modalData = await redis.get(redisKey); - const modal = new CreatePollModal(headline, votes_per_user, title, modalData ? JSON.parse(modalData) : undefined); + const modal = new CreatePollModal(this.client.user!.id, headline, votes_per_user, title, modalData ? JSON.parse(modalData) : undefined); modal.on("invalid", (data) => redis.set(redisKey, JSON.stringify(data))); modal.on("deleteCachedData", () => redis.del(redisKey)); @@ -208,12 +211,12 @@ export class Poll extends Command if(!memberPermissions?.has(PermissionFlagsBits.ManageChannels) && user.id !== poll.createdBy) return this.editReply(int, embedify("You are not the author of this poll so you can't delete it.", settings.embedColors.error)); - const pollMsgs = await this.getPollMsgs(poll); + const pollMsgs = await this.fetchPollMsgs(poll); if(!pollMsgs) return this.editReply(int, embedify("You can only use this command in a server.", settings.embedColors.error)); - const finalVotes = await this.accumulateVotes(pollMsgs.reduce((a, c) => { a.push(c as never); return a; }, []), poll.voteOptions); + const finalVotes = await this.accumulateVotes(pollMsgs.reduce((a, c) => { a.push(c as never); return a; }, []), poll); const { peopleVoted, getReducedWinningOpts } = this.parseFinalVotes(finalVotes); @@ -286,63 +289,77 @@ export class Poll extends Command { const expPolls = await getExpiredPolls(); + // can't Promise.all() else the Discord API could rate limit us, so instead use for ... await for await(const poll of expPolls) { - const { guildId, pollId, channel, voteOptions, dueTimestamp: endTime } = poll; + const { guildId, pollId, channel, dueTimestamp: endTime } = poll; const redisKey = `check_poll_${guildId}-${pollId}`; - // idk how to do this better - let remIdx: undefined | number = undefined; this.reactionCollectors.forEach((c, i) => { if(c.guildId === guildId && c.pollId === pollId) - remIdx = i; + this.reactionCollectors.splice(i, 1); }); - typeof remIdx === "number" && this.reactionCollectors.splice(remIdx, 1); - if(!(await redis.get(redisKey))) + const hasKey = await redis.get(redisKey); + if(hasKey) continue; await redis.set(redisKey, 1); + + // there is a tiny potential for the in-progress "delete jobs" cache to get + // out of whack so this timeout provides eventual consistency after a minute + // this problem only really occurs while debugging but who knows + const redisDelTimeout = setTimeout(() => redis.del(redisKey), 60_000); try { - const msgs = await this.getPollMsgs(poll); + const msgs = await this.fetchPollMsgs(poll); if(msgs && msgs.size > 0) { const firstMsg = msgs.at(0)!; - const finalVotes = await this.accumulateVotes(msgs.reduce((a, c) => { a.push(c as never); return a; }, []), voteOptions); + const finalVotes = await this.accumulateVotes(msgs.reduce((a, c) => { a.push(c as never); return a; }, []), poll); const startTime = firstMsg.createdAt; - // can't Promise.all() else the api could rate limit us - await firstMsg.edit({ embeds: [ this.getConclusionEmbed(finalVotes, startTime, endTime, guildId, channel, firstMsg.id) ] }); + await firstMsg.edit({ + embeds: [ this.getConclusionEmbed(finalVotes, startTime, endTime, guildId, channel, firstMsg.id) ], + }); - this.sendConclusion(firstMsg, finalVotes, startTime, endTime); + await this.sendConclusion(firstMsg, finalVotes, startTime, endTime); } - deletePoll(guildId, pollId); + await deletePoll(guildId, pollId); } catch(err) { // TODO: add logging lib console.error(`Error while checking poll with guildId=${guildId} and pollId=${pollId}:\n`, err); } finally { + clearTimeout(redisDelTimeout); await redis.del(redisKey); } } } - async getPollMsgs({ guildId, channel, messages }: PollObj) + /** Fetches all messages of the provided poll */ + async fetchPollMsgs({ guildId, channel, messages }: PollObj) { const gui = this.client.guilds.cache.find(g => g.id === guildId); if(!gui) return; - const chan = (await gui.channels.fetch()).find(c => c.id === channel); + const chan = (await gui.channels.fetch()).find(c => c.id === channel) as TextChannel | undefined; - return (chan as TextChannel | undefined)?.messages.cache - .filter(m => messages.includes(m.id)) + const msgs = await chan?.messages.fetch({ + // fetch around the centermost message + around: messages[Math.floor(messages.length / 2)], + // buffer for when the poll is sent in an active channel, as other members could send messages in between + limit: messages.length + 20, + }); + + return msgs + ?.filter(m => messages.includes(m.id)) // filter out all extra messages captured above .sort((a, b) => a.createdTimestamp < b.createdTimestamp ? 1 : -1); } - getConclusionEmbed(finalVotes: PollVote[], startTime: Date, endTime: Date, guildId: string, channelId: string, firstMsgId: string) + getConclusionEmbed(finalVotes: PollOptionVotes[], startTime: Date, endTime: Date, guildId: string, channelId: string, firstMsgId: string) { const { finalVotesFields, peopleVoted, totalVotes, winningOptions, getReducedWinningOpts @@ -360,7 +377,7 @@ export class Poll extends Command .addFields(finalVotesFields); } - parseFinalVotes(finalVotes: PollVote[]) + parseFinalVotes(finalVotes: PollOptionVotes[]) { const finalVotesFields = CreatePollModal.reduceOptionFields(finalVotes.map(v => `${v.option} - **${v.votes.length}**`, true)); @@ -381,13 +398,13 @@ export class Poll extends Command totalVotes += score; }); - const sortedVotes = finalVotes.sort((a, b) => a.votes.length < b.votes.length ? 1 : -1); - const winningOptions = sortedVotes.filter(v => v.votes === sortedVotes[0].votes); + const sortedVotes = finalVotes.sort((a, b) => a.votes.length === b.votes.length ? 0 : (a.votes.length < b.votes.length ? 1 : -1)); + const winningOptions = sortedVotes.filter(v => v.votes.length === sortedVotes[0].votes.length); const getReducedWinningOpts = (limit?: number) => winningOptions.reduce((a, c, i) => `${a}${ limit === undefined || i < limit - ? `\n\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} ${autoPlural("vote", c.votes)}**` : ""}` + ? `\n> ${c.emoji} \u200B ${c.option}${winningOptions.length > 1 ? `\nWith **${c.votes} ${autoPlural("vote", c.votes)}**` : ""}` : "" }`, ""); @@ -403,29 +420,42 @@ export class Poll extends Command }; } - sendConclusion(msg: Message, finalVotes: PollVote[], startTime: Date, endTime: Date) + sendConclusion(msg: Message, finalVotes: PollOptionVotes[], startTime: Date, endTime: Date) { - // TODO: - const { peopleVoted, getReducedWinningOpts } = this.parseFinalVotes(finalVotes); return msg.reply({ embeds: [ new EmbedBuilder() .setColor(settings.embedColors.default) - .setTitle("This poll has closed.") - .setDescription(`It ran from to \n${peopleVoted} people have voted and these are the results:\n\n${getReducedWinningOpts()}`) + .setTitle("This poll has ended.") + .setDescription(`It ran from to \n${peopleVoted} people have voted and these are the results:\n${getReducedWinningOpts()}`) ]}); } - async accumulateVotes(msgs: Message[], _voteOpts: string[]): Promise + /** Takes in Message instances to accumulate the provided reaction emoji votes on */ + async accumulateVotes(msgs: Message[], { voteOptions }: PollObj): Promise { - for await(const msg of msgs) - { - const reacts = msg.reactions.cache.entries(); + const votes: PollOptionVotes[] = []; + const voteOpts: { opt: string, emoji: string }[] = voteOptions.map((opt, i) => ({ opt, emoji: settings.emojiList[i] })); - console.log(reacts); + for await(const msg of msgs) { + for await(const [em, re] of [...msg.reactions.cache.entries()]) { + const voteOpt = voteOpts.find(vo => vo.emoji === em); + if(voteOpt) + { + if(!votes.find(v => v.emoji === em)) + votes.push({ + emoji: voteOpt.emoji, + msg: re.message as Message, + option: voteOpt.opt, + votes: (await re.users.fetch()) + .filter(u => !u.bot && !u.system) + .map(u => u.id), + }); + } + } } - return []; + return votes; } } diff --git a/src/commands/util/Whois.ts b/src/commands/util/Whois.ts index 7607068..eddb314 100644 --- a/src/commands/util/Whois.ts +++ b/src/commands/util/Whois.ts @@ -78,8 +78,6 @@ export class Whois extends Command goToPageBtn: pages.length > 5, }); - pe.on("error", (err) => console.log(err)); - await pe.useInt(int); } else diff --git a/src/modals/poll.ts b/src/modals/poll.ts index ea34290..d9634bc 100644 --- a/src/modals/poll.ts +++ b/src/modals/poll.ts @@ -26,13 +26,15 @@ export interface CreatePollModal { export class CreatePollModal extends Modal { + private clientId; + private headline; private votesPerUser; private title; public reactionCollectors: ReactionCollector[] = []; - constructor(headline?: string, votesPerUser = 1, title?: string, modalData?: PollModalData) + constructor(clientId: string, headline?: string, votesPerUser = 1, title?: string, modalData?: PollModalData) { const p = zeroPad, d = new Date(); const defaultExpiry = `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`; @@ -69,6 +71,8 @@ export class CreatePollModal extends Modal ], }); + this.clientId = clientId; + this.headline = headline; this.votesPerUser = votesPerUser; this.title = title; @@ -103,28 +107,30 @@ export class CreatePollModal extends Modal // TODO: this might get costly if the bot grows /** * Watches for extraneous reactions on the passed poll messages + * @param clientId ID of the bot client so its reactions can be ignored * @param msgs Messages to watch * @param voteOptions The options users can vote on * @static This function is static so it can be reused in @commands/Poll.ts */ - public static watchReactions(msgs: Message[], voteOptions: string[], votesPerUser: number) + public static watchReactions(clientId: string, msgs: Message[], voteOptions: string[], votesPerUser: number) { const colls: ReactionCollector[] = []; const pollEmojis = settings.emojiList.slice(0, voteOptions.length); msgs.forEach(msg => { - colls.push(msg.createReactionCollector({ - // TODO: check - filter: (re, user) => { - if(msgs.reduce( - (a, c) => a + c.reactions.cache.filter(r => r.users.cache.has(user.id)).size, 0 - ) <= votesPerUser) - re.remove(); - if(!pollEmojis.includes(re.emoji.name ?? "_")) - re.remove(); - return true; // collector doesn't actually do anything besides remove extraneous reactions - }, - })); + const coll = msg.createReactionCollector(); + coll.on("collect", (re, user) => { + if(user.bot && user.id !== clientId) + re.remove(); + if(msgs.reduce( + (a, c) => a + c.reactions.cache.filter(r => r.users.cache.has(user.id)).size, 0 + ) <= votesPerUser) + re.remove(); + // remove emojis added by users + if(!pollEmojis.includes(re.emoji.name ?? "_")) + re.remove(); + }); + colls.push(coll); }); return colls; } @@ -198,7 +204,7 @@ export class CreatePollModal extends Modal }); } - this.reactionCollectors = CreatePollModal.watchReactions(msgs, voteOptions, this.votesPerUser); + this.reactionCollectors = CreatePollModal.watchReactions(this.clientId, msgs, voteOptions, this.votesPerUser); const dbGld = await getGuild(guild.id); From 0d2f47f9301fc1c906d710edf3a2c19f682d48e7 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sun, 4 Dec 2022 01:23:16 +0100 Subject: [PATCH 50/51] chore: unhide some excluded files --- .vscode/settings.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 8f9e90b..c419e06 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -44,9 +44,7 @@ "editor.defaultFormatter": "vscode.json-language-features", }, "files.exclude": { - "**/.env": true, "out/**": true, - "node_modules/": true }, "git.branchPrefix": "feat/", "git.branchProtection": [ "main" ], From 71cb90fef77566ffdc93b4bf7c55252c7c0a92a3 Mon Sep 17 00:00:00 2001 From: Sv443 Date: Sun, 4 Dec 2022 01:24:02 +0100 Subject: [PATCH 51/51] feat: input lang & more improvements in /translate --- src/commands/util/Translate.ts | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/commands/util/Translate.ts b/src/commands/util/Translate.ts index 67ce93b..387eb5b 100644 --- a/src/commands/util/Translate.ts +++ b/src/commands/util/Translate.ts @@ -9,6 +9,9 @@ import { isArrayEmpty } from "svcorelib"; export class Translate extends Command { + readonly LANGS = Object.entries(languages) + .map(([name, code]) => ({ name, code })); + constructor() { super({ @@ -28,6 +31,12 @@ export class Translate extends Command type: ApplicationCommandOptionType.String, required: true, }, + { + name: "input_language", + desc: "Language of the text to translate. Leave empty to auto-detect.", + type: ApplicationCommandOptionType.String, + required: false, + }, ], }); } @@ -36,11 +45,9 @@ export class Translate extends Command { const text = (int.options.get("text", true).value as string).trim(); const lang = (int.options.get("language", true).value as string).trim(); + const inLang = (int.options.get("input_language")?.value as string | null)?.trim(); - const langs = Object.entries(languages) - .map(([name, code]) => ({ name, code })); - - const fuse = new Fuse(langs, { + const fuse = new Fuse(this.LANGS, { keys: [ "name" ], threshold: 0.5, }); @@ -54,7 +61,7 @@ export class Translate extends Command await this.deferReply(int); - const tr = await this.getTranslation(text, resLang.code); + const tr = await this.getTranslation(text, resLang.code, inLang); if(!tr) return await this.editReply(int, embedify("Couldn't find a translation for that", settings.embedColors.error)); @@ -72,16 +79,16 @@ export class Translate extends Command return await this.editReply(int, ebd); } - async getTranslation(text: string, targetLang: string): Promise<{ fromLang: string, translation: string } | null> + async getTranslation(text: string, targetLang: string, inLang = "auto") { try { - const { data, status } = await axios.get(`https://translate.googleapis.com/translate_a/single?sl=auto&tl=${targetLang}&q=${encodeURI(text)}&client=gtx&dt=t&ie=UTF-8&oe=UTF-8`); + const { data, status } = await axios.get(`https://translate.googleapis.com/translate_a/single?sl=${inLang}&tl=${targetLang}&q=${encodeURI(text)}&client=gtx&dt=t&ie=UTF-8&oe=UTF-8`); if(status < 200 || status >= 300) return null; - const fromLang = data?.[2]; + const fromLang = data?.[2] as string | undefined; let trParts = data?.[0]; if(!fromLang || !trParts) @@ -95,8 +102,8 @@ export class Translate extends Command if(isArrayEmpty(trParts) === true) return null; - const translation = trParts - .filter((p: unknown) => typeof p === "string") + const translation = (trParts as unknown[]) + .filter(p => typeof p === "string") .join("").trim(); return { fromLang, translation };