import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageCreateOptions, MessageReaction, PartialMessage, TextChannel, User } from "discord.js" import { Emoji, Emotes, NONE_OF_THAT } from "../constants" import { logger, newRequestId } from "../logger" import { getMembersWithRoleFromGuild } from "./roleFilter" import { config } from "../configuration" import { VoteMessage, isVoteEndedMessage, isVoteMessage } from "./messageIdentifiers" import { createDateStringFromEvent } from "./dateHelper" import { Maybe } from "../interfaces" import format from "date-fns/format" import toDate from "date-fns/toDate" import differenceInDays from "date-fns/differenceInDays" import addDays from "date-fns/addDays" import isAfter from "date-fns/isAfter" import { ExtendedClient } from "../structures/client" import { JellyfinHandler } from "../jellyfin/handler" export type Vote = { emote: string, //todo habs nicht hinbekommen hier Emotes zu nutzen count: number, movie: string } export type VoteMessageInfo = { votes: Vote[], eventId: string, eventDate: Date } export default class VoteController { private client: ExtendedClient private yavinJellyfinHandler: JellyfinHandler public constructor(_client: ExtendedClient, _yavin: JellyfinHandler) { this.client = _client this.yavinJellyfinHandler = _yavin } public async handleNoneOfThatVote(messageReaction: MessageReaction, user: User, reactedUponMessage: VoteMessage, requestId: string, guildId: string) { if (!messageReaction.message.guild) return 'No guild' logger.debug(`${reactedUponMessage.id} is vote message`, { requestId, guildId }) const watcherRoleMember = await getMembersWithRoleFromGuild(config.bot.announcement_role, messageReaction.message.guild) logger.info("ROLE MEMBERS " + JSON.stringify(watcherRoleMember), { requestId, guildId }) const watcherRoleMemberCount = watcherRoleMember.size logger.info(`MEMBER COUNT: ${watcherRoleMemberCount}`, { requestId, guildId }) const noneOfThatReactions = messageReaction.message.reactions.cache.get(NONE_OF_THAT)?.users.cache.filter(x => x.id !== this.client.user?.id).size ?? 0 const memberThreshold = (watcherRoleMemberCount / 2) logger.info(`Reroll ${noneOfThatReactions} > ${memberThreshold} ?`, { requestId, guildId }) if (noneOfThatReactions > memberThreshold) { logger.info('Starting poll reroll', { requestId, guildId }) messageReaction.message.edit((messageReaction.message.content ?? "").concat('\nDiese Abstimmung muss wiederholt werden.')) // get movies that _had_ votes //const oldMovieNames: Vote[] = this.parseVotesFromVoteMessage(messageReaction.message, requestId) const eventId = this.parseEventIdFromMessage(messageReaction.message, requestId) const eventStartDate: Date = this.fetchEventStartDateByEventId(eventId, requestId) //TODO // // get movies from jellyfin to fill the remaining slots const newMovieCount = config.bot.random_movie_count //- oldMovieNames.length const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId) // merge const movies = newMovies // create new message await this.closePoll(messageReaction.message.guild, requestId) const message = this.createVoteMessageText(eventId, eventStartDate, movies, guildId, requestId) const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId) if (!announcementChannel) { logger.error(`No announcementChannel found for ${guildId}, can't post poll`) return } const sentMessage = await this.sendVoteMessage(message, movies.length, announcementChannel) sentMessage.pin() } logger.info(`No reroll`, { requestId, guildId }) } parseEventIdFromMessage(message: Message | PartialMessage, requestId: string): string { throw new Error("Method not implemented.") } private fetchEventStartDateByEventId(eventId: string, requestId: string): Date { throw new Error("Method not implemented.") } public parseVotesFromVoteMessage(message: VoteMessage, requestId: string): VoteMessageInfo { const lines = message.cleanContent.split('\n') let eventId = "" let eventDate: Date = new Date() let votes: Vote[] = [] for (const line of lines) { if (line.includes('https://discord.com/events')) { const urlMatcher = RegExp(/(http|https|ftp):\/\/(\S*)/ig) const result = line.match(urlMatcher) if (!result) throw Error('No event url found in Message') eventId = result?.[0].split('/').at(-1) ?? "" } else if (!line.slice(0, 5).includes(':')) { eventDate = this.parseEventDateFromLine(line) } else if (line.slice(0, 5).includes(':')) { const splitLine = line.split(":") const [emoji, movie] = splitLine const fetchedVoteFromMessage = message.reactions.cache.get(emoji) if (fetchedVoteFromMessage) { if (emoji === NONE_OF_THAT) { votes.push({ movie: NONE_OF_THAT, emote: NONE_OF_THAT, count: fetchedVoteFromMessage.count }) } else votes.push({ movie: movie.trim(), emote: emoji, count: fetchedVoteFromMessage.count }) } else { logger.error(`No vote reaction found for movie, assuming 0`, requestId) votes.push({ movie, emote: emoji, count: 0 }) } } } return { eventId, eventDate, votes } } public parseEventDateFromLine(line: string): Date { const datematcher = RegExp(/((0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012]))(\ um\ )(([012][0-9]:[0-5][0-9]))/i) const result: RegExpMatchArray | null = line.match(datematcher) const timeFromResult = result?.at(-1) const dateFromResult = result?.at(1)?.concat(format(new Date(), '.yyyy')).concat(" " + timeFromResult) ?? "" return new Date(dateFromResult) } public createVoteMessageText(eventId: string, eventStartDate: Date, movies: string[], guildId: string, requestId: string): string { let message = `[Abstimmung] für https://discord.com/events/${guildId}/${eventId} \n<@&${config.bot.announcement_role}> Es gibt eine neue Abstimmung für die nächste Watchparty ${createDateStringFromEvent(eventStartDate, guildId, requestId)}! 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]).concat("\n") } message = message.concat(NONE_OF_THAT).concat(": Wenn dir nichts davon gefällt.") return message } public async sendVoteMessage(message: string, movieCount: number, announcementChannel: TextChannel) { const options: MessageCreateOptions = { allowedMentions: { parse: ["roles"] }, content: message, } const sentMessage: Message = await (await announcementChannel.fetch()).send(options) for (let i = 0; i < movieCount; i++) { sentMessage.react(Emotes[i]) } sentMessage.react(NONE_OF_THAT) return sentMessage } public async closePoll(guild: Guild, requestId: string) { const guildId = guild.id logger.info("stopping poll", { guildId, requestId }) const announcementChannel: Maybe = this.client.getAnnouncementChannelForGuild(guildId) if (!announcementChannel) { logger.error("Could not find the textchannel. Unable to close poll.", { guildId, requestId }) return } const messages: Message[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages .map((value) => value) .filter(message => !isVoteEndedMessage(message) && isVoteMessage(message)) .sort((a, b) => b.createdTimestamp - a.createdTimestamp) if (!messages || messages.length <= 0) { 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, requestId }) logger.debug(`Last message: ${JSON.stringify(lastMessage, null, 2)}`, { guildId, requestId }) const votes = (await this.getVotesByEmote(lastMessage, guildId, requestId)) .sort((a, b) => b.count - a.count) logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId, requestId }) logger.info("Deleting vote message") await lastMessage.delete() const event = await this.getEvent(guild, guild.id, requestId) if (event) { this.updateEvent(event, votes, guild, guildId, requestId) this.sendVoteClosedMessage(event, votes[0].movie, guildId, requestId) } lastMessage.unpin() //todo: uncomment when bot has permission to pin/unpin } public async getVotesByEmote(message: Message, guildId: string, requestId: string): Promise { const votes: Vote[] = [] 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, requestId }) const reaction = message.reactions.resolve(emote) logger.debug(`Reaction for emote ${emote}: ${JSON.stringify(reaction, null, 2)}`, { guildId, requestId }) if (reaction) { const vote: Vote = { emote: emote, count: reaction.count, movie: this.extractMovieFromMessageByEmote(message, emote) } votes.push(vote) } } return votes } public async getEvent(guild: Guild, guildId: string, requestId: string): Promise { 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, requestId }) if (!voteEvents || voteEvents.length <= 0) { logger.error("Could not find vote event. Cancelling update!", { guildId, requestId }) return null } return voteEvents[0] } public async updateEvent(voteEvent: GuildScheduledEvent, votes: Vote[], guild: Guild, guildId: string, requestId: string) { logger.info(`Updating event with movie ${votes[0].movie}.`, { guildId, requestId }) 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, requestId }) logger.info("Updating event.", { guildId, requestId }) voteEvent.edit(options) } public async sendVoteClosedMessage(event: GuildScheduledEvent, movie: string, guildId: string, requestId: string) { const date = event.scheduledStartAt ? format(event.scheduledStartAt, "dd.MM") : "Fehler, event hatte kein Datum" const time = event.scheduledStartAt ? format(event.scheduledStartAt, "HH:mm") : "Fehler, event hatte kein Datum" const body = `[Abstimmung beendet] für https://discord.com/events/${event.guildId}/${event.id}\n<@&${config.bot.announcement_role}> Wir gucken ${movie} am ${date} um ${time}` const options: MessageCreateOptions = { content: body, allowedMentions: { parse: ["roles"] } } const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId) logger.info("Sending vote closed message.", { guildId, requestId }) if (!announcementChannel) { logger.error("Could not find announcement channel. Please fix!", { guildId, requestId }) return } announcementChannel.send(options) } private extractMovieFromMessageByEmote(message: Message, emote: 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 } public async checkForPollsToClose(guild: Guild): Promise { const requestId = newRequestId() logger.info(`Automatic check for poll closing.`, { guildId: guild.id, requestId }) const events = (await guild.scheduledEvents.fetch()).filter(event => event.name.toLocaleLowerCase().includes("voting offen")).map(event => event) if (events.length > 1) { logger.error("Handling more than one Event is not implemented yet. Found more than one poll to close") return } else if (events.length == 0) { logger.info("Could not find any events. Cancelling", { guildId: guild.id, requestId }) } 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: guild.id, requestId }) return } const createDate: Date = toDate(updatedEvent.createdTimestamp) const eventDate: Date = toDate(updatedEvent.scheduledStartTimestamp) const difference: number = differenceInDays(createDate, eventDate) if (difference <= 2) { logger.info("Less than two days between event create and event start. Not closing poll.", { guildId: guild.id, requestId }) return } const closePollDate: Date = addDays(eventDate, -2) if (isAfter(Date.now(), closePollDate)) { logger.info("Less than two days until event. Closing poll", { guildId: guild.id, requestId }) this.closePoll(guild, requestId) } else { logger.info(`ScheduledStart: ${closePollDate}. Now: ${toDate(Date.now())}`, { guildId: guild.id, requestId }) } } }