Compare commits
5 Commits
e8893646f0
...
e54f03292e
Author | SHA1 | Date | |
---|---|---|---|
e54f03292e | |||
fe45445811 | |||
8f02e11dba | |||
878c81bfa7 | |||
ca19168cf4 |
@ -11,5 +11,6 @@ export const Emoji = {
|
||||
"seven": "\u0037\uFE0F\u20E3",
|
||||
"eight": "\u0038\uFE0F\u20E3",
|
||||
"nine": "\u0039\uFE0F\u20E3",
|
||||
"ten": "\uD83D\uDD1F"
|
||||
"ten": "\uD83D\uDD1F",
|
||||
"ticket": "🎫"
|
||||
}
|
||||
|
@ -32,7 +32,11 @@ export async function execute(event: GuildScheduledEvent) {
|
||||
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)
|
||||
} else {
|
||||
|
@ -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 })
|
||||
}
|
||||
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.")
|
||||
}
|
||||
|
||||
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 })
|
||||
|
@ -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
|
||||
|
54
tests/discord/votes.test.ts
Normal file
54
tests/discord/votes.test.ts
Normal 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)
|
||||
})
|
@ -1,4 +1,3 @@
|
||||
import { GuildScheduledEvent } from "discord.js"
|
||||
import { createDateStringFromEvent } from "../../server/helper/dateHelper"
|
||||
import MockDate from 'mockdate'
|
||||
|
||||
@ -6,8 +5,8 @@ beforeAll(() => {
|
||||
MockDate.set('01-01-2023')
|
||||
})
|
||||
|
||||
function getTestDate(date: string): GuildScheduledEvent {
|
||||
return <GuildScheduledEvent>{ scheduledStartAt: new Date(date) }
|
||||
function getTestDate(date: string): Date {
|
||||
return new Date(date)
|
||||
}
|
||||
test('createDateStringFromEvent - correct formatting', () => {
|
||||
expect(createDateStringFromEvent(getTestDate('01-01-2023 12:30'), "")).toEqual('heute um 12:30')
|
||||
|
Loading…
Reference in New Issue
Block a user