diff --git a/package-lock.json b/package-lock.json index 26f3f99..c453438 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@discordjs/rest": "^1.7.0", "@tsconfig/recommended": "^1.0.2", "@types/node": "^18.15.11", + "@types/node-cron": "^3.0.7", "@types/request": "^2.48.8", "@types/uuid": "^9.0.1", "axios": "^1.3.5", @@ -20,6 +21,7 @@ "discord.js": "^14.9.0", "dotenv": "^16.0.3", "jellyfin-apiclient": "^1.10.0", + "node-cron": "^3.0.2", "sqlite3": "^5.1.6", "ts-node": "^10.9.1", "typescript": "^5.0.4", @@ -1585,6 +1587,11 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz", "integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==" }, + "node_modules/@types/node-cron": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.7.tgz", + "integrity": "sha512-9PuLtBboc/+JJ7FshmJWv769gDonTpItN0Ol5TMwclpSQNjVyB2SRxSKBcTtbSysSL5R7Oea06kTTFNciCoYwA==" + }, "node_modules/@types/prettier": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", @@ -5004,6 +5011,25 @@ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==" }, + "node_modules/node-cron": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz", + "integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==", + "dependencies": { + "uuid": "8.3.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/node-cron/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/node-fetch": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", @@ -8124,6 +8150,11 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz", "integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==" }, + "@types/node-cron": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.7.tgz", + "integrity": "sha512-9PuLtBboc/+JJ7FshmJWv769gDonTpItN0Ol5TMwclpSQNjVyB2SRxSKBcTtbSysSL5R7Oea06kTTFNciCoYwA==" + }, "@types/prettier": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", @@ -10702,6 +10733,21 @@ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==" }, + "node-cron": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz", + "integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==", + "requires": { + "uuid": "8.3.2" + }, + "dependencies": { + "uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" + } + } + }, "node-fetch": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", diff --git a/package.json b/package.json index 4b1d930..c70ccba 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "@discordjs/rest": "^1.7.0", "@tsconfig/recommended": "^1.0.2", "@types/node": "^18.15.11", + "@types/node-cron": "^3.0.7", "@types/request": "^2.48.8", "@types/uuid": "^9.0.1", "axios": "^1.3.5", @@ -16,6 +17,7 @@ "discord.js": "^14.9.0", "dotenv": "^16.0.3", "jellyfin-apiclient": "^1.10.0", + "node-cron": "^3.0.2", "sqlite3": "^5.1.6", "ts-node": "^10.9.1", "typescript": "^5.0.4", diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index 6363fdd..66131cc 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -1,11 +1,10 @@ -import { Command } from '../structures/command' -import { RunOptions } from '../types/commandTypes' -import { APIEmbed, Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageEditOptions, TextChannel } from 'discord.js' +import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageEditOptions, TextChannel } from 'discord.js' import { v4 as uuid } from 'uuid' -import { logger } from '../logger' import { config } from '../configuration' import { Emotes } from '../events/guildScheduledEventCreate' -import { EndOfLineState } from 'typescript' +import { logger } from '../logger' +import { Command } from '../structures/command' +import { RunOptions } from '../types/commandTypes' export default new Command({ name: 'closepoll', @@ -16,38 +15,52 @@ export default new Command({ const requestId = uuid() const guildId = command.guildId! logger.info("Got command for closing poll!", { guildId: guildId, requestId }) + if (!command.guild) { + logger.error("No guild found in interaction. Cancelling closing request") + command.followUp("Es gab leider ein Problem. Ich konnte deine Anfrage nicht bearbeiten :(") + return + } - const announcementChannel: TextChannel = (await command.guild?.channels.fetch()) - ?.filter(channel => channel!.id === config.bot.announcement_channel_id) - .map((value, _) => value)[0] //todo: needs to be done less sketchy - - interaction.interaction.followUp("Alles klar, beende die Umfrage :)") - - - const messages: Message[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages - .map((value, _) => value) - .filter(message => !message.cleanContent.includes("[Abstimmung beendet]") && message.cleanContent.includes("[Abstimmung]")) - .sort((a, b) => b.createdTimestamp - a.createdTimestamp) - - - const lastMessage: Message = messages[0] - - logger.debug(`Found messages: ${JSON.stringify(messages, null, 2)}`, { guildId: guildId, requestId }) - - logger.debug(`Last message: ${JSON.stringify(lastMessage, null, 2)}`, { guildId: guildId, requestId }) - - const votes = await (await getVotesByEmote(lastMessage, guildId, requestId)) - .sort((a, b) => b.count - a.count) - - logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId: guildId, requestId }) - - updateEvent(votes, command.guild!, guildId, requestId) - updateMessage(votes[0].movie, lastMessage, guildId, requestId) - - //lastMessage.unpin() //todo: uncomment when bot has permission to pin/unpin + command.followUp("Alles klar, beende die Umfrage :)") + closePoll(command.guild, requestId) } }) +export async function closePoll(guild: Guild, requestId: string) { + const guildId = guild.id + logger.info("stopping poll", { guildId: guildId, requestId }) + const announcementChannel: TextChannel = (await guild.channels.fetch()) + ?.filter(channel => channel!.id === config.bot.announcement_channel_id) + .map((value, _) => value)[0] //todo: needs to be done less sketchy + + const messages: Message[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages + .map((value, _) => value) + .filter(message => !message.cleanContent.includes("[Abstimmung beendet]") && message.cleanContent.includes("[Abstimmung]")) + .sort((a, b) => b.createdTimestamp - a.createdTimestamp) + + if (!messages || messages.length <= 0) { + logger.info("Could not find any vote messages. Cancelling pollClose", { guildId: guildId, requestId }) + return + } + + + const lastMessage: Message = messages[0] + + logger.debug(`Found messages: ${JSON.stringify(messages, null, 2)}`, { guildId: guildId, requestId }) + + logger.debug(`Last message: ${JSON.stringify(lastMessage, null, 2)}`, { guildId: guildId, requestId }) + + const votes = await (await getVotesByEmote(lastMessage, guildId, requestId)) + .sort((a, b) => b.count - a.count) + + logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId: guildId, requestId }) + + updateEvent(votes, guild!, guildId, requestId) + updateMessage(votes[0].movie, lastMessage, guildId, requestId) + + //lastMessage.unpin() //todo: uncomment when bot has permission to pin/unpin +} + async function updateMessage(movie: string, message: Message, guildId: string, requestId: string) { const body = `[Abstimmung beendet] Gewonnen hat: ${movie}` .concat(message.cleanContent.substring("[Abstimmung]".length)) @@ -65,15 +78,16 @@ async function updateEvent(votes: Vote[], guild: Guild, guildId: string, request .map((value, _) => value) .filter(event => event.name.toLowerCase().includes("voting offen")) logger.debug(`Found events: ${JSON.stringify(voteEvents, null, 2)}`, { guildId: guildId, requestId }) - - if(!voteEvents || voteEvents.length <= 0) { + + if (!voteEvents || voteEvents.length <= 0) { logger.error("Could not find vote event. Cancelling update!", { guildId: guildId, requestId }) + return } const voteEvent: GuildScheduledEvent = voteEvents[0] const options: GuildScheduledEventEditOptions> = { name: votes[0].movie, - description: `!wp\nNummer 2: ${votes[1].movie} mit ${votes[1].count -1} Stimmen\nNummer 3: ${votes[2].movie} mit ${votes[2].count -1} Stimmen` + description: `!wp\nNummer 2: ${votes[1].movie} mit ${votes[1].count - 1} Stimmen\nNummer 3: ${votes[2].movie} mit ${votes[2].count - 1} Stimmen` } logger.debug(`Updating event: ${JSON.stringify(voteEvent, null, 2)}`, { guildId: guildId, requestId }) voteEvent.edit(options) @@ -90,7 +104,6 @@ async function getVotesByEmote(message: Message, guildId: string, requestId: str logger.debug(`Number of items in emotes: ${Object.values(Emotes).length}`) for (let i = 0; i < Object.keys(Emotes).length / 2; i++) { const emote = Emotes[i] - // for (const emote of Object.keys(Emotes)) { logger.debug(`Getting reaction for emote ${emote}`, { guildId: guildId, requestId }) const reaction = await message.reactions.resolve(emote) logger.debug(`Reaction for emote ${emote}: ${JSON.stringify(reaction, null, 2)}`, { guildId: guildId, requestId }) diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts index 312ccdd..e997807 100644 --- a/server/events/guildScheduledEventCreate.ts +++ b/server/events/guildScheduledEventCreate.ts @@ -1,14 +1,17 @@ -import { BaseFetchOptions, ChannelType, GuildBasedChannel, GuildChannelResolvable, GuildMember, GuildScheduledEvent, GuildScheduledEventStatus, Message, TextChannel, messageLink } from "discord.js"; +import { GuildScheduledEvent, Message, TextChannel } from "discord.js"; +import { ScheduledTask, schedule } from "node-cron"; import { v4 as uuid } from "uuid"; import { jellyfinHandler } from "../.."; -import { getGuildSpecificTriggerRoleId } from "../helper/roleFilter"; -import { logger } from "../logger"; +import { closePoll } from "../commands/closepoll"; import { config } from "../configuration"; +import { logger } from "../logger"; export const name = 'guildScheduledEventCreate' -export enum Emotes {"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"} +export enum Emotes { "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" } + +export let task: ScheduledTask | undefined export async function execute(event: GuildScheduledEvent) { const requestId = uuid() @@ -23,8 +26,6 @@ export async function execute(event: GuildScheduledEvent) { logger.info(`Got ${movies.length} random movies. Creating voting`, { guildId: event.guildId, requestId }) logger.debug(`Movies: ${JSON.stringify(movies.map(movie => movie.name))}`, { guildId: event.guildId, requestId }) - - const channel: TextChannel = (await event.guild?.channels.fetch())?.filter(channel => channel!.id === config.bot.announcement_channel_id).map((value, _) => value)[0] //todo: needs to be done less sketchy logger.debug(`Found channel ${JSON.stringify(channel, null, 2)}`) @@ -40,6 +41,42 @@ export async function execute(event: GuildScheduledEvent) { sentMessage.react(Emotes[i]) } + if(!task){ + task = schedule("0 * * * * *", () => checkForPollsToClose(event)) + } + // sentMessage.pin() //todo: uncomment when bot has permission to pin messages. Also update closepoll.ts to only fetch pinned messages } +} + +async function checkForPollsToClose(event: GuildScheduledEvent): Promise { + const requestId = uuid() + logger.info(`Automatic check for poll closing.`, { guildId: event.guildId, requestId }) + if (!event.guild) { + logger.error("No guild in event. Cancelling.", { guildId: event.guildId, requestId }) + return + } + //refetch event in case the time changed or the poll is already closed + const events = (await event.guild.scheduledEvents.fetch()) + .filter(event => event.name.toLowerCase().includes("voting offen")) + .map((value, _) => value) + + if(!events || events.length <= 0) { + logger.info("Did not find any events. Cancelling", { guildId: event.guildId, requestId }) + return + } else if(events.length > 1) { + logger.error(`More than one event found. Don't know which one is the right one :( Events: ${JSON.stringify(events, null, 2)}`, { guildId: event.guildId, requestId }) + return + } + const updatedEvent = events[0] //add two hours because of different timezones in discord api and Date.now() + if(!updatedEvent.scheduledStartTimestamp) { + logger.error("Event does not have a scheduled start time. Cancelling", { guildId: event.guildId, requestId }) + return + } + if ((updatedEvent.scheduledStartTimestamp - Date.now()) <= (1000 * 60 * 60 * 24 * 2)) { + logger.info("Less than two days until event. Closing poll", { guildId: event.guildId, requestId }) + closePoll(event.guild, requestId) + } else { + logger.info(`ScheduledStart: ${updatedEvent.scheduledStartTimestamp}. Now: ${Date.now()}`, { guildId: event.guildId, requestId }) + } } \ No newline at end of file