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 (messageReaction.emoji.toString() === NONE_OF_THAT) {
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) {
// do something

View File

@ -34,9 +34,8 @@ export default class VoteController {
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'
const guild = messageReaction.message.guild
logger.debug(`${reactedUponMessage.id} is vote message`, { requestId, guildId })
const watcherRoleMember = await getMembersWithRoleFromGuild(config.bot.announcement_role, messageReaction.message.guild)
@ -45,58 +44,52 @@ export default class VoteController {
const watcherRoleMemberCount = watcherRoleMember.size
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)
logger.info(`Reroll ${noneOfThatReactions} > ${memberThreshold} ?`, { requestId, guildId })
if (noneOfThatReactions > memberThreshold)
logger.info(`No reroll`, { requestId, guildId })
else
if (noneOfThatReactions > memberThreshold) {
logger.info('Starting poll reroll', { requestId, guildId })
await this.handleReroll(reactedUponMessage, guild, guild.id, requestId)
}
public async handleReroll(voteMessage: VoteMessage, guild: Guild, guildId: string, requestId: string) {
messageReaction.message.edit((messageReaction.message.content ?? "").concat('\nDiese Abstimmung muss wiederholt werden.'))
// get movies that _had_ votes
//const oldMovieNames: Vote[] = this.parseVotesFromVoteMessage(messageReaction.message, requestId)
const parsedIds = this.parseGuildIdAndEventIdFromWholeMessage(messageReaction.message.cleanContent ?? '')
const eventStartDate: Date = this.fetchEventStartDateByEventId(parsedIds.eventId, requestId) //TODO
//
// get movies from jellyfin to fill the remaining slots
const newMovieCount = config.bot.random_movie_count //- oldMovieNames.length
const newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
//get movies that already had votes to give them a second chance
const voteInfo = await this.parseVoteInfoFromVoteMessage(voteMessage, requestId)
// merge
const movies = newMovies
// 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 newMovies = await this.yavinJellyfinHandler.getRandomMovieNames(newMovieCount, guildId, requestId)
// merge
const movies = newMovies.concat(voteInfo.votes.map(x => x.movie))
// create new message
await this.closePoll(guild, requestId)
const message = this.createVoteMessageText(guild.id, voteInfo.eventDate, movies, guildId, requestId)
const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) {
logger.error(`No announcementChannel found for ${guildId}, can't post poll`)
return
// create new message
await this.closePoll(messageReaction.message.guild, requestId)
const message = this.createVoteMessageText(parsedIds.guildId, eventStartDate, movies, guildId, requestId)
const announcementChannel = this.client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) {
logger.error(`No announcementChannel found for ${guildId}, can't post poll`)
return
}
const sentMessage = await this.sendVoteMessage(message, movies.length, announcementChannel)
sentMessage.pin()
}
const sentMessage = await this.sendVoteMessage(message, movies.length, announcementChannel)
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 {
throw new Error("Method not implemented.")
}
public async parseVoteInfoFromVoteMessage(message: VoteMessage, requestId: string): Promise<VoteMessageInfo> {
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')
let parsedIds = this.parseGuildIdAndEventIdFromWholeMessage(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 eventDate: Date = this.parseEventDateFromMessage(message.cleanContent)
let votes: Vote[] = []
for (const line of lines) {
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 {
logger.warn(`Falling back to RegEx parsing to get Event Date`, { guildId, requestId })
public parseEventDateFromMessage(message: string): Date {
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 timeFromResult = result?.at(-1)
const dateFromResult = result?.at(1)?.concat(format(new Date(), 'yyyy')).concat(" " + timeFromResult) ?? ""
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 {
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++) {

View File

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