From 2707f7d73bc2caae477a5cb7e1b142ad055d4835 Mon Sep 17 00:00:00 2001 From: Sammy Date: Sat, 10 Jun 2023 14:23:10 +0200 Subject: [PATCH 01/11] Add automatic creation of vote message with random movies When a !nextwp event is created the bot will fetch random movies and create a message that people can vote on --- server/configuration.ts | 5 ++- server/events/guildScheduledEventCreate.ts | 44 +++++++++++++++++++ server/events/guildScheduledEventUpdate.ts | 3 +- server/jellyfin/handler.ts | 50 +++++++++++++++++++--- 4 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 server/events/guildScheduledEventCreate.ts diff --git a/server/configuration.ts b/server/configuration.ts index fa3d020..adb58fc 100644 --- a/server/configuration.ts +++ b/server/configuration.ts @@ -1,4 +1,5 @@ import dotenv from "dotenv" +import { AddListingProviderRequestToJSON } from "./jellyfin" dotenv.config() interface options { @@ -22,6 +23,7 @@ export interface Config { workaround_token: string watcher_role: string jf_admin_role: string + announcement_channel_id: string } } export const config: Config = { @@ -53,6 +55,7 @@ export const config: Config = { jellyfin_url: process.env.JELLYFIN_URL ?? "", workaround_token: process.env.TOKEN ?? "", watcher_role: process.env.WATCHER_ROLE ?? "", - jf_admin_role: process.env.ADMIN_ROLE ?? "" + jf_admin_role: process.env.ADMIN_ROLE ?? "", + announcement_channel_id: process.env.CHANNEL_ID ?? "" } } diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts new file mode 100644 index 0000000..1896691 --- /dev/null +++ b/server/events/guildScheduledEventCreate.ts @@ -0,0 +1,44 @@ +import { BaseFetchOptions, ChannelType, GuildBasedChannel, GuildChannelResolvable, GuildMember, GuildScheduledEvent, GuildScheduledEventStatus, Message, TextChannel, messageLink } from "discord.js"; +import { v4 as uuid } from "uuid"; +import { jellyfinHandler } from "../.."; +import { getGuildSpecificTriggerRoleId } from "../helper/roleFilter"; +import { logger } from "../logger"; +import { config } from "../configuration"; + + +export const name = 'guildScheduledEventCreate' + +const emotes = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] + +export async function execute(event: GuildScheduledEvent) { + const requestId = uuid() + logger.debug(`New event created: ${JSON.stringify(event, null, 2)}`, { guildId: event.guildId, requestId }) + + if (event.name.toLowerCase().includes("!nextwp")) { + logger.info("Event was a placeholder event to start a new watchparty and voting. Creating vote!", { guildId: event.guildId, requestId }) + logger.debug("Renaming event", { guildId: event.guildId, requestId }) + event.edit({ name: "Watchparty - Voting offen" }) + const movies = await jellyfinHandler.getRandomMovies(5, event.guildId, requestId) + + 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)}`) + + let message = "Es gibt eine neue Abstimmung für die nächste Watchparty! Stimme hierunter für den nächsten Film ab!\n" + + for (let i = 0; i < movies.length; i++) { + message = message.concat(emotes[i]).concat(": ").concat(movies[i].name!).concat("\n") + } + + const sentMessage: Message = await (await channel.fetch()).send(message) + + for (let i = 0; i < movies.length; i++) { + sentMessage.react(emotes[i]) + } + + } +} \ No newline at end of file diff --git a/server/events/guildScheduledEventUpdate.ts b/server/events/guildScheduledEventUpdate.ts index c08353f..d731b09 100644 --- a/server/events/guildScheduledEventUpdate.ts +++ b/server/events/guildScheduledEventUpdate.ts @@ -9,8 +9,8 @@ export const name = 'guildScheduledEventUpdate' export async function execute(oldEvent: GuildScheduledEvent, newEvent: GuildScheduledEvent) { try { - logger.info(JSON.stringify(newEvent, null, 2)) const requestId = uuid() + logger.debug(`Got scheduledEvent update. New Event: ${JSON.stringify(newEvent, null, 2)}`,{guildId: newEvent.guildId, requestId}) if (newEvent.description?.toLowerCase().includes("!wp") && [GuildScheduledEventStatus.Active, GuildScheduledEventStatus.Completed].includes(newEvent.status)) { const roles = getGuildSpecificTriggerRoleId(newEvent.guildId).map((key, value)=> value) @@ -37,6 +37,7 @@ export async function execute(oldEvent: GuildScheduledEvent, newEvent: GuildSche logger.error(error) } } + async function createJFUsers(members: GuildMember[], movieName: string, requestId?: string) { logger.info(`Creating users for: \n ${JSON.stringify(members, null, 2)}`) members.forEach(member => { diff --git a/server/jellyfin/handler.ts b/server/jellyfin/handler.ts index 18bb0e4..7bdd0df 100644 --- a/server/jellyfin/handler.ts +++ b/server/jellyfin/handler.ts @@ -2,8 +2,8 @@ import { GuildMember } from "discord.js"; import { Config } from "../configuration"; import { Maybe, PermissionLevel } from "../interfaces"; import { logger } from "../logger"; -import { CreateUserByNameOperationRequest, DeleteUserRequest, SystemApi, UpdateUserPasswordOperationRequest, UpdateUserPolicyOperationRequest, UserApi } from "./apis"; -import { UpdateUserPasswordRequest } from "./models"; +import { CreateUserByNameOperationRequest, DeleteUserRequest, GetItemsRequest, GetMovieRemoteSearchResultsOperationRequest, ItemLookupApi, ItemsApi, LibraryApi, SystemApi, UpdateUserPasswordOperationRequest, UpdateUserPolicyOperationRequest, UserApi } from "./apis"; +import { BaseItemDto, UpdateUserPasswordRequest } from "./models"; import { UserDto } from "./models/UserDto"; import { Configuration, ConfigurationParameters } from "./runtime"; @@ -12,6 +12,7 @@ export class JellyfinHandler { private userApi: UserApi private systemApi: SystemApi + private moviesApi: ItemsApi private token: string private authHeader: { headers: { 'X-Emby-Authorization': string } } private config: Config @@ -24,7 +25,7 @@ export class JellyfinHandler { } return this.serverName } - constructor(_config: Config, _userApi?: UserApi, _systemApi?: SystemApi) { + constructor(_config: Config, _userApi?: UserApi, _systemApi?: SystemApi, _itemsApi?: ItemsApi) { this.config = _config this.token = this.config.bot.jellfin_token this.authHeader = { @@ -40,8 +41,14 @@ export class JellyfinHandler { basePath: this.config.bot.jellyfin_url, headers: this.authHeader.headers } + const libraryApiConfigurationParams: ConfigurationParameters = { + basePath: this.config.bot.jellyfin_url, + headers: this.authHeader.headers + } + this.userApi = _userApi ?? new UserApi(new Configuration(userApiConfigurationParams)) this.systemApi = _systemApi ?? new SystemApi(new Configuration(systemApiConfigurationParams)) + this.moviesApi = _itemsApi ?? new ItemsApi(new Configuration(libraryApiConfigurationParams)) logger.info(`Initialized Jellyfin handler`, { requestId: 'Init' }) } @@ -222,7 +229,38 @@ export class JellyfinHandler { } } - -} -export enum UserUpsertResult {enabled, created} + public async getAllMovies(guildId: string, requestId: string): Promise { + logger.info("requesting all movies from jellyfin", { guildId: guildId, requestId }) + + const liloJfUser = await this.getUser({ guild: { id: guildId }, displayName: "lilo" }, requestId) + + const searchParams: GetItemsRequest = { + userId: liloJfUser?.id, + parentId: "f137a2dd21bbc1b99aa5c0f6bf02a805" // collection ID for all movies + } + const movies = (await (this.moviesApi.getItems(searchParams))).items?.filter(item => !item.isFolder) + // logger.debug(JSON.stringify(movies, null, 2), { guildId: guildId, requestId }) + logger.info(`Found ${movies?.length} movies in total`, { guildId: guildId, requestId }) + return movies ?? [] + } + + public async getRandomMovies(count: number, guildId: string, requestId: string): Promise { + logger.info(`${count} random movies requested.`, { guildId: guildId, requestId }) + const allMovies = await this.getAllMovies(guildId, requestId) + if (count >= allMovies.length) { + logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`) + return allMovies + } + const movies: BaseItemDto[] = [] + for (let i = 0; i < count; i++) { + const index = Math.random() * allMovies.length + movies.push(...allMovies.splice(index, 1)) // maybe out of bounds? ? + } + + return movies + } + + +} +export enum UserUpsertResult { enabled, created } -- 2.40.1 From c8fa89ae63eddb932c7ffdfe0f12e7243b88494f Mon Sep 17 00:00:00 2001 From: Sammy Date: Sat, 10 Jun 2023 17:27:32 +0200 Subject: [PATCH 02/11] Add command to close the poll and update the event --- server/commands/closepoll.ts | 115 +++++++++++++++++++++ server/events/guildScheduledEventCreate.ts | 9 +- 2 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 server/commands/closepoll.ts diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts new file mode 100644 index 0000000..6363fdd --- /dev/null +++ b/server/commands/closepoll.ts @@ -0,0 +1,115 @@ +import { Command } from '../structures/command' +import { RunOptions } from '../types/commandTypes' +import { APIEmbed, 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' + +export default new Command({ + name: 'closepoll', + description: 'Aktuelle Umfrage für nächste Watchparty beenden und Gewinner in Event eintragen.', + options: [], + run: async (interaction: RunOptions) => { + const command = interaction.interaction + const requestId = uuid() + const guildId = command.guildId! + logger.info("Got command for closing poll!", { guildId: guildId, requestId }) + + 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 + } +}) + +async function updateMessage(movie: string, message: Message, guildId: string, requestId: string) { + const body = `[Abstimmung beendet] Gewonnen hat: ${movie}` + .concat(message.cleanContent.substring("[Abstimmung]".length)) + + const options: MessageEditOptions = { + content: body, + } + message.edit(options) + +} + +async function updateEvent(votes: Vote[], guild: Guild, guildId: string, requestId: string) { + logger.info(`Updating event with movie ${votes[0].movie}.`, { guildId: guildId, requestId }) + const voteEvents = (await guild.scheduledEvents.fetch()) + .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) { + logger.error("Could not find vote event. Cancelling update!", { guildId: guildId, requestId }) + } + + 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` + } + logger.debug(`Updating event: ${JSON.stringify(voteEvent, null, 2)}`, { guildId: guildId, requestId }) + voteEvent.edit(options) +} + +type Vote = { + emote: string, //todo habs nicht hinbekommen hier Emotes zu nutzen + count: number, + movie: string +} + +async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise { + const votes: Vote[] = [] + 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 }) + if (reaction) { + const vote: Vote = { emote: emote, count: reaction.count, movie: extractMovieFromMessageByEmote(message, emote, guildId, requestId) } + votes.push(vote) + } + } + return votes +} + +function extractMovieFromMessageByEmote(message: Message, emote: string, guildId: string, requestId: string): string { + const lines = message.cleanContent.split("\n") + const emoteLines = lines.filter(line => line.includes(emote)) + + if (!emoteLines) { + return "" + } + const movie = emoteLines[0].substring(emoteLines[0].indexOf(emote) + emote.length + 2) // plus colon and space + + return movie +} \ No newline at end of file diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts index 1896691..312ccdd 100644 --- a/server/events/guildScheduledEventCreate.ts +++ b/server/events/guildScheduledEventCreate.ts @@ -8,7 +8,7 @@ import { config } from "../configuration"; export const name = 'guildScheduledEventCreate' -const emotes = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] +export enum Emotes {"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"} export async function execute(event: GuildScheduledEvent) { const requestId = uuid() @@ -28,17 +28,18 @@ export async function execute(event: GuildScheduledEvent) { 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)}`) - let message = "Es gibt eine neue Abstimmung für die nächste Watchparty! Stimme hierunter für den nächsten Film ab!\n" + let message = "[Abstimmung]\nEs gibt eine neue Abstimmung für die nächste Watchparty! Stimme hierunter für den nächsten Film ab!\n" for (let i = 0; i < movies.length; i++) { - message = message.concat(emotes[i]).concat(": ").concat(movies[i].name!).concat("\n") + message = message.concat(Emotes[i]).concat(": ").concat(movies[i].name!).concat("\n") } const sentMessage: Message = await (await channel.fetch()).send(message) for (let i = 0; i < movies.length; i++) { - sentMessage.react(emotes[i]) + sentMessage.react(Emotes[i]) } + // sentMessage.pin() //todo: uncomment when bot has permission to pin messages. Also update closepoll.ts to only fetch pinned messages } } \ No newline at end of file -- 2.40.1 From c2d8838cf8e270ddfeda6a327e98906879e6882b Mon Sep 17 00:00:00 2001 From: Sammy Date: Sat, 10 Jun 2023 22:53:11 +0200 Subject: [PATCH 03/11] polls will be closed automatically 2 days before event start --- package-lock.json | 46 ++++++++++++ package.json | 2 + server/commands/closepoll.ts | 87 +++++++++++++--------- server/events/guildScheduledEventCreate.ts | 49 ++++++++++-- 4 files changed, 141 insertions(+), 43 deletions(-) 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 -- 2.40.1 From 0d5c3d30a90676d731bfc7a56061d7c7aec50827 Mon Sep 17 00:00:00 2001 From: Sammy Date: Sat, 10 Jun 2023 22:58:00 +0200 Subject: [PATCH 04/11] Fix loggers Some logger messages were missing requestId and guildId --- server/commands/closepoll.ts | 6 ++++-- server/events/guildScheduledEventCreate.ts | 2 +- server/jellyfin/handler.ts | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index 66131cc..062df9e 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -16,7 +16,7 @@ export default new Command({ 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") + logger.error("No guild found in interaction. Cancelling closing request", {guildId: guildId, requestId}) command.followUp("Es gab leider ein Problem. Ich konnte deine Anfrage nicht bearbeiten :(") return } @@ -68,6 +68,7 @@ async function updateMessage(movie: string, message: Message, guildId: string, r const options: MessageEditOptions = { content: body, } + logger.info("Updating message.", {guildId: guildId, requestId}) message.edit(options) } @@ -90,6 +91,7 @@ async function updateEvent(votes: Vote[], guild: Guild, guildId: string, request 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 }) + logger.info("Updating event.", {guildId: guildId, requestId}) voteEvent.edit(options) } @@ -101,7 +103,7 @@ type Vote = { async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise { const votes: Vote[] = [] - logger.debug(`Number of items in emotes: ${Object.values(Emotes).length}`) + logger.debug(`Number of items in emotes: ${Object.values(Emotes).length}`, {guildId: guildId, requestId}) for (let i = 0; i < Object.keys(Emotes).length / 2; i++) { const emote = Emotes[i] logger.debug(`Getting reaction for emote ${emote}`, { guildId: guildId, requestId }) diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts index e997807..da1985c 100644 --- a/server/events/guildScheduledEventCreate.ts +++ b/server/events/guildScheduledEventCreate.ts @@ -27,7 +27,7 @@ export async function execute(event: GuildScheduledEvent) { 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)}`) + logger.debug(`Found channel ${JSON.stringify(channel, null, 2)}`, { guildId: event.guildId, requestId }) let message = "[Abstimmung]\nEs gibt eine neue Abstimmung für die nächste Watchparty! Stimme hierunter für den nächsten Film ab!\n" diff --git a/server/jellyfin/handler.ts b/server/jellyfin/handler.ts index 7bdd0df..4bd5c67 100644 --- a/server/jellyfin/handler.ts +++ b/server/jellyfin/handler.ts @@ -248,7 +248,7 @@ export class JellyfinHandler { logger.info(`${count} random movies requested.`, { guildId: guildId, requestId }) const allMovies = await this.getAllMovies(guildId, requestId) if (count >= allMovies.length) { - logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`) + logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`, { guildId: guildId, requestId }) return allMovies } const movies: BaseItemDto[] = [] -- 2.40.1 From 1ee55f995cea7a36abe90bbd07366dd62008bdf7 Mon Sep 17 00:00:00 2001 From: Sammy Date: Sun, 11 Jun 2023 09:01:25 +0200 Subject: [PATCH 05/11] minor resilience improvement and formatting in closepoll.ts was an unsafe arrays usage without checking the bounds --- server/commands/closepoll.ts | 11 ++++++++--- server/events/guildScheduledEventCreate.ts | 8 ++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index 062df9e..66c3beb 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -29,9 +29,15 @@ export default new Command({ 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()) + const channels: 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 + .map((value, _) => value) + + if(!channels || channels.length != 1) { + logger.error(`Could not find announcement channel. Found ${channels}`) + } + + const announcementChannel = channels[0] const messages: Message[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages .map((value, _) => value) @@ -43,7 +49,6 @@ export async function closePoll(guild: Guild, requestId: string) { return } - const lastMessage: Message = messages[0] logger.debug(`Found messages: ${JSON.stringify(messages, null, 2)}`, { guildId: guildId, requestId }) diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts index da1985c..9b51552 100644 --- a/server/events/guildScheduledEventCreate.ts +++ b/server/events/guildScheduledEventCreate.ts @@ -41,7 +41,7 @@ export async function execute(event: GuildScheduledEvent) { sentMessage.react(Emotes[i]) } - if(!task){ + if (!task) { task = schedule("0 * * * * *", () => checkForPollsToClose(event)) } @@ -61,15 +61,15 @@ async function checkForPollsToClose(event: GuildScheduledEvent): Promise { .filter(event => event.name.toLowerCase().includes("voting offen")) .map((value, _) => value) - if(!events || events.length <= 0) { + if (!events || events.length <= 0) { logger.info("Did not find any events. Cancelling", { guildId: event.guildId, requestId }) return - } else if(events.length > 1) { + } 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) { + if (!updatedEvent.scheduledStartTimestamp) { logger.error("Event does not have a scheduled start time. Cancelling", { guildId: event.guildId, requestId }) return } -- 2.40.1 From 550aa53188b99adb5e9910ae7feebc13dbd0e9d6 Mon Sep 17 00:00:00 2001 From: Sammy Date: Sun, 11 Jun 2023 09:12:14 +0200 Subject: [PATCH 06/11] make closepoll return when no channel found --- server/commands/closepoll.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index 66c3beb..fa3be24 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -35,6 +35,7 @@ export async function closePoll(guild: Guild, requestId: string) { if(!channels || channels.length != 1) { logger.error(`Could not find announcement channel. Found ${channels}`) + return } const announcementChannel = channels[0] -- 2.40.1 From 117ff23a0ce7c2313f09475f53f52822e75fc0c0 Mon Sep 17 00:00:00 2001 From: Sammy Date: Sun, 11 Jun 2023 15:42:31 +0200 Subject: [PATCH 07/11] remove typecast to unknown Somehow I thought it was necessary because the compiler said it at some point --- server/commands/closepoll.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index fa3be24..fb8e74c 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -29,7 +29,7 @@ export default new Command({ export async function closePoll(guild: Guild, requestId: string) { const guildId = guild.id logger.info("stopping poll", { guildId: guildId, requestId }) - const channels: TextChannel[] = (await guild.channels.fetch()) + const channels: TextChannel[] = (await guild.channels.fetch()) ?.filter(channel => channel!.id === config.bot.announcement_channel_id) .map((value, _) => value) -- 2.40.1 From 40d220ed7b90246e33454f190278dcadbcfbc00f Mon Sep 17 00:00:00 2001 From: Sammy Date: Mon, 12 Jun 2023 19:43:33 +0200 Subject: [PATCH 08/11] refactor: use date-fns for date comparison --- server/events/guildScheduledEventCreate.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts index 9b51552..f0b66b6 100644 --- a/server/events/guildScheduledEventCreate.ts +++ b/server/events/guildScheduledEventCreate.ts @@ -5,6 +5,8 @@ import { jellyfinHandler } from "../.."; import { closePoll } from "../commands/closepoll"; import { config } from "../configuration"; import { logger } from "../logger"; +import toDate from "date-fns/fp/toDate"; +import { addDays, isAfter, isBefore } from "date-fns"; export const name = 'guildScheduledEventCreate' @@ -73,10 +75,14 @@ async function checkForPollsToClose(event: GuildScheduledEvent): Promise { 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)) { + + const eventDate: Date = toDate(updatedEvent.scheduledStartTimestamp) + const closePollDate: Date = addDays(eventDate, -2) + + if (isAfter(Date.now(), closePollDate)) { 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 }) + logger.info(`ScheduledStart: ${closePollDate}. Now: ${toDate(Date.now())}`, { guildId: event.guildId, requestId }) } } \ No newline at end of file -- 2.40.1 From c0369fcb494a2e73cd9f94fb17d49b85e138cf38 Mon Sep 17 00:00:00 2001 From: Sammy Date: Mon, 12 Jun 2023 20:27:54 +0200 Subject: [PATCH 09/11] Fetch announcement channel at server start --- server/commands/closepoll.ts | 11 ++------- server/events/guildScheduledEventCreate.ts | 8 +++---- server/structures/client.ts | 27 +++++++++++++++++++--- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index fb8e74c..22c1a5f 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -5,6 +5,7 @@ import { Emotes } from '../events/guildScheduledEventCreate' import { logger } from '../logger' import { Command } from '../structures/command' import { RunOptions } from '../types/commandTypes' +import { client } from '../..' export default new Command({ name: 'closepoll', @@ -29,16 +30,8 @@ export default new Command({ export async function closePoll(guild: Guild, requestId: string) { const guildId = guild.id logger.info("stopping poll", { guildId: guildId, requestId }) - const channels: TextChannel[] = (await guild.channels.fetch()) - ?.filter(channel => channel!.id === config.bot.announcement_channel_id) - .map((value, _) => value) - - if(!channels || channels.length != 1) { - logger.error(`Could not find announcement channel. Found ${channels}`) - return - } - const announcementChannel = channels[0] + const announcementChannel: TextChannel = client.getAnnouncementChannelForGuild(guildId) const messages: Message[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages .map((value, _) => value) diff --git a/server/events/guildScheduledEventCreate.ts b/server/events/guildScheduledEventCreate.ts index f0b66b6..bdee85b 100644 --- a/server/events/guildScheduledEventCreate.ts +++ b/server/events/guildScheduledEventCreate.ts @@ -1,7 +1,7 @@ import { GuildScheduledEvent, Message, TextChannel } from "discord.js"; import { ScheduledTask, schedule } from "node-cron"; import { v4 as uuid } from "uuid"; -import { jellyfinHandler } from "../.."; +import { client, jellyfinHandler } from "../.."; import { closePoll } from "../commands/closepoll"; import { config } from "../configuration"; import { logger } from "../logger"; @@ -28,8 +28,8 @@ 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)}`, { guildId: event.guildId, requestId }) + const announcementChannel: TextChannel = client.getAnnouncementChannelForGuild(event.guildId) + logger.debug(`Found channel ${JSON.stringify(announcementChannel, null, 2)}`, { guildId: event.guildId, requestId }) let message = "[Abstimmung]\nEs gibt eine neue Abstimmung für die nächste Watchparty! Stimme hierunter für den nächsten Film ab!\n" @@ -37,7 +37,7 @@ export async function execute(event: GuildScheduledEvent) { message = message.concat(Emotes[i]).concat(": ").concat(movies[i].name!).concat("\n") } - const sentMessage: Message = await (await channel.fetch()).send(message) + const sentMessage: Message = await (await announcementChannel.fetch()).send(message) for (let i = 0; i < movies.length; i++) { sentMessage.react(Emotes[i]) diff --git a/server/structures/client.ts b/server/structures/client.ts index 06e1f50..d0b58cb 100644 --- a/server/structures/client.ts +++ b/server/structures/client.ts @@ -1,18 +1,21 @@ -import { ApplicationCommandDataResolvable, Client, ClientOptions, Collection, GatewayIntentBits, Guild, IntentsBitField, Snowflake } from "discord.js"; +import { ApplicationCommandDataResolvable, Client, ClientOptions, Collection, GatewayIntentBits, Guild, IntentsBitField, Snowflake, TextChannel } from "discord.js"; import { CommandType } from "../types/commandTypes"; import fs from 'fs' import { config } from "../configuration"; import { logger } from "../logger"; import { JellyfinHandler } from "../jellyfin/handler"; + + export class ExtendedClient extends Client { private eventFilePath = `${__dirname}/../events` private commandFilePath = `${__dirname}/../commands` private jellyfin: JellyfinHandler public commands: Collection = new Collection() + private announcementChannels: Collection = new Collection //guildId to TextChannel public constructor(jf: JellyfinHandler) { const intents: IntentsBitField = new IntentsBitField() - intents.add(IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.MessageContent, IntentsBitField.Flags.Guilds, IntentsBitField.Flags.DirectMessages, IntentsBitField.Flags.GuildScheduledEvents, IntentsBitField.Flags.GuildVoiceStates) + intents.add(IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.MessageContent, IntentsBitField.Flags.Guilds, IntentsBitField.Flags.DirectMessages, IntentsBitField.Flags.GuildScheduledEvents, IntentsBitField.Flags.GuildVoiceStates) const options: ClientOptions = { intents } super(options) this.jellyfin = jf @@ -61,20 +64,38 @@ export class ExtendedClient extends Client { //logger.info(`Ready processing ${JSON.stringify(client)}`) logger.info(`SlashCommands: ${JSON.stringify(slashCommands)}`) const guilds = client.guilds.cache + this.registerCommands(slashCommands, guilds) this.cacheUsers(guilds) + this.cacheAnnouncementServer(guilds) }) } catch (error) { logger.info(`Error refreshing slash commands: ${error}`) } } + private async cacheAnnouncementServer(guilds: Collection) { + for (const guild of guilds.values()) { + const channels: TextChannel[] = (await guild.channels.fetch()) + ?.filter(channel => channel!.id === config.bot.announcement_channel_id) + .map((value, _) => value) + + if (!channels || channels.length != 1) { + logger.error(`Could not find announcement channel for guild ${guild.name} with guildId ${guild.id}. Found ${channels}`) + continue + } + logger.info(`Fetched announcement channel: ${JSON.stringify(channels[0])}`) + this.announcementChannels.set(guild.id, channels[0]) + } + } + public getAnnouncementChannelForGuild(guildId: string): TextChannel { + return this.announcementChannels.get(guildId)! //we set the channel by ourselves only if we find one, I think this is sage (mark my words) + } public async cacheUsers(guilds: Collection) { guilds.forEach((guild: Guild, id: Snowflake) => { logger.info(`Fetching members for ${guild.name}|${id}`) guild.members.fetch() logger.info(`Fetched: ${guild.memberCount} members`) }) - } public async registerEventCallback() { try { -- 2.40.1 From f3669ec34fa0ce67a355e6d7ed9c22eb80491091 Mon Sep 17 00:00:00 2001 From: Sammy Date: Mon, 12 Jun 2023 20:31:52 +0200 Subject: [PATCH 10/11] move collection id of movies into configurations --- server/configuration.ts | 4 +++- server/jellyfin/handler.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/server/configuration.ts b/server/configuration.ts index adb58fc..5807c47 100644 --- a/server/configuration.ts +++ b/server/configuration.ts @@ -24,6 +24,7 @@ export interface Config { watcher_role: string jf_admin_role: string announcement_channel_id: string + jf_collection_id: string } } export const config: Config = { @@ -56,6 +57,7 @@ export const config: Config = { workaround_token: process.env.TOKEN ?? "", watcher_role: process.env.WATCHER_ROLE ?? "", jf_admin_role: process.env.ADMIN_ROLE ?? "", - announcement_channel_id: process.env.CHANNEL_ID ?? "" + announcement_channel_id: process.env.CHANNEL_ID ?? "", + jf_collection_id: process.env.JELLYFIN_COLLECTION_ID ?? "" } } diff --git a/server/jellyfin/handler.ts b/server/jellyfin/handler.ts index 4bd5c67..7b3a202 100644 --- a/server/jellyfin/handler.ts +++ b/server/jellyfin/handler.ts @@ -236,7 +236,7 @@ export class JellyfinHandler { const searchParams: GetItemsRequest = { userId: liloJfUser?.id, - parentId: "f137a2dd21bbc1b99aa5c0f6bf02a805" // collection ID for all movies + parentId: this.config.bot.jf_collection_id // collection ID for all movies } const movies = (await (this.moviesApi.getItems(searchParams))).items?.filter(item => !item.isFolder) // logger.debug(JSON.stringify(movies, null, 2), { guildId: guildId, requestId }) -- 2.40.1 From fdc0fc47b5d88821ff39a119b8b3679882dfe696 Mon Sep 17 00:00:00 2001 From: Sammy Date: Mon, 12 Jun 2023 20:36:05 +0200 Subject: [PATCH 11/11] removed unnecessary guildId: from logger calls --- server/commands/closepoll.ts | 32 +++++++++++----------- server/events/guildScheduledEventUpdate.ts | 2 +- server/jellyfin/handler.ts | 8 +++--- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/server/commands/closepoll.ts b/server/commands/closepoll.ts index 22c1a5f..1290882 100644 --- a/server/commands/closepoll.ts +++ b/server/commands/closepoll.ts @@ -15,9 +15,9 @@ export default new Command({ const command = interaction.interaction const requestId = uuid() const guildId = command.guildId! - logger.info("Got command for closing poll!", { guildId: guildId, requestId }) + logger.info("Got command for closing poll!", { guildId, requestId }) if (!command.guild) { - logger.error("No guild found in interaction. Cancelling closing request", {guildId: guildId, requestId}) + logger.error("No guild found in interaction. Cancelling closing request", { guildId, requestId }) command.followUp("Es gab leider ein Problem. Ich konnte deine Anfrage nicht bearbeiten :(") return } @@ -29,7 +29,7 @@ export default new Command({ export async function closePoll(guild: Guild, requestId: string) { const guildId = guild.id - logger.info("stopping poll", { guildId: guildId, requestId }) + logger.info("stopping poll", { guildId, requestId }) const announcementChannel: TextChannel = client.getAnnouncementChannelForGuild(guildId) @@ -39,20 +39,20 @@ export async function closePoll(guild: Guild, requestId: string) { .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 }) + logger.info("Could not find any vote messages. Cancelling pollClose", { guildId, requestId }) return } const lastMessage: Message = messages[0] - logger.debug(`Found messages: ${JSON.stringify(messages, null, 2)}`, { guildId: guildId, requestId }) + logger.debug(`Found messages: ${JSON.stringify(messages, null, 2)}`, { guildId, requestId }) - logger.debug(`Last message: ${JSON.stringify(lastMessage, null, 2)}`, { guildId: guildId, requestId }) + logger.debug(`Last message: ${JSON.stringify(lastMessage, null, 2)}`, { 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 }) + logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId, requestId }) updateEvent(votes, guild!, guildId, requestId) updateMessage(votes[0].movie, lastMessage, guildId, requestId) @@ -67,20 +67,20 @@ async function updateMessage(movie: string, message: Message, guildId: string, r const options: MessageEditOptions = { content: body, } - logger.info("Updating message.", {guildId: guildId, requestId}) + logger.info("Updating message.", { guildId, requestId }) message.edit(options) } async function updateEvent(votes: Vote[], guild: Guild, guildId: string, requestId: string) { - logger.info(`Updating event with movie ${votes[0].movie}.`, { guildId: guildId, requestId }) + logger.info(`Updating event with movie ${votes[0].movie}.`, { guildId, requestId }) const voteEvents = (await guild.scheduledEvents.fetch()) .map((value, _) => value) .filter(event => event.name.toLowerCase().includes("voting offen")) - logger.debug(`Found events: ${JSON.stringify(voteEvents, null, 2)}`, { guildId: guildId, requestId }) + logger.debug(`Found events: ${JSON.stringify(voteEvents, null, 2)}`, { guildId, requestId }) if (!voteEvents || voteEvents.length <= 0) { - logger.error("Could not find vote event. Cancelling update!", { guildId: guildId, requestId }) + logger.error("Could not find vote event. Cancelling update!", { guildId, requestId }) return } @@ -89,8 +89,8 @@ async function updateEvent(votes: Vote[], guild: Guild, guildId: string, request 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` } - logger.debug(`Updating event: ${JSON.stringify(voteEvent, null, 2)}`, { guildId: guildId, requestId }) - logger.info("Updating event.", {guildId: guildId, requestId}) + logger.debug(`Updating event: ${JSON.stringify(voteEvent, null, 2)}`, { guildId, requestId }) + logger.info("Updating event.", { guildId, requestId }) voteEvent.edit(options) } @@ -102,12 +102,12 @@ type Vote = { async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise { const votes: Vote[] = [] - logger.debug(`Number of items in emotes: ${Object.values(Emotes).length}`, {guildId: guildId, requestId}) + logger.debug(`Number of items in emotes: ${Object.values(Emotes).length}`, { guildId, requestId }) for (let i = 0; i < Object.keys(Emotes).length / 2; i++) { const emote = Emotes[i] - logger.debug(`Getting reaction for emote ${emote}`, { guildId: guildId, requestId }) + logger.debug(`Getting reaction for emote ${emote}`, { guildId, requestId }) const reaction = await message.reactions.resolve(emote) - logger.debug(`Reaction for emote ${emote}: ${JSON.stringify(reaction, null, 2)}`, { guildId: guildId, requestId }) + logger.debug(`Reaction for emote ${emote}: ${JSON.stringify(reaction, null, 2)}`, { guildId, requestId }) if (reaction) { const vote: Vote = { emote: emote, count: reaction.count, movie: extractMovieFromMessageByEmote(message, emote, guildId, requestId) } votes.push(vote) diff --git a/server/events/guildScheduledEventUpdate.ts b/server/events/guildScheduledEventUpdate.ts index d731b09..b479101 100644 --- a/server/events/guildScheduledEventUpdate.ts +++ b/server/events/guildScheduledEventUpdate.ts @@ -47,6 +47,6 @@ async function createJFUsers(members: GuildMember[], movieName: string, requestI } async function deleteJFUsers(guildId: string, requestId?: string) { - logger.info(`Watchparty ended, deleting tmp users`) + logger.info(`Watchparty ended, deleting tmp users`, { guildId, requestId }) jellyfinHandler.purge(guildId, requestId) } \ No newline at end of file diff --git a/server/jellyfin/handler.ts b/server/jellyfin/handler.ts index 7b3a202..27e26ab 100644 --- a/server/jellyfin/handler.ts +++ b/server/jellyfin/handler.ts @@ -230,7 +230,7 @@ export class JellyfinHandler { } public async getAllMovies(guildId: string, requestId: string): Promise { - logger.info("requesting all movies from jellyfin", { guildId: guildId, requestId }) + logger.info("requesting all movies from jellyfin", { guildId, requestId }) const liloJfUser = await this.getUser({ guild: { id: guildId }, displayName: "lilo" }, requestId) @@ -240,15 +240,15 @@ export class JellyfinHandler { } const movies = (await (this.moviesApi.getItems(searchParams))).items?.filter(item => !item.isFolder) // logger.debug(JSON.stringify(movies, null, 2), { guildId: guildId, requestId }) - logger.info(`Found ${movies?.length} movies in total`, { guildId: guildId, requestId }) + logger.info(`Found ${movies?.length} movies in total`, { guildId, requestId }) return movies ?? [] } public async getRandomMovies(count: number, guildId: string, requestId: string): Promise { - logger.info(`${count} random movies requested.`, { guildId: guildId, requestId }) + logger.info(`${count} random movies requested.`, { guildId, requestId }) const allMovies = await this.getAllMovies(guildId, requestId) if (count >= allMovies.length) { - logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`, { guildId: guildId, requestId }) + logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`, { guildId, requestId }) return allMovies } const movies: BaseItemDto[] = [] -- 2.40.1