Merge pull request 'Add automatic creation of vote message with random movies' (#16) from feat/voting into master
Reviewed-on: #16
This commit is contained in:
commit
acc38fdcb0
46
package-lock.json
generated
46
package-lock.json
generated
@ -12,6 +12,7 @@
|
||||
"@discordjs/rest": "^1.7.0",
|
||||
"@tsconfig/recommended": "^1.0.2",
|
||||
"@types/node": "^18.15.11",
|
||||
"@types/node-cron": "^3.0.7",
|
||||
"@types/request": "^2.48.8",
|
||||
"@types/uuid": "^9.0.1",
|
||||
"axios": "^1.3.5",
|
||||
@ -20,6 +21,7 @@
|
||||
"discord.js": "^14.9.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"jellyfin-apiclient": "^1.10.0",
|
||||
"node-cron": "^3.0.2",
|
||||
"sqlite3": "^5.1.6",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^5.0.4",
|
||||
@ -1585,6 +1587,11 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz",
|
||||
"integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q=="
|
||||
},
|
||||
"node_modules/@types/node-cron": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.7.tgz",
|
||||
"integrity": "sha512-9PuLtBboc/+JJ7FshmJWv769gDonTpItN0Ol5TMwclpSQNjVyB2SRxSKBcTtbSysSL5R7Oea06kTTFNciCoYwA=="
|
||||
},
|
||||
"node_modules/@types/prettier": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz",
|
||||
@ -5004,6 +5011,25 @@
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
|
||||
"integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ=="
|
||||
},
|
||||
"node_modules/node-cron": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz",
|
||||
"integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==",
|
||||
"dependencies": {
|
||||
"uuid": "8.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/node-cron/node_modules/uuid": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
|
||||
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/node-fetch": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz",
|
||||
@ -8124,6 +8150,11 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz",
|
||||
"integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q=="
|
||||
},
|
||||
"@types/node-cron": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.7.tgz",
|
||||
"integrity": "sha512-9PuLtBboc/+JJ7FshmJWv769gDonTpItN0Ol5TMwclpSQNjVyB2SRxSKBcTtbSysSL5R7Oea06kTTFNciCoYwA=="
|
||||
},
|
||||
"@types/prettier": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz",
|
||||
@ -10702,6 +10733,21 @@
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
|
||||
"integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ=="
|
||||
},
|
||||
"node-cron": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.2.tgz",
|
||||
"integrity": "sha512-iP8l0yGlNpE0e6q1o185yOApANRe47UPbLf4YxfbiNHt/RU5eBcGB/e0oudruheSf+LQeDMezqC5BVAb5wwRcQ==",
|
||||
"requires": {
|
||||
"uuid": "8.3.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"uuid": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
|
||||
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
|
||||
}
|
||||
}
|
||||
},
|
||||
"node-fetch": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz",
|
||||
|
@ -8,6 +8,7 @@
|
||||
"@discordjs/rest": "^1.7.0",
|
||||
"@tsconfig/recommended": "^1.0.2",
|
||||
"@types/node": "^18.15.11",
|
||||
"@types/node-cron": "^3.0.7",
|
||||
"@types/request": "^2.48.8",
|
||||
"@types/uuid": "^9.0.1",
|
||||
"axios": "^1.3.5",
|
||||
@ -16,6 +17,7 @@
|
||||
"discord.js": "^14.9.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"jellyfin-apiclient": "^1.10.0",
|
||||
"node-cron": "^3.0.2",
|
||||
"sqlite3": "^5.1.6",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^5.0.4",
|
||||
|
129
server/commands/closepoll.ts
Normal file
129
server/commands/closepoll.ts
Normal file
@ -0,0 +1,129 @@
|
||||
import { Guild, GuildScheduledEvent, GuildScheduledEventEditOptions, GuildScheduledEventSetStatusArg, GuildScheduledEventStatus, Message, MessageEditOptions, TextChannel } from 'discord.js'
|
||||
import { v4 as uuid } from 'uuid'
|
||||
import { config } from '../configuration'
|
||||
import { Emotes } from '../events/guildScheduledEventCreate'
|
||||
import { logger } from '../logger'
|
||||
import { Command } from '../structures/command'
|
||||
import { RunOptions } from '../types/commandTypes'
|
||||
import { client } from '../..'
|
||||
|
||||
export default new Command({
|
||||
name: 'closepoll',
|
||||
description: 'Aktuelle Umfrage für nächste Watchparty beenden und Gewinner in Event eintragen.',
|
||||
options: [],
|
||||
run: async (interaction: RunOptions) => {
|
||||
const command = interaction.interaction
|
||||
const requestId = uuid()
|
||||
const guildId = command.guildId!
|
||||
logger.info("Got command for closing poll!", { guildId, requestId })
|
||||
if (!command.guild) {
|
||||
logger.error("No guild found in interaction. Cancelling closing request", { guildId, requestId })
|
||||
command.followUp("Es gab leider ein Problem. Ich konnte deine Anfrage nicht bearbeiten :(")
|
||||
return
|
||||
}
|
||||
|
||||
command.followUp("Alles klar, beende die Umfrage :)")
|
||||
closePoll(command.guild, requestId)
|
||||
}
|
||||
})
|
||||
|
||||
export async function closePoll(guild: Guild, requestId: string) {
|
||||
const guildId = guild.id
|
||||
logger.info("stopping poll", { guildId, requestId })
|
||||
|
||||
const announcementChannel: TextChannel = client.getAnnouncementChannelForGuild(guildId)
|
||||
|
||||
const messages: Message<true>[] = (await announcementChannel.messages.fetch()) //todo: fetch only pinned messages
|
||||
.map((value, _) => value)
|
||||
.filter(message => !message.cleanContent.includes("[Abstimmung beendet]") && message.cleanContent.includes("[Abstimmung]"))
|
||||
.sort((a, b) => b.createdTimestamp - a.createdTimestamp)
|
||||
|
||||
if (!messages || messages.length <= 0) {
|
||||
logger.info("Could not find any vote messages. Cancelling pollClose", { guildId, requestId })
|
||||
return
|
||||
}
|
||||
|
||||
const lastMessage: Message<true> = messages[0]
|
||||
|
||||
logger.debug(`Found messages: ${JSON.stringify(messages, null, 2)}`, { guildId, requestId })
|
||||
|
||||
logger.debug(`Last message: ${JSON.stringify(lastMessage, null, 2)}`, { guildId, requestId })
|
||||
|
||||
const votes = await (await getVotesByEmote(lastMessage, guildId, requestId))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
|
||||
logger.debug(`votes: ${JSON.stringify(votes, null, 2)}`, { guildId, requestId })
|
||||
|
||||
updateEvent(votes, guild!, guildId, requestId)
|
||||
updateMessage(votes[0].movie, lastMessage, guildId, requestId)
|
||||
|
||||
//lastMessage.unpin() //todo: uncomment when bot has permission to pin/unpin
|
||||
}
|
||||
|
||||
async function updateMessage(movie: string, message: Message, guildId: string, requestId: string) {
|
||||
const body = `[Abstimmung beendet] Gewonnen hat: ${movie}`
|
||||
.concat(message.cleanContent.substring("[Abstimmung]".length))
|
||||
|
||||
const options: MessageEditOptions = {
|
||||
content: body,
|
||||
}
|
||||
logger.info("Updating message.", { guildId, requestId })
|
||||
message.edit(options)
|
||||
|
||||
}
|
||||
|
||||
async function updateEvent(votes: Vote[], guild: Guild, guildId: string, requestId: string) {
|
||||
logger.info(`Updating event with movie ${votes[0].movie}.`, { guildId, requestId })
|
||||
const voteEvents = (await guild.scheduledEvents.fetch())
|
||||
.map((value, _) => value)
|
||||
.filter(event => event.name.toLowerCase().includes("voting offen"))
|
||||
logger.debug(`Found events: ${JSON.stringify(voteEvents, null, 2)}`, { guildId, requestId })
|
||||
|
||||
if (!voteEvents || voteEvents.length <= 0) {
|
||||
logger.error("Could not find vote event. Cancelling update!", { guildId, requestId })
|
||||
return
|
||||
}
|
||||
|
||||
const voteEvent: GuildScheduledEvent<GuildScheduledEventStatus> = voteEvents[0]
|
||||
const options: GuildScheduledEventEditOptions<GuildScheduledEventStatus.Scheduled, GuildScheduledEventSetStatusArg<GuildScheduledEventStatus.Scheduled>> = {
|
||||
name: votes[0].movie,
|
||||
description: `!wp\nNummer 2: ${votes[1].movie} mit ${votes[1].count - 1} Stimmen\nNummer 3: ${votes[2].movie} mit ${votes[2].count - 1} Stimmen`
|
||||
}
|
||||
logger.debug(`Updating event: ${JSON.stringify(voteEvent, null, 2)}`, { guildId, requestId })
|
||||
logger.info("Updating event.", { guildId, requestId })
|
||||
voteEvent.edit(options)
|
||||
}
|
||||
|
||||
type Vote = {
|
||||
emote: string, //todo habs nicht hinbekommen hier Emotes zu nutzen
|
||||
count: number,
|
||||
movie: string
|
||||
}
|
||||
|
||||
async function getVotesByEmote(message: Message, guildId: string, requestId: string): Promise<Vote[]> {
|
||||
const votes: Vote[] = []
|
||||
logger.debug(`Number of items in emotes: ${Object.values(Emotes).length}`, { guildId, requestId })
|
||||
for (let i = 0; i < Object.keys(Emotes).length / 2; i++) {
|
||||
const emote = Emotes[i]
|
||||
logger.debug(`Getting reaction for emote ${emote}`, { guildId, requestId })
|
||||
const reaction = await message.reactions.resolve(emote)
|
||||
logger.debug(`Reaction for emote ${emote}: ${JSON.stringify(reaction, null, 2)}`, { guildId, requestId })
|
||||
if (reaction) {
|
||||
const vote: Vote = { emote: emote, count: reaction.count, movie: extractMovieFromMessageByEmote(message, emote, guildId, requestId) }
|
||||
votes.push(vote)
|
||||
}
|
||||
}
|
||||
return votes
|
||||
}
|
||||
|
||||
function extractMovieFromMessageByEmote(message: Message, emote: string, guildId: string, requestId: string): string {
|
||||
const lines = message.cleanContent.split("\n")
|
||||
const emoteLines = lines.filter(line => line.includes(emote))
|
||||
|
||||
if (!emoteLines) {
|
||||
return ""
|
||||
}
|
||||
const movie = emoteLines[0].substring(emoteLines[0].indexOf(emote) + emote.length + 2) // plus colon and space
|
||||
|
||||
return movie
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
import dotenv from "dotenv"
|
||||
import { AddListingProviderRequestToJSON } from "./jellyfin"
|
||||
dotenv.config()
|
||||
|
||||
interface options {
|
||||
@ -22,6 +23,8 @@ export interface Config {
|
||||
workaround_token: string
|
||||
watcher_role: string
|
||||
jf_admin_role: string
|
||||
announcement_channel_id: string
|
||||
jf_collection_id: string
|
||||
}
|
||||
}
|
||||
export const config: Config = {
|
||||
@ -53,6 +56,8 @@ export const config: Config = {
|
||||
jellyfin_url: process.env.JELLYFIN_URL ?? "",
|
||||
workaround_token: process.env.TOKEN ?? "",
|
||||
watcher_role: process.env.WATCHER_ROLE ?? "",
|
||||
jf_admin_role: process.env.ADMIN_ROLE ?? ""
|
||||
jf_admin_role: process.env.ADMIN_ROLE ?? "",
|
||||
announcement_channel_id: process.env.CHANNEL_ID ?? "",
|
||||
jf_collection_id: process.env.JELLYFIN_COLLECTION_ID ?? ""
|
||||
}
|
||||
}
|
||||
|
88
server/events/guildScheduledEventCreate.ts
Normal file
88
server/events/guildScheduledEventCreate.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { GuildScheduledEvent, Message, TextChannel } from "discord.js";
|
||||
import { ScheduledTask, schedule } from "node-cron";
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { client, jellyfinHandler } from "../..";
|
||||
import { closePoll } from "../commands/closepoll";
|
||||
import { config } from "../configuration";
|
||||
import { logger } from "../logger";
|
||||
import toDate from "date-fns/fp/toDate";
|
||||
import { addDays, isAfter, isBefore } from "date-fns";
|
||||
|
||||
|
||||
export const name = 'guildScheduledEventCreate'
|
||||
|
||||
export enum Emotes { "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" }
|
||||
|
||||
export let task: ScheduledTask | undefined
|
||||
|
||||
export async function execute(event: GuildScheduledEvent) {
|
||||
const requestId = uuid()
|
||||
logger.debug(`New event created: ${JSON.stringify(event, null, 2)}`, { guildId: event.guildId, requestId })
|
||||
|
||||
if (event.name.toLowerCase().includes("!nextwp")) {
|
||||
logger.info("Event was a placeholder event to start a new watchparty and voting. Creating vote!", { guildId: event.guildId, requestId })
|
||||
logger.debug("Renaming event", { guildId: event.guildId, requestId })
|
||||
event.edit({ name: "Watchparty - Voting offen" })
|
||||
const movies = await jellyfinHandler.getRandomMovies(5, event.guildId, requestId)
|
||||
|
||||
logger.info(`Got ${movies.length} random movies. Creating voting`, { guildId: event.guildId, requestId })
|
||||
logger.debug(`Movies: ${JSON.stringify(movies.map(movie => movie.name))}`, { guildId: event.guildId, requestId })
|
||||
|
||||
const announcementChannel: TextChannel = client.getAnnouncementChannelForGuild(event.guildId)
|
||||
logger.debug(`Found channel ${JSON.stringify(announcementChannel, null, 2)}`, { guildId: event.guildId, requestId })
|
||||
|
||||
let message = "[Abstimmung]\nEs gibt eine neue Abstimmung für die nächste Watchparty! 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].name!).concat("\n")
|
||||
}
|
||||
|
||||
const sentMessage: Message<true> = await (await announcementChannel.fetch()).send(message)
|
||||
|
||||
for (let i = 0; i < movies.length; i++) {
|
||||
sentMessage.react(Emotes[i])
|
||||
}
|
||||
|
||||
if (!task) {
|
||||
task = schedule("0 * * * * *", () => checkForPollsToClose(event))
|
||||
}
|
||||
|
||||
// sentMessage.pin() //todo: uncomment when bot has permission to pin messages. Also update closepoll.ts to only fetch pinned messages
|
||||
}
|
||||
}
|
||||
|
||||
async function checkForPollsToClose(event: GuildScheduledEvent): Promise<void> {
|
||||
const requestId = uuid()
|
||||
logger.info(`Automatic check for poll closing.`, { guildId: event.guildId, requestId })
|
||||
if (!event.guild) {
|
||||
logger.error("No guild in event. Cancelling.", { guildId: event.guildId, requestId })
|
||||
return
|
||||
}
|
||||
//refetch event in case the time changed or the poll is already closed
|
||||
const events = (await event.guild.scheduledEvents.fetch())
|
||||
.filter(event => event.name.toLowerCase().includes("voting offen"))
|
||||
.map((value, _) => value)
|
||||
|
||||
if (!events || events.length <= 0) {
|
||||
logger.info("Did not find any events. Cancelling", { guildId: event.guildId, requestId })
|
||||
return
|
||||
} else if (events.length > 1) {
|
||||
logger.error(`More than one event found. Don't know which one is the right one :( Events: ${JSON.stringify(events, null, 2)}`, { guildId: event.guildId, requestId })
|
||||
return
|
||||
}
|
||||
const updatedEvent = events[0] //add two hours because of different timezones in discord api and Date.now()
|
||||
if (!updatedEvent.scheduledStartTimestamp) {
|
||||
logger.error("Event does not have a scheduled start time. Cancelling", { guildId: event.guildId, requestId })
|
||||
return
|
||||
}
|
||||
|
||||
const eventDate: Date = toDate(updatedEvent.scheduledStartTimestamp)
|
||||
const closePollDate: Date = addDays(eventDate, -2)
|
||||
|
||||
if (isAfter(Date.now(), closePollDate)) {
|
||||
logger.info("Less than two days until event. Closing poll", { guildId: event.guildId, requestId })
|
||||
closePoll(event.guild, requestId)
|
||||
} else {
|
||||
logger.info(`ScheduledStart: ${closePollDate}. Now: ${toDate(Date.now())}`, { guildId: event.guildId, requestId })
|
||||
}
|
||||
}
|
@ -9,8 +9,8 @@ export const name = 'guildScheduledEventUpdate'
|
||||
|
||||
export async function execute(oldEvent: GuildScheduledEvent, newEvent: GuildScheduledEvent) {
|
||||
try {
|
||||
logger.info(JSON.stringify(newEvent, null, 2))
|
||||
const requestId = uuid()
|
||||
logger.debug(`Got scheduledEvent update. New Event: ${JSON.stringify(newEvent, null, 2)}`,{guildId: newEvent.guildId, requestId})
|
||||
|
||||
if (newEvent.description?.toLowerCase().includes("!wp") && [GuildScheduledEventStatus.Active, GuildScheduledEventStatus.Completed].includes(newEvent.status)) {
|
||||
const roles = getGuildSpecificTriggerRoleId(newEvent.guildId).map((key, value)=> value)
|
||||
@ -37,6 +37,7 @@ export async function execute(oldEvent: GuildScheduledEvent, newEvent: GuildSche
|
||||
logger.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function createJFUsers(members: GuildMember[], movieName: string, requestId?: string) {
|
||||
logger.info(`Creating users for: \n ${JSON.stringify(members, null, 2)}`)
|
||||
members.forEach(member => {
|
||||
@ -46,6 +47,6 @@ async function createJFUsers(members: GuildMember[], movieName: string, requestI
|
||||
}
|
||||
|
||||
async function deleteJFUsers(guildId: string, requestId?: string) {
|
||||
logger.info(`Watchparty ended, deleting tmp users`)
|
||||
logger.info(`Watchparty ended, deleting tmp users`, { guildId, requestId })
|
||||
jellyfinHandler.purge(guildId, requestId)
|
||||
}
|
@ -2,8 +2,8 @@ import { GuildMember } from "discord.js";
|
||||
import { Config } from "../configuration";
|
||||
import { Maybe, PermissionLevel } from "../interfaces";
|
||||
import { logger } from "../logger";
|
||||
import { CreateUserByNameOperationRequest, DeleteUserRequest, SystemApi, UpdateUserPasswordOperationRequest, UpdateUserPolicyOperationRequest, UserApi } from "./apis";
|
||||
import { UpdateUserPasswordRequest } from "./models";
|
||||
import { CreateUserByNameOperationRequest, DeleteUserRequest, GetItemsRequest, GetMovieRemoteSearchResultsOperationRequest, ItemLookupApi, ItemsApi, LibraryApi, SystemApi, UpdateUserPasswordOperationRequest, UpdateUserPolicyOperationRequest, UserApi } from "./apis";
|
||||
import { BaseItemDto, UpdateUserPasswordRequest } from "./models";
|
||||
import { UserDto } from "./models/UserDto";
|
||||
import { Configuration, ConfigurationParameters } from "./runtime";
|
||||
|
||||
@ -12,6 +12,7 @@ export class JellyfinHandler {
|
||||
|
||||
private userApi: UserApi
|
||||
private systemApi: SystemApi
|
||||
private moviesApi: ItemsApi
|
||||
private token: string
|
||||
private authHeader: { headers: { 'X-Emby-Authorization': string } }
|
||||
private config: Config
|
||||
@ -24,7 +25,7 @@ export class JellyfinHandler {
|
||||
}
|
||||
return this.serverName
|
||||
}
|
||||
constructor(_config: Config, _userApi?: UserApi, _systemApi?: SystemApi) {
|
||||
constructor(_config: Config, _userApi?: UserApi, _systemApi?: SystemApi, _itemsApi?: ItemsApi) {
|
||||
this.config = _config
|
||||
this.token = this.config.bot.jellfin_token
|
||||
this.authHeader = {
|
||||
@ -40,8 +41,14 @@ export class JellyfinHandler {
|
||||
basePath: this.config.bot.jellyfin_url,
|
||||
headers: this.authHeader.headers
|
||||
}
|
||||
const libraryApiConfigurationParams: ConfigurationParameters = {
|
||||
basePath: this.config.bot.jellyfin_url,
|
||||
headers: this.authHeader.headers
|
||||
}
|
||||
|
||||
this.userApi = _userApi ?? new UserApi(new Configuration(userApiConfigurationParams))
|
||||
this.systemApi = _systemApi ?? new SystemApi(new Configuration(systemApiConfigurationParams))
|
||||
this.moviesApi = _itemsApi ?? new ItemsApi(new Configuration(libraryApiConfigurationParams))
|
||||
logger.info(`Initialized Jellyfin handler`, { requestId: 'Init' })
|
||||
}
|
||||
|
||||
@ -222,7 +229,38 @@ export class JellyfinHandler {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
export enum UserUpsertResult {enabled, created}
|
||||
public async getAllMovies(guildId: string, requestId: string): Promise<BaseItemDto[]> {
|
||||
logger.info("requesting all movies from jellyfin", { guildId, requestId })
|
||||
|
||||
const liloJfUser = await this.getUser(<GuildMember>{ guild: { id: guildId }, displayName: "lilo" }, requestId)
|
||||
|
||||
const searchParams: GetItemsRequest = {
|
||||
userId: liloJfUser?.id,
|
||||
parentId: this.config.bot.jf_collection_id // collection ID for all movies
|
||||
}
|
||||
const movies = (await (this.moviesApi.getItems(searchParams))).items?.filter(item => !item.isFolder)
|
||||
// logger.debug(JSON.stringify(movies, null, 2), { guildId: guildId, requestId })
|
||||
logger.info(`Found ${movies?.length} movies in total`, { guildId, requestId })
|
||||
return movies ?? []
|
||||
}
|
||||
|
||||
public async getRandomMovies(count: number, guildId: string, requestId: string): Promise<BaseItemDto[]> {
|
||||
logger.info(`${count} random movies requested.`, { guildId, requestId })
|
||||
const allMovies = await this.getAllMovies(guildId, requestId)
|
||||
if (count >= allMovies.length) {
|
||||
logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`, { guildId, requestId })
|
||||
return allMovies
|
||||
}
|
||||
const movies: BaseItemDto[] = []
|
||||
for (let i = 0; i < count; i++) {
|
||||
const index = Math.random() * allMovies.length
|
||||
movies.push(...allMovies.splice(index, 1)) // maybe out of bounds? ?
|
||||
}
|
||||
|
||||
return movies
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
export enum UserUpsertResult { enabled, created }
|
||||
|
||||
|
@ -1,18 +1,21 @@
|
||||
import { ApplicationCommandDataResolvable, Client, ClientOptions, Collection, GatewayIntentBits, Guild, IntentsBitField, Snowflake } from "discord.js";
|
||||
import { ApplicationCommandDataResolvable, Client, ClientOptions, Collection, GatewayIntentBits, Guild, IntentsBitField, Snowflake, TextChannel } from "discord.js";
|
||||
import { CommandType } from "../types/commandTypes";
|
||||
import fs from 'fs'
|
||||
import { config } from "../configuration";
|
||||
import { logger } from "../logger";
|
||||
import { JellyfinHandler } from "../jellyfin/handler";
|
||||
|
||||
|
||||
|
||||
export class ExtendedClient extends Client {
|
||||
private eventFilePath = `${__dirname}/../events`
|
||||
private commandFilePath = `${__dirname}/../commands`
|
||||
private jellyfin: JellyfinHandler
|
||||
public commands: Collection<string, CommandType> = new Collection()
|
||||
private announcementChannels: Collection<string, TextChannel> = new Collection //guildId to TextChannel
|
||||
public constructor(jf: JellyfinHandler) {
|
||||
const intents: IntentsBitField = new IntentsBitField()
|
||||
intents.add(IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.MessageContent, IntentsBitField.Flags.Guilds, IntentsBitField.Flags.DirectMessages, IntentsBitField.Flags.GuildScheduledEvents, IntentsBitField.Flags.GuildVoiceStates)
|
||||
intents.add(IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.MessageContent, IntentsBitField.Flags.Guilds, IntentsBitField.Flags.DirectMessages, IntentsBitField.Flags.GuildScheduledEvents, IntentsBitField.Flags.GuildVoiceStates)
|
||||
const options: ClientOptions = { intents }
|
||||
super(options)
|
||||
this.jellyfin = jf
|
||||
@ -61,20 +64,38 @@ export class ExtendedClient extends Client {
|
||||
//logger.info(`Ready processing ${JSON.stringify(client)}`)
|
||||
logger.info(`SlashCommands: ${JSON.stringify(slashCommands)}`)
|
||||
const guilds = client.guilds.cache
|
||||
|
||||
this.registerCommands(slashCommands, guilds)
|
||||
this.cacheUsers(guilds)
|
||||
this.cacheAnnouncementServer(guilds)
|
||||
})
|
||||
} catch (error) {
|
||||
logger.info(`Error refreshing slash commands: ${error}`)
|
||||
}
|
||||
}
|
||||
private async cacheAnnouncementServer(guilds: Collection<Snowflake, Guild>) {
|
||||
for (const guild of guilds.values()) {
|
||||
const channels: TextChannel[] = <TextChannel[]>(await guild.channels.fetch())
|
||||
?.filter(channel => channel!.id === config.bot.announcement_channel_id)
|
||||
.map((value, _) => value)
|
||||
|
||||
if (!channels || channels.length != 1) {
|
||||
logger.error(`Could not find announcement channel for guild ${guild.name} with guildId ${guild.id}. Found ${channels}`)
|
||||
continue
|
||||
}
|
||||
logger.info(`Fetched announcement channel: ${JSON.stringify(channels[0])}`)
|
||||
this.announcementChannels.set(guild.id, channels[0])
|
||||
}
|
||||
}
|
||||
public getAnnouncementChannelForGuild(guildId: string): TextChannel {
|
||||
return this.announcementChannels.get(guildId)! //we set the channel by ourselves only if we find one, I think this is sage (mark my words)
|
||||
}
|
||||
public async cacheUsers(guilds: Collection<Snowflake, Guild>) {
|
||||
guilds.forEach((guild: Guild, id: Snowflake) => {
|
||||
logger.info(`Fetching members for ${guild.name}|${id}`)
|
||||
guild.members.fetch()
|
||||
logger.info(`Fetched: ${guild.memberCount} members`)
|
||||
})
|
||||
|
||||
}
|
||||
public async registerEventCallback() {
|
||||
try {
|
||||
|
Loading…
Reference in New Issue
Block a user