Compare commits

..

No commits in common. "a2adef808f26382c8980d777bcba30bb5334317a" and "c022cc32d5de3f2bb695f7dad3a19d6347fbc9b8" have entirely different histories.

3 changed files with 42 additions and 67 deletions

View File

@ -34,7 +34,7 @@ export async function execute(messageReaction: MessageReaction, user: User) {
if (isVoteMessage(reactedUponMessage)) { if (isVoteMessage(reactedUponMessage)) {
if (messageReaction.emoji.toString() === NONE_OF_THAT) { if (messageReaction.emoji.toString() === NONE_OF_THAT) {
logger.info(`Reaction is NONE_OF_THAT on a vote message. Handling`, { requestId, guildId }) logger.info(`Reaction is NONE_OF_THAT on a vote message. Handling`, { requestId, guildId })
return client.voteController.handleNoneOfThatVote(messageReaction, reactedUponMessage, requestId, guildId) return client.voteController.handleNoneOfThatVote(messageReaction, user, reactedUponMessage, requestId, guildId)
} }
if (messageReaction.emoji.toString() === Emoji.one) { if (messageReaction.emoji.toString() === Emoji.one) {
// do something // do something

View File

@ -34,9 +34,8 @@ export default class VoteController {
this.yavinJellyfinHandler = _yavin this.yavinJellyfinHandler = _yavin
} }
public async handleNoneOfThatVote(messageReaction: MessageReaction, 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'
const guild = messageReaction.message.guild
logger.debug(`${reactedUponMessage.id} is vote message`, { requestId, guildId }) logger.debug(`${reactedUponMessage.id} is vote message`, { requestId, guildId })
const watcherRoleMember = await getMembersWithRoleFromGuild(config.bot.announcement_role, messageReaction.message.guild) const watcherRoleMember = await getMembersWithRoleFromGuild(config.bot.announcement_role, messageReaction.message.guild)
@ -45,31 +44,28 @@ 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 = reactedUponMessage.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 !== 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 })
if (noneOfThatReactions > memberThreshold) if (noneOfThatReactions > memberThreshold) {
logger.info(`No reroll`, { requestId, guildId })
else
logger.info('Starting poll reroll', { requestId, guildId }) logger.info('Starting poll reroll', { requestId, guildId })
await this.handleReroll(reactedUponMessage, guild, guild.id, requestId) messageReaction.message.edit((messageReaction.message.content ?? "").concat('\nDiese Abstimmung muss wiederholt werden.'))
} // get movies that _had_ votes
public async handleReroll(voteMessage: VoteMessage, guild: Guild, guildId: string, requestId: string) { //const oldMovieNames: Vote[] = this.parseVotesFromVoteMessage(messageReaction.message, requestId)
const parsedIds = this.parseGuildIdAndEventIdFromWholeMessage(messageReaction.message.cleanContent ?? '')
//get movies that already had votes to give them a second chance const eventStartDate: Date = this.fetchEventStartDateByEventId(parsedIds.eventId, requestId) //TODO
const voteInfo = await this.parseVoteInfoFromVoteMessage(voteMessage, requestId) //
// 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 - voteInfo.votes.filter(x => x.count > 2).length const newMovieCount = config.bot.random_movie_count //- oldMovieNames.length
const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId) const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
// merge // merge
const movies = newMovies.concat(voteInfo.votes.map(x => x.movie)) const movies = newMovies
// create new message // create new message
await this.closePoll(guild, requestId) await this.closePoll(messageReaction.message.guild, requestId)
const message = this.createVoteMessageText(guild.id, voteInfo.eventDate, movies, guildId, requestId) const message = this.createVoteMessageText(parsedIds.guildId, eventStartDate, movies, guildId, requestId)
const announcementChannel = this.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`)
@ -78,25 +74,22 @@ export default class VoteController {
const sentMessage = await this.sendVoteMessage(message, movies.length, announcementChannel) const sentMessage = await this.sendVoteMessage(message, movies.length, announcementChannel)
sentMessage.pin() sentMessage.pin()
} }
logger.info(`No reroll`, { requestId, guildId })
private async fetchEventStartDateByEventId(guild: Guild, eventId: string, requestId: string): Promise<Maybe<Date>> {
const guildEvent: GuildScheduledEvent = await guild.scheduledEvents.fetch(eventId)
if (!guildEvent) logger.error(`GuildScheduledEvent with id${eventId} could not be found`, { requestId, guildId: guild.id })
if (guildEvent.scheduledStartAt)
return guildEvent.scheduledStartAt
} }
private fetchEventStartDateByEventId(eventId: string, requestId: string): Date {
public async parseVoteInfoFromVoteMessage(message: VoteMessage, requestId: string): Promise<VoteMessageInfo> { throw new Error("Method not implemented.")
}
public parseGuildIdAndEventIdFromWholeMessage(message: string) {
const idmatch = RegExp(/(?:http|https):\/\/discord\.com\/events\/(\d*)\/(\d*)/)
const matches = message.match(idmatch)
if (matches && matches.length == 3)
return { guildId: matches[1], eventId: matches[2] }
throw Error(`Could not find eventId in Vote Message`)
}
public parseVotesFromVoteMessage(message: VoteMessage, requestId: string): VoteMessageInfo {
const lines = message.cleanContent.split('\n') const lines = message.cleanContent.split('\n')
let parsedIds = this.parseGuildIdAndEventIdFromWholeMessage(message.cleanContent) let parsedIds = this.parseGuildIdAndEventIdFromWholeMessage(message.cleanContent)
let eventDate: Date = this.parseEventDateFromMessage(message.cleanContent)
if (!message.guild)
throw new Error(`Message ${message.id} not a guild message`)
let eventStartDate: Maybe<Date> = await this.fetchEventStartDateByEventId(message.guild, parsedIds.eventId, requestId)
if (!eventStartDate) eventStartDate = this.parseEventDateFromMessage(message.cleanContent, message.guild.id, requestId)
let votes: Vote[] = [] let votes: Vote[] = []
for (const line of lines) { for (const line of lines) {
if (line.slice(0, 5).includes(':')) { if (line.slice(0, 5).includes(':')) {
@ -114,25 +107,18 @@ export default class VoteController {
} }
} }
} }
return <VoteMessageInfo>{ eventId: parsedIds.eventId, eventDate: eventStartDate, votes } return <VoteMessageInfo>{ eventId: parsedIds.eventId, eventDate, votes }
} }
public parseEventDateFromMessage(message: string, guildId: string, requestId: string): Date { public parseEventDateFromMessage(message: string): Date {
logger.warn(`Falling back to RegEx parsing to get Event Date`, { guildId, requestId })
const datematcher = RegExp(/((?:0[1-9]|[12][0-9]|3[01])\.(?:0[1-9]|1[012])\.)(?:\ um\ )((?:(?:[01][0-9]|[2][0-3])\:[0-5][0-9])|(?:[2][4]\:00))!/i) const datematcher = RegExp(/((?:0[1-9]|[12][0-9]|3[01])\.(?:0[1-9]|1[012])\.)(?:\ um\ )((?:(?:[01][0-9]|[2][0-3])\:[0-5][0-9])|(?:[2][4]\:00))!/i)
const result: RegExpMatchArray | null = message.match(datematcher) const result: RegExpMatchArray | null = message.match(datematcher)
const timeFromResult = result?.at(-1) const timeFromResult = result?.at(-1)
const dateFromResult = result?.at(1)?.concat(format(new Date(), 'yyyy')).concat(" " + timeFromResult) ?? "" const dateFromResult = result?.at(1)?.concat(format(new Date(), 'yyyy')).concat(" " + timeFromResult) ?? ""
return new Date(dateFromResult) return new Date(dateFromResult)
} }
public parseGuildIdAndEventIdFromWholeMessage(message: string) {
const idmatch = RegExp(/(?:http|https):\/\/discord\.com\/events\/(\d*)\/(\d*)/)
const matches = message.match(idmatch)
if (matches && matches.length == 3)
return { guildId: matches[1], eventId: matches[2] }
throw Error(`Could not find eventId in Vote Message`)
}
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++) {

View File

@ -3,7 +3,7 @@ import VoteController, { Vote, VoteMessageInfo } from "../../server/helper/vote.
import { JellyfinHandler } from "../../server/jellyfin/handler" import { JellyfinHandler } from "../../server/jellyfin/handler"
import { ExtendedClient } from "../../server/structures/client" import { ExtendedClient } from "../../server/structures/client"
import { VoteMessage } from "../../server/helper/messageIdentifiers" import { VoteMessage } from "../../server/helper/messageIdentifiers"
test('parse votes from vote message', async () => { test('parse votes from vote message', () => {
const testMovies = [ const testMovies = [
'Movie1', 'Movie1',
'Movie2', 'Movie2',
@ -33,17 +33,6 @@ test('parse votes from vote message', async () => {
const msg: VoteMessage = <VoteMessage><unknown>{ const msg: VoteMessage = <VoteMessage><unknown>{
cleanContent: testMessage, cleanContent: testMessage,
guild:{
id:testGuildId,
scheduledEvents:{
fetch: jest.fn().mockImplementation((input:any)=>{
if(input === testEventId)
return {
scheduledStartAt: testEventDate
}
})
}
},
reactions: { reactions: {
cache: { cache: {
get: jest.fn().mockImplementation((input: any) => { get: jest.fn().mockImplementation((input: any) => {
@ -57,7 +46,7 @@ test('parse votes from vote message', async () => {
} }
} }
const result = await voteController.parseVoteInfoFromVoteMessage(msg, 'requestId') const result = voteController.parseVotesFromVoteMessage(msg, 'requestId')
console.log(JSON.stringify(result)) console.log(JSON.stringify(result))
expect(Array.isArray(result)).toBe(false) expect(Array.isArray(result)).toBe(false)
expect(result.eventId).toEqual(testEventId) expect(result.eventId).toEqual(testEventId)