Compare commits

..

No commits in common. "e54f03292e467b4ab59da9c6b5465a2e5aaf14be" and "e8893646f0e354c52e5e599838c037696f1e4867" have entirely different histories.

6 changed files with 26 additions and 128 deletions

View File

@ -11,6 +11,5 @@ 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,11 +32,7 @@ export async function execute(event: GuildScheduledEvent) {
return return
} }
if (!event.scheduledStartAt) { const message = `[Watchparty] https://discord.com/events/${event.guildId}/${event.id} \nHey <@&${config.bot.announcement_role}>, wir gucken ${event.name} ${createDateStringFromEvent(event, guildId, requestId)}`
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,5 +1,6 @@
import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageCreateOptions, MessageReaction, PartialMessage, TextChannel, User } from "discord.js" import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageCreateOptions, MessageReaction, TextChannel, User } from "discord.js"
import { Emoji, Emotes, NONE_OF_THAT } from "../constants" import { client, yavinJellyfinHandler } from "../.."
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"
@ -11,28 +12,13 @@ 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'
@ -44,7 +30,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 !== this.client.user?.id).size ?? 0 const noneOfThatReactions = messageReaction.message.reactions.cache.get(NONE_OF_THAT)?.users.cache.filter(x => x.id !== 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 })
@ -52,21 +38,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: Vote[] = this.parseVotesFromVoteMessage(messageReaction.message, requestId) const oldMovieNames: string[] = this.parseMoviesFromVoteMessage(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 this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId) const newMovies = await yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
// merge // merge
const movies = newMovies const movies = oldMovieNames.concat(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 = this.client.getAnnouncementChannelForGuild(guildId) const announcementChannel = 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
@ -79,45 +65,16 @@ 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.")
} }
public parseVotesFromVoteMessage(message: VoteMessage, requestId: string): VoteMessageInfo { private parseMoviesFromVoteMessage(message: Message<boolean> | import("discord.js").PartialMessage, requestId: string): string[] {
const lines = message.cleanContent.split('\n') throw new Error("Method not implemented.")
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")
@ -147,7 +104,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> = this.client.getAnnouncementChannelForGuild(guildId) const announcementChannel: Maybe<TextChannel> = 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
@ -231,7 +188,7 @@ export default class VoteController {
content: body, content: body,
allowedMentions: { parse: ["roles"] } allowedMentions: { parse: ["roles"] }
} }
const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId) const announcementChannel = 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,7 +10,6 @@ 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 "../..";
@ -18,7 +17,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(this, yavinJellyfinHandler) public voteController: VoteController = new VoteController()
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

@ -1,54 +0,0 @@
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,3 +1,4 @@
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'
@ -5,8 +6,8 @@ beforeAll(() => {
MockDate.set('01-01-2023') MockDate.set('01-01-2023')
}) })
function getTestDate(date: string): Date { function getTestDate(date: string): GuildScheduledEvent {
return new Date(date) return <GuildScheduledEvent>{ scheduledStartAt: 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')