All files / discord/src index.ts

0% Statements 0/51
0% Branches 0/20
0% Functions 0/8
0% Lines 0/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153                                                                                                                                                                                                                                                                                                                 
import { Logger, FlarieCommand, type Platform, FlarieError } from '@flarie/core';
import { EventEmitter } from 'node:events';
import {
  BitFieldResolvable,
  Client,
  GatewayIntentsString,
  Partials,
  PermissionFlagsBits,
  REST,
  Routes,
  SlashCommandBuilder,
} from 'discord.js';
import { toFlarieInteraction } from './utils/interaction';
import { FlarieMessage } from '@flarie/core';
import { toDiscordSendPayload } from './utils/payloads';
 
export class DiscordPlatform extends EventEmitter implements Platform {
  public static readonly NAME = 'discord';
  #client: Client;
  #options: DiscordPlatform.InternalOptions;
  #commands: Map<string, FlarieCommand>;
 
  constructor({ username, partials, intents, ...options }: DiscordPlatform.Options) {
    super();
    this.#options = options;
    this.#commands = new Map();
 
    this.#client = new Client({
      partials,
      intents,
    });
 
    this.#client.on('ready', async () => {
      this.emit('ready');
 
      const promises: Promise<any>[] = [];
 
      if (username && this.#client.user) {
        promises.push(this.#client.user.setUsername(username));
      }
 
      await Promise.all(promises);
    });
  }
 
  async authenticate(): Promise<void> {
    await this.#client.login(this.#options.token);
  }
 
  async #unpublish() {
    this.#commands.clear();
 
    const rest = new REST({ version: '10' }).setToken(this.#options.token);
 
    Logger.silly('Deleting application commands...');
 
    await rest.put(Routes.applicationCommands(this.#options.clientId), { body: [] });
 
    Logger.info('Successfully deleted all application commands.');
  }
 
  async register(commands: FlarieCommand[]): Promise<void> {
    const rest = new REST({ version: '10' }).setToken(this.#options.token);
 
    try {
      await this.#unpublish();
 
      for (const command of commands) {
        this.#commands.set(command.name, command);
      }
 
      await rest.put(Routes.applicationCommands(this.#options.clientId), {
        body: commands.map((command) => {
          return new SlashCommandBuilder()
            .setName(command.name)
            .setDescription(command.description)
            .setDefaultMemberPermissions(command.disabled ? '0' : PermissionFlagsBits.UseApplicationCommands)
            .setDMPermission(command.allowDMs)
            .toJSON();
        }),
      });
 
      this.#client.on('interactionCreate', async (discordInteraction) => {
        if (!discordInteraction.isCommand()) return;
 
        const command = this.#commands.get(discordInteraction.commandName);
 
        if (!command) return;
 
        const interaction = toFlarieInteraction(discordInteraction);
 
        try {
          await command.invoke(interaction);
 
          if (!interaction.replied) {
            await interaction.reply({
              content: 'Your command completed, but you never told anyone about it! :<',
              ephemeral: true,
            });
          }
        } catch (error) {
          if (error instanceof FlarieError) {
            Logger.log(error.level, error.message);
            await interaction.reply(error.toFlarieMessage());
          } else {
            Logger.error(error?.toString());
            await interaction.reply('There was an error while executing this command!');
          }
        }
      });
    } catch (error) {
      console.error(error);
    }
  }
 
  async send(serverId: string, channelId: string, message: string | FlarieMessage): Promise<void> {
    const guild = this.#client.guilds.cache.get(serverId);
 
    if (!guild) {
      Logger.error(`Invalid server requested! (${serverId})`);
      return;
    }
 
    const channel = await this.#client.channels.fetch(channelId);
 
    Logger.silly('Channel: ', channel);
 
    if (!channel || !channel.isSendable()) {
      Logger.error(`Invalid channel requested! (${channelId})`);
      return;
    }
 
    await channel.send(toDiscordSendPayload(message));
  }
}
 
export namespace DiscordPlatform {
  export type Options = {
    username?: string;
    clientId: string;
    token: string;
    partials?: Partials[];
    intents: BitFieldResolvable<GatewayIntentsString, number>;
  };
 
  export type InternalOptions = {
    clientId: string;
    token: string;
  };
}
 
export { Partials } from 'discord.js';