feat/40-reroll-on-disinterest #54

Merged
kenobi merged 73 commits from feat/40-reroll-on-disinterest into master 2023-11-19 20:24:36 +01:00
2 changed files with 61 additions and 17 deletions
Showing only changes of commit e54f03292e - Show all commits

View File

@ -1,6 +1,5 @@
import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageCreateOptions, MessageReaction, TextChannel, User } from "discord.js"
import { client, yavinJellyfinHandler } from "../.."
import { Emotes, NONE_OF_THAT } from "../constants"
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"
@ -12,13 +11,28 @@ 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"
import { getYear } from "date-fns"
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'
@ -30,7 +44,7 @@ export default class VoteController {
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 !== client.user?.id).size ?? 0
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 })
@ -38,21 +52,21 @@ export default class VoteController {
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: string[] = this.parseMoviesFromVoteMessage(messageReaction.message,requestId)
//const oldMovieNames: Vote[] = this.parseVotesFromVoteMessage(messageReaction.message, requestId)
const eventId = this.parseEventIdFromMessage(messageReaction.message, requestId)
const eventStartDate: Date = this.fetchEventStartDateByEventId(eventId,requestId) //TODO
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 yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
const newMovieCount = config.bot.random_movie_count //- oldMovieNames.length
const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
// merge
const movies = oldMovieNames.concat(newMovies)
const movies = newMovies
// create new message
await this.closePoll(messageReaction.message.guild, requestId)
const message = this.createVoteMessageText(eventId, eventStartDate, movies, guildId, requestId)
const announcementChannel = client.getAnnouncementChannelForGuild(guildId)
const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) {
logger.error(`No announcementChannel found for ${guildId}, can't post poll`)
return
@ -65,16 +79,45 @@ export default class VoteController {
private fetchEventStartDateByEventId(eventId: string, requestId: string): Date {
throw new Error("Method not implemented.")
}
private parseMoviesFromVoteMessage(message: Message<boolean> | import("discord.js").PartialMessage, requestId: string): string[] {
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(':')) {
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) ?? ""
eventDate = new Date(dateFromResult)
} else if (line.slice(0, 5).includes(':')) {
const splitLine = line.split(":")
const [emoji, movie] = splitLine
if (emoji === NONE_OF_THAT) continue
const fetchedVoteFromMessage = message.reactions.cache.get(emoji)
if (fetchedVoteFromMessage) {
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 <VoteMessageInfo>{ eventId, eventDate, votes }
}
private parseEventIdFromMessage(message: Message<boolean> | import("discord.js").PartialMessage, requestId: string): string {
private parseEventIdFromMessage(message: Message<boolean> | PartialMessage, requestId: string): string {
throw new Error("Method not implemented.")
}
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`
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")
@ -104,7 +147,7 @@ export default class VoteController {
const guildId = guild.id
logger.info("stopping poll", { guildId, requestId })
const announcementChannel: Maybe<TextChannel> = client.getAnnouncementChannelForGuild(guildId)
const announcementChannel: Maybe<TextChannel> = this.client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) {
logger.error("Could not find the textchannel. Unable to close poll.", { guildId, requestId })
return
@ -188,7 +231,7 @@ export default class VoteController {
content: body,
allowedMentions: { parse: ["roles"] }
}
const announcementChannel = client.getAnnouncementChannelForGuild(guildId)
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 })

View File

@ -10,6 +10,7 @@ import { logger } from "../logger";
import { CommandType } from "../types/commandTypes";
import { isInitialAnnouncement } from "../helper/messageIdentifiers";
import VoteController from "../helper/vote.controller";
import { yavinJellyfinHandler } from "../..";
@ -17,7 +18,7 @@ export class ExtendedClient extends Client {
private eventFilePath = `${__dirname}/../events`
private commandFilePath = `${__dirname}/../commands`
private jellyfin: JellyfinHandler
public voteController: VoteController = new VoteController()
public voteController: VoteController = new VoteController(this, yavinJellyfinHandler)
public commands: Collection<string, CommandType> = new Collection()
private announcementChannels: Collection<string, TextChannel> = new Collection() //guildId to TextChannel
private announcementRoleHandlerTask: Collection<string, ScheduledTask> = new Collection() //one task per guild