Compare commits

...

2 Commits

Author SHA1 Message Date
0d5c3d30a9 Fix loggers
Some logger messages were missing requestId and guildId
2023-06-10 22:58:00 +02:00
c2d8838cf8 polls will be closed automatically 2 days before event start 2023-06-10 22:53:11 +02:00
5 changed files with 146 additions and 46 deletions

46
package-lock.json generated
View File

@ -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",

View File

@ -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",

View File

@ -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", {guildId: guildId, requestId})
command.followUp("Es gab leider ein Problem. Ich konnte deine Anfrage nicht bearbeiten :(")
return
}
const announcementChannel: TextChannel = <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<true>[] = (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<true> = 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 = <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<true>[] = (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<true> = 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))
@ -55,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)
}
@ -65,17 +79,19 @@ 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<GuildScheduledEventStatus> = voteEvents[0]
const options: GuildScheduledEventEditOptions<GuildScheduledEventStatus.Scheduled, GuildScheduledEventSetStatusArg<GuildScheduledEventStatus.Scheduled>> = {
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 })
logger.info("Updating event.", {guildId: guildId, requestId})
voteEvent.edit(options)
}
@ -87,10 +103,9 @@ type Vote = {
async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise<Vote[]> {
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]
// 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 })

View File

@ -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,10 +26,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 = <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"
@ -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<void> {
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 })
}
}

View File

@ -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[] = []