Compare commits

...

5 Commits

Author SHA1 Message Date
e54f03292e add a message parser to vote controller
All checks were successful
Compile the repository / compile (pull_request) Successful in 1m33s
Run unit tests / test (pull_request) Successful in 1m27s
parses a vote message line by line to extract
- eventdate
- eventid
- movies
- votes
This depends on the structure of the message to not change substantially.
as such it's quite brittle
2023-07-13 22:47:28 +02:00
fe45445811 add a test case to check for proper message parsing 2023-07-13 22:46:28 +02:00
8f02e11dba add ticket to emoji list 2023-07-13 22:46:14 +02:00
878c81bfa7 linting 2023-07-13 22:46:03 +02:00
ca19168cf4 add early abort message to announce watch party 2023-07-13 22:45:28 +02:00
6 changed files with 128 additions and 26 deletions

View File

@ -11,5 +11,6 @@ export const Emoji = {
"seven": "\u0037\uFE0F\u20E3", "seven": "\u0037\uFE0F\u20E3",
"eight": "\u0038\uFE0F\u20E3", "eight": "\u0038\uFE0F\u20E3",
"nine": "\u0039\uFE0F\u20E3", "nine": "\u0039\uFE0F\u20E3",
"ten": "\uD83D\uDD1F" "ten": "\uD83D\uDD1F",
"ticket": "🎫"
} }

View File

@ -32,7 +32,11 @@ export async function execute(event: GuildScheduledEvent) {
return return
} }
const message = `[Watchparty] https://discord.com/events/${event.guildId}/${event.id} \nHey <@&${config.bot.announcement_role}>, wir gucken ${event.name} ${createDateStringFromEvent(event, guildId, requestId)}` if (!event.scheduledStartAt) {
logger.error('Event has no start date, bailing out')
return
}
const message = `[Watchparty] https://discord.com/events/${event.guildId}/${event.id} \nHey <@&${config.bot.announcement_role}>, wir gucken ${event.name} ${createDateStringFromEvent(event.scheduledStartAt, guildId, requestId)}`
channel.send(message) channel.send(message)
} else { } else {

View File

@ -1,6 +1,5 @@
import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageCreateOptions, MessageReaction, TextChannel, User } from "discord.js" import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageCreateOptions, MessageReaction, PartialMessage, TextChannel, User } from "discord.js"
import { client, yavinJellyfinHandler } from "../.." import { Emoji, Emotes, NONE_OF_THAT } from "../constants"
import { Emotes, NONE_OF_THAT } from "../constants"
import { logger, newRequestId } from "../logger" import { logger, newRequestId } from "../logger"
import { getMembersWithRoleFromGuild } from "./roleFilter" import { getMembersWithRoleFromGuild } from "./roleFilter"
import { config } from "../configuration" import { config } from "../configuration"
@ -12,13 +11,28 @@ import toDate from "date-fns/toDate"
import differenceInDays from "date-fns/differenceInDays" import differenceInDays from "date-fns/differenceInDays"
import addDays from "date-fns/addDays" import addDays from "date-fns/addDays"
import isAfter from "date-fns/isAfter" import isAfter from "date-fns/isAfter"
import { ExtendedClient } from "../structures/client"
import { JellyfinHandler } from "../jellyfin/handler"
import { getYear } from "date-fns"
export type Vote = { export type Vote = {
emote: string, //todo habs nicht hinbekommen hier Emotes zu nutzen emote: string, //todo habs nicht hinbekommen hier Emotes zu nutzen
count: number, count: number,
movie: string movie: string
} }
export type VoteMessageInfo = {
votes: Vote[],
eventId: string,
eventDate: Date
}
export default class VoteController { 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) { public async handleNoneOfThatVote(messageReaction: MessageReaction, user: User, reactedUponMessage: VoteMessage, requestId: string, guildId: string) {
if (!messageReaction.message.guild) return 'No guild' if (!messageReaction.message.guild) return 'No guild'
@ -30,7 +44,7 @@ export default class VoteController {
const watcherRoleMemberCount = watcherRoleMember.size const watcherRoleMemberCount = watcherRoleMember.size
logger.info(`MEMBER COUNT: ${watcherRoleMemberCount}`, { requestId, guildId }) 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) const memberThreshold = (watcherRoleMemberCount / 2)
logger.info(`Reroll ${noneOfThatReactions} > ${memberThreshold} ?`, { requestId, guildId }) logger.info(`Reroll ${noneOfThatReactions} > ${memberThreshold} ?`, { requestId, guildId })
@ -38,21 +52,21 @@ export default class VoteController {
logger.info('Starting poll reroll', { requestId, guildId }) logger.info('Starting poll reroll', { requestId, guildId })
messageReaction.message.edit((messageReaction.message.content ?? "").concat('\nDiese Abstimmung muss wiederholt werden.')) messageReaction.message.edit((messageReaction.message.content ?? "").concat('\nDiese Abstimmung muss wiederholt werden.'))
// get movies that _had_ votes // 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 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 // get movies from jellyfin to fill the remaining slots
const newMovieCount = config.bot.random_movie_count - oldMovieNames.length const newMovieCount = config.bot.random_movie_count //- oldMovieNames.length
const newMovies = await yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId) const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
// merge // merge
const movies = oldMovieNames.concat(newMovies) const movies = newMovies
// create new message // create new message
await this.closePoll(messageReaction.message.guild, requestId) await this.closePoll(messageReaction.message.guild, requestId)
const message = this.createVoteMessageText(eventId, eventStartDate, movies, guildId, requestId) const message = this.createVoteMessageText(eventId, eventStartDate, movies, guildId, requestId)
const announcementChannel = client.getAnnouncementChannelForGuild(guildId) const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) { if (!announcementChannel) {
logger.error(`No announcementChannel found for ${guildId}, can't post poll`) logger.error(`No announcementChannel found for ${guildId}, can't post poll`)
return return
@ -65,16 +79,45 @@ export default class VoteController {
private fetchEventStartDateByEventId(eventId: string, requestId: string): Date { private fetchEventStartDateByEventId(eventId: string, requestId: string): Date {
throw new Error("Method not implemented.") throw new Error("Method not implemented.")
} }
private parseMoviesFromVoteMessage(message: Message<boolean> | import("discord.js").PartialMessage, requestId: string): string[] { public parseVotesFromVoteMessage(message: VoteMessage, requestId: string): VoteMessageInfo {
throw new Error("Method not implemented.") 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 })
} }
private parseEventIdFromMessage(message: Message<boolean> | import("discord.js").PartialMessage, requestId: string): string { }
}
return <VoteMessageInfo>{ eventId, eventDate, votes }
}
private parseEventIdFromMessage(message: Message<boolean> | PartialMessage, requestId: string): string {
throw new Error("Method not implemented.") throw new Error("Method not implemented.")
} }
public createVoteMessageText(eventId: string, eventStartDate: Date, movies: string[], guildId: string, requestId: string): string { 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++) { for (let i = 0; i < movies.length; i++) {
message = message.concat(Emotes[i]).concat(": ").concat(movies[i]).concat("\n") message = message.concat(Emotes[i]).concat(": ").concat(movies[i]).concat("\n")
@ -104,7 +147,7 @@ export default class VoteController {
const guildId = guild.id const guildId = guild.id
logger.info("stopping poll", { guildId, requestId }) logger.info("stopping poll", { guildId, requestId })
const announcementChannel: Maybe<TextChannel> = client.getAnnouncementChannelForGuild(guildId) const announcementChannel: Maybe<TextChannel> = this.client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) { if (!announcementChannel) {
logger.error("Could not find the textchannel. Unable to close poll.", { guildId, requestId }) logger.error("Could not find the textchannel. Unable to close poll.", { guildId, requestId })
return return
@ -188,7 +231,7 @@ export default class VoteController {
content: body, content: body,
allowedMentions: { parse: ["roles"] } allowedMentions: { parse: ["roles"] }
} }
const announcementChannel = client.getAnnouncementChannelForGuild(guildId) const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId)
logger.info("Sending vote closed message.", { guildId, requestId }) logger.info("Sending vote closed message.", { guildId, requestId })
if (!announcementChannel) { if (!announcementChannel) {
logger.error("Could not find announcement channel. Please fix!", { guildId, requestId }) 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 { CommandType } from "../types/commandTypes";
import { isInitialAnnouncement } from "../helper/messageIdentifiers"; import { isInitialAnnouncement } from "../helper/messageIdentifiers";
import VoteController from "../helper/vote.controller"; import VoteController from "../helper/vote.controller";
import { yavinJellyfinHandler } from "../..";
@ -17,7 +18,7 @@ export class ExtendedClient extends Client {
private eventFilePath = `${__dirname}/../events` private eventFilePath = `${__dirname}/../events`
private commandFilePath = `${__dirname}/../commands` private commandFilePath = `${__dirname}/../commands`
private jellyfin: JellyfinHandler private jellyfin: JellyfinHandler
public voteController: VoteController = new VoteController() public voteController: VoteController = new VoteController(this, yavinJellyfinHandler)
public commands: Collection<string, CommandType> = new Collection() public commands: Collection<string, CommandType> = new Collection()
private announcementChannels: Collection<string, TextChannel> = new Collection() //guildId to TextChannel private announcementChannels: Collection<string, TextChannel> = new Collection() //guildId to TextChannel
private announcementRoleHandlerTask: Collection<string, ScheduledTask> = new Collection() //one task per guild private announcementRoleHandlerTask: Collection<string, ScheduledTask> = new Collection() //one task per guild

View File

@ -0,0 +1,54 @@
import { Emoji } from "../../server/constants"
import VoteController, { Vote, VoteMessageInfo } from "../../server/helper/vote.controller"
import { JellyfinHandler } from "../../server/jellyfin/handler"
import { ExtendedClient } from "../../server/structures/client"
import { VoteMessage } from "../../server/helper/messageIdentifiers"
test('parse votes from vote message', () => {
const testMovies = [
'Movie1',
'Movie2',
'Movie3',
'Movie4',
'Movie5'
]
const testEventId = '1234321'
const testEventDate = new Date('2023-01-01')
const voteController: VoteController = new VoteController(<ExtendedClient>{}, <JellyfinHandler>{})
const testMessage = voteController.createVoteMessageText(testEventId, testEventDate, testMovies, "guildid", "requestId")
const expectedResult: VoteMessageInfo = {
eventId: testEventId,
eventDate: testEventDate,
votes: [
{ emote: Emoji.one, count: 1, movie: testMovies[0] },
{ emote: Emoji.two, count: 2, movie: testMovies[1] },
{ emote: Emoji.three, count: 3, movie: testMovies[2] },
{ emote: Emoji.four, count: 1, movie: testMovies[3] },
{ emote: Emoji.five, count: 1, movie: testMovies[4] },
]
}
const msg: VoteMessage = <VoteMessage><unknown>{
cleanContent: testMessage,
reactions: {
cache: {
get: jest.fn().mockImplementation((input: any) => {
// Abusing duck typing
// Message Reaction has a method `count` and the expected votes
// have a field `count`
// this will evaluate to the same 'result'
return expectedResult.votes.find(e => e.emote === input)
})
}
}
}
const result = voteController.parseVotesFromVoteMessage(msg, 'requestId')
console.log(JSON.stringify(result))
expect(Array.isArray(result)).toBe(false)
expect(result.eventId).toEqual(testEventId)
expect(result.eventDate).toEqual(testEventDate)
expect(result.votes.length).toEqual(testMovies.length)
expect(result).toEqual(expectedResult)
})

View File

@ -1,4 +1,3 @@
import { GuildScheduledEvent } from "discord.js"
import { createDateStringFromEvent } from "../../server/helper/dateHelper" import { createDateStringFromEvent } from "../../server/helper/dateHelper"
import MockDate from 'mockdate' import MockDate from 'mockdate'
@ -6,8 +5,8 @@ beforeAll(() => {
MockDate.set('01-01-2023') MockDate.set('01-01-2023')
}) })
function getTestDate(date: string): GuildScheduledEvent { function getTestDate(date: string): Date {
return <GuildScheduledEvent>{ scheduledStartAt: new Date(date) } return new Date(date)
} }
test('createDateStringFromEvent - correct formatting', () => { test('createDateStringFromEvent - correct formatting', () => {
expect(createDateStringFromEvent(getTestDate('01-01-2023 12:30'), "")).toEqual('heute um 12:30') expect(createDateStringFromEvent(getTestDate('01-01-2023 12:30'), "")).toEqual('heute um 12:30')