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"
kenobi marked this conversation as resolved Outdated

Move check to handleMessageReactionAdd

Move check to handleMessageReactionAdd

moved

moved
import { ExtendedClient } from "../structures/client"
import { JellyfinHandler } from "../jellyfin/handler"
kenobi marked this conversation as resolved Outdated

duplicate check. already checked before call in handleMessageReactionAdd

duplicate check. already checked before call in handleMessageReactionAdd

removed

removed
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
magnetotail marked this conversation as resolved Outdated

Parameter die eine Message sind heißen oft "message", manchmal aber auch "msg". sollte vereinheitlicht sein

Parameter die eine Message sind heißen oft "message", manchmal aber auch "msg". sollte vereinheitlicht sein
66507cb08fa50ba3a7be28388c55b21227fb2261

fc64728a78

Jetzt sollten alle Occurences beseitigt sein.

fc64728a780f99b56aebff7f0a7c5d24a901d90d Jetzt sollten alle Occurences beseitigt sein.
const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
// merge
const movies = oldMovieNames.concat(newMovies)
const movies = newMovies
// create new message
magnetotail marked this conversation as resolved Outdated

above WHAT threshold? What does it do??

above WHAT threshold? What does it do??
20da25f2bf9a473704f8b4660e5f05183679ba39

Mit einem Kommentar versehen und entsprechend deines vorschlags umbenannt

Mit einem Kommentar versehen und entsprechend deines vorschlags umbenannt
await this.closePoll(messageReaction.message.guild, requestId)
magnetotail marked this conversation as resolved Outdated

threshold seems to be a magic number

threshold seems to be a magic number

Or rename method to "hasAtLeastOneVote"

Or rename method to "hasAtLeastOneVote"
296a490e935cbdb79b70d73d2df9bc12a5774c53

done

done
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
magnetotail marked this conversation as resolved Outdated

comment is misleading, voteinfo is also used to get the eventid and eventdate in line 93

comment is misleading, voteinfo is also used to get the eventid and eventdate in line 93
119343c916b023a926e534575ae803cdec5b9594
@ -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(':')) {
magnetotail marked this conversation as resolved Outdated

is not a message, only messagetext

is not a message, only messagetext
a455fd8ff7e6b8ffb032fb4aed9389da68ee513b

done

done
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 })
magnetotail marked this conversation as resolved Outdated

why not pin message in method above?

why not pin message in method above?

7d794a8001
should have been moved to prepareAndSendVoteMessage()

7d794a8001a66d068f949c893d689a068c3caeed should have been moved to prepareAndSendVoteMessage()
}
}
}
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)
kenobi marked this conversation as resolved Outdated

wtf :D

wtf :D

it's magic

it's magic ✨
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