Compare commits

..

No commits in common. "0d5c3d30a90676d731bfc7a56061d7c7aec50827" and "c8fa89ae63eddb932c7ffdfe0f12e7243b88494f" have entirely different histories.

5 changed files with 47 additions and 147 deletions

46
package-lock.json generated
View File

@ -12,7 +12,6 @@
"@discordjs/rest": "^1.7.0", "@discordjs/rest": "^1.7.0",
"@tsconfig/recommended": "^1.0.2", "@tsconfig/recommended": "^1.0.2",
"@types/node": "^18.15.11", "@types/node": "^18.15.11",
"@types/node-cron": "^3.0.7",
"@types/request": "^2.48.8", "@types/request": "^2.48.8",
"@types/uuid": "^9.0.1", "@types/uuid": "^9.0.1",
"axios": "^1.3.5", "axios": "^1.3.5",
@ -21,7 +20,6 @@
"discord.js": "^14.9.0", "discord.js": "^14.9.0",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"jellyfin-apiclient": "^1.10.0", "jellyfin-apiclient": "^1.10.0",
"node-cron": "^3.0.2",
"sqlite3": "^5.1.6", "sqlite3": "^5.1.6",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^5.0.4", "typescript": "^5.0.4",
@ -1587,11 +1585,6 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz",
"integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==" "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": { "node_modules/@types/prettier": {
"version": "2.7.2", "version": "2.7.2",
"resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz",
@ -5011,25 +5004,6 @@
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
"integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==" "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": { "node_modules/node-fetch": {
"version": "2.6.9", "version": "2.6.9",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz",
@ -8150,11 +8124,6 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz",
"integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==" "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": { "@types/prettier": {
"version": "2.7.2", "version": "2.7.2",
"resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz",
@ -10733,21 +10702,6 @@
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
"integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==" "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": { "node-fetch": {
"version": "2.6.9", "version": "2.6.9",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz",

View File

@ -8,7 +8,6 @@
"@discordjs/rest": "^1.7.0", "@discordjs/rest": "^1.7.0",
"@tsconfig/recommended": "^1.0.2", "@tsconfig/recommended": "^1.0.2",
"@types/node": "^18.15.11", "@types/node": "^18.15.11",
"@types/node-cron": "^3.0.7",
"@types/request": "^2.48.8", "@types/request": "^2.48.8",
"@types/uuid": "^9.0.1", "@types/uuid": "^9.0.1",
"axios": "^1.3.5", "axios": "^1.3.5",
@ -17,7 +16,6 @@
"discord.js": "^14.9.0", "discord.js": "^14.9.0",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"jellyfin-apiclient": "^1.10.0", "jellyfin-apiclient": "^1.10.0",
"node-cron": "^3.0.2",
"sqlite3": "^5.1.6", "sqlite3": "^5.1.6",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^5.0.4", "typescript": "^5.0.4",

View File

@ -1,10 +1,11 @@
import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageEditOptions, TextChannel } from 'discord.js'
import { v4 as uuid } from 'uuid'
import { config } from '../configuration'
import { Emotes } from '../events/guildScheduledEventCreate'
import { logger } from '../logger'
import { Command } from '../structures/command' import { Command } from '../structures/command'
import { RunOptions } from '../types/commandTypes' 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({ export default new Command({
name: 'closepoll', name: 'closepoll',
@ -15,34 +16,19 @@ export default new Command({
const requestId = uuid() const requestId = uuid()
const guildId = command.guildId! const guildId = command.guildId!
logger.info("Got command for closing poll!", { guildId: guildId, requestId }) 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
}
command.followUp("Alles klar, beende die Umfrage :)") const announcementChannel: TextChannel = <TextChannel>(await command.guild?.channels.fetch())
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) ?.filter(channel => channel!.id === config.bot.announcement_channel_id)
.map((value, _) => value)[0] //todo: needs to be done less sketchy .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 const messages: Message<true>[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages
.map((value, _) => value) .map((value, _) => value)
.filter(message => !message.cleanContent.includes("[Abstimmung beendet]") && message.cleanContent.includes("[Abstimmung]")) .filter(message => !message.cleanContent.includes("[Abstimmung beendet]") && message.cleanContent.includes("[Abstimmung]"))
.sort((a, b) => b.createdTimestamp - a.createdTimestamp) .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] const lastMessage: Message<true> = messages[0]
@ -55,11 +41,12 @@ export async function closePoll(guild: Guild, requestId: string) {
logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId: guildId, requestId }) logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId: guildId, requestId })
updateEvent(votes, guild!, guildId, requestId) updateEvent(votes, command.guild!, guildId, requestId)
updateMessage(votes[0].movie, lastMessage, guildId, requestId) updateMessage(votes[0].movie, lastMessage, guildId, requestId)
//lastMessage.unpin() //todo: uncomment when bot has permission to pin/unpin //lastMessage.unpin() //todo: uncomment when bot has permission to pin/unpin
} }
})
async function updateMessage(movie: string, message: Message, guildId: string, requestId: string) { async function updateMessage(movie: string, message: Message, guildId: string, requestId: string) {
const body = `[Abstimmung beendet] Gewonnen hat: ${movie}` const body = `[Abstimmung beendet] Gewonnen hat: ${movie}`
@ -68,7 +55,6 @@ async function updateMessage(movie: string, message: Message, guildId: string, r
const options: MessageEditOptions = { const options: MessageEditOptions = {
content: body, content: body,
} }
logger.info("Updating message.", {guildId: guildId, requestId})
message.edit(options) message.edit(options)
} }
@ -80,18 +66,16 @@ async function updateEvent(votes: Vote[], guild: Guild, guildId: string, request
.filter(event => event.name.toLowerCase().includes("voting offen")) .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: guildId, requestId })
if (!voteEvents || voteEvents.length <= 0) { 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: guildId, requestId })
return
} }
const voteEvent: GuildScheduledEvent<GuildScheduledEventStatus> = voteEvents[0] const voteEvent: GuildScheduledEvent<GuildScheduledEventStatus> = voteEvents[0]
const options: GuildScheduledEventEditOptions<GuildScheduledEventStatus.Scheduled, GuildScheduledEventSetStatusArg<GuildScheduledEventStatus.Scheduled>> = { const options: GuildScheduledEventEditOptions<GuildScheduledEventStatus.Scheduled, GuildScheduledEventSetStatusArg<GuildScheduledEventStatus.Scheduled>> = {
name: votes[0].movie, 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.debug(`Updating event: ${JSON.stringify(voteEvent, null, 2)}`, { guildId: guildId, requestId })
logger.info("Updating event.", {guildId: guildId, requestId})
voteEvent.edit(options) voteEvent.edit(options)
} }
@ -103,9 +87,10 @@ type Vote = {
async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise<Vote[]> { async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise<Vote[]> {
const votes: Vote[] = [] 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}`)
for (let i = 0; i < Object.keys(Emotes).length / 2; i++) { for (let i = 0; i < Object.keys(Emotes).length / 2; i++) {
const emote = Emotes[i] const emote = Emotes[i]
// for (const emote of Object.keys(Emotes)) {
logger.debug(`Getting reaction for emote ${emote}`, { guildId: guildId, requestId }) logger.debug(`Getting reaction for emote ${emote}`, { guildId: guildId, requestId })
const reaction = await message.reactions.resolve(emote) 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: guildId, requestId })

View File

@ -1,17 +1,14 @@
import { GuildScheduledEvent, Message, TextChannel } from "discord.js"; import { BaseFetchOptions, ChannelType, GuildBasedChannel, GuildChannelResolvable, GuildMember, GuildScheduledEvent, GuildScheduledEventStatus, Message, TextChannel, messageLink } from "discord.js";
import { ScheduledTask, schedule } from "node-cron";
import { v4 as uuid } from "uuid"; import { v4 as uuid } from "uuid";
import { jellyfinHandler } from "../.."; import { jellyfinHandler } from "../..";
import { closePoll } from "../commands/closepoll"; import { getGuildSpecificTriggerRoleId } from "../helper/roleFilter";
import { config } from "../configuration";
import { logger } from "../logger"; import { logger } from "../logger";
import { config } from "../configuration";
export const name = 'guildScheduledEventCreate' 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) { export async function execute(event: GuildScheduledEvent) {
const requestId = uuid() const requestId = uuid()
@ -26,8 +23,10 @@ export async function execute(event: GuildScheduledEvent) {
logger.info(`Got ${movies.length} random movies. Creating voting`, { guildId: 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 }) 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 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)}`, { guildId: event.guildId, requestId }) logger.debug(`Found channel ${JSON.stringify(channel, null, 2)}`)
let message = "[Abstimmung]\nEs 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"
@ -41,42 +40,6 @@ export async function execute(event: GuildScheduledEvent) {
sentMessage.react(Emotes[i]) 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 // 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 }) logger.info(`${count} random movies requested.`, { guildId: guildId, requestId })
const allMovies = await this.getAllMovies(guildId, requestId) const allMovies = await this.getAllMovies(guildId, requestId)
if (count >= allMovies.length) { 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.`)
return allMovies return allMovies
} }
const movies: BaseItemDto[] = [] const movies: BaseItemDto[] = []