113 lines
No EOL
3.6 KiB
TypeScript
113 lines
No EOL
3.6 KiB
TypeScript
import {
|
|
Client,
|
|
GatewayIntentBits,
|
|
Events,
|
|
Interaction,
|
|
ChatInputCommandInteraction,
|
|
MessageFlags,
|
|
Activity,
|
|
ActivityType
|
|
} from "discord.js";
|
|
import Commands from "./Commands/Commands";
|
|
import {Container} from "../Container/Container";
|
|
import {Logger} from "log4js";
|
|
import {UserError} from "./UserError";
|
|
|
|
export class DiscordClient {
|
|
private readonly client: Client;
|
|
private commands: Commands;
|
|
|
|
public get Client (): Client {
|
|
return this.client;
|
|
}
|
|
|
|
constructor() {
|
|
this.client = new Client({
|
|
intents: [GatewayIntentBits.Guilds]
|
|
})
|
|
|
|
this.commands = new Commands();
|
|
}
|
|
|
|
applyEvents() {
|
|
this.client.once(Events.ClientReady, () => {
|
|
Container.get<Logger>("logger").info(`Ready! Logged in as ${this.client.user.tag}`);
|
|
this.client.user.setActivity('your PnP playdates', {
|
|
type: ActivityType.Watching,
|
|
});
|
|
})
|
|
|
|
this.client.on(Events.InteractionCreate, async (interaction: Interaction) => {
|
|
const method = this.findCommandMethod(interaction);
|
|
if (!method) {
|
|
Container.get<Logger>("logger").error(`Could not find method for '${interaction.commandName}'`);
|
|
return;
|
|
}
|
|
|
|
await method();
|
|
})
|
|
}
|
|
|
|
connect(token: string) {
|
|
this.client.login(token);
|
|
}
|
|
|
|
private findCommandMethod(interaction: Interaction) {
|
|
if (interaction.isChatInputCommand()) {
|
|
const command = this.commands.getCommand(interaction.commandName);
|
|
|
|
if (!command) {
|
|
return null;
|
|
}
|
|
|
|
if (!('execute' in command)) {
|
|
return null;
|
|
}
|
|
|
|
return async () => {
|
|
Container.get<Logger>("logger").debug(`Found chat command ${interaction.commandName}: running...`);
|
|
|
|
try {
|
|
await command.execute(interaction)
|
|
}
|
|
catch (e: any) {
|
|
Container.get<Logger>("logger").error(e)
|
|
|
|
let userMessage = ":x: There was an error while executing this command!";
|
|
if (e.constructor.name === UserError.name) {
|
|
userMessage = `:x: \`${e.message}\` - Please validate your request!`
|
|
}
|
|
if (interaction.replied || interaction.deferred) {
|
|
await interaction.followUp({ content: userMessage, flags: MessageFlags.Ephemeral });
|
|
} else {
|
|
await interaction.reply({ content: userMessage, flags: MessageFlags.Ephemeral });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (interaction.isAutocomplete()) {
|
|
const command = this.commands.getCommand(interaction.commandName);
|
|
|
|
if (!command) {
|
|
return null;
|
|
}
|
|
|
|
if (!('handleAutocomplete' in command)) {
|
|
return null;
|
|
}
|
|
|
|
return async () => {
|
|
Container.get<Logger>("logger").debug(`Found command ${interaction.commandName} for autocomplete: handling...`);
|
|
|
|
try {
|
|
await command.handleAutocomplete(interaction);
|
|
} catch (e: any) {
|
|
Container.get<Logger>('logger').error(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
} |