discordx Documentation

repository·main·Indexed 20 days ago

https://github.com/discordx-ts/discordx

A TypeScript framework that extends discord.js, enabling developers to build Discord bots using a decorator-based approach. It provides a structured way to handle Slash commands, prefix commands, and GUI interactions (buttons, select menus, modals, and context menus). Key features include multi-bot support, dependency injection via TSyringe and TypeDI, and a guard system for event interception. The ecosystem includes specialized packages for music playback (@discordx/lava-player), pagination, and utility guards.

Tokens
67.1K
Snippets
229
Records
275
Agent score
72%

What's inside discordx

  1. Overview of discordx packages

    main

    The discordx ecosystem consists of several specialized packages designed to extend Discord bot functionality, ranging from core framework capabilities to music playback and pagination.

    Core Framework

    • discordx: The main framework for creating Discord bots using TypeScript and Decorators.
    • create-discordx: A CLI tool used to scaffold new projects using pre-defined templates.
    • @discordx/di: A dependency injection service that supports agnostic Inversion of Control (IOC).
    • @discordx/importer: A solution for importing modules in both ESM and CJS environments.
    • @discordx/utilities: A collection of utilities to enhance general discordx functionality.
    • @discordx/internal: Contains internal methods used by the discordx framework.

    Music and Audio

    • @discordx/lava-player: A Lavalink player library written in TypeScript for Node.js.
    • @discordx/lava-queue: A queue management system specifically for @discordx/lava-player.
    • @discordx/music: A music player library utilizing YTDL.
    • @discordx/plugin-lava-player: A high-level Discord music player plugin that leverages Lavalink.
    • @discordx/plugin-ytdl-player: A high-level Discord music player plugin that utilizes YTDL.

    UI and UX

    • @discordx/pagination: A library dedicated to creating pagination-based messages within Discord bots.
  2. Overview of discordx features

    main

    discordx is an extension of discord.js that allows you to build Discord bots using TypeScript decorators. Key features include:

    • Multi-bot support: Use the @Bot decorator to run multiple bots in a single Node.js instance.
    • Command types: Support for both modern Slash commands (@Slash) and traditional prefix commands (@SimpleCommand).
    • Interaction handling: Built-in handlers for all Discord interactions including slash commands, buttons, select menus, and context menus.
    • Dependency Injection: Support for TSyringe and TypeDI.
    • Command Management: Use client.initApplicationCommands to manage (create, update, or remove) Discord application commands.
  3. What is discordx?

    main
    discordx is a TypeScript framework designed to build Discord bots using decorators. It acts as an extension of discord.js, meaning it maintains the same internal behavior, methods, and properties as discord.js while providing a more readable and simplified developer experience through TypeScript decorators.
  4. Use @SlashGroup to organize commands into groups and subgroups

    main

    The @SlashGroup decorator allows you to create hierarchical command structures in Discord, such as subcommands and subcommand groups.

    Hierarchy Levels

    • Level 1 (Groups): A top-level command containing multiple subcommands.
      • command -> subcommand
    • Level 2 (Subgroups): A command containing groups, which in turn contain subcommands.
      • command -> subcommand-group -> subcommand

    Creating Groups and Subgroups

    To create a group or subgroup, use @SlashGroup as a Class Decorator on a class decorated with @Discord().

    • For a Group: Pass a SlashGroupOptions object.
    • For a Subgroup: Pass a SlashGroupOptions object and specify the root property to link it to its parent group.

    Assigning Commands to Groups

    Once a group is defined, you can assign @Slash methods to it using @SlashGroup as a Method Decorator or a Class Decorator.

    1. Class Level Assignment: Applying @SlashGroup(name) to the class will automatically assign all methods within that class to the specified group.
    2. Method Level Assignment: Applying @SlashGroup(name) directly to a specific method assigns only that method to the group.

    When working with subgroups, you must provide both the subgroup name and the root group name: @SlashGroup(subgroupName, rootName).

    // Creating a subgroup
    @Discord()
    @SlashGroup({ description: "Manage permissions", name: "permission" })
    @SlashGroup({
      description: "Manage permissions",
      name: "user",
      root: "permission", // must specify the parent group name
    })
    class Example {}
    
    // Assigning a method to a subgroup
    @Slash({ description: "get" })
    @SlashGroup("user", "permission")
    get() {}
  5. Use GUI decorators for interactive components

    main

    GUI decorators allow you to define and handle interactive Discord components like buttons, menus, and modals.

    • @ButtonComponent: Defines an interactive button.
    • @ContextMenu: Defines a context menu interaction.
    • @ModalComponent: Defines an interactive modal.
    • @SelectMenuComponent: Defines a select menu (dropdown) component.
  6. Use Guards to intercept events

    main

    Discordx implements a guard system inspired by Koa middleware. Guards are functions executed before an event handler to determine if the handler should proceed.

    • Application: Guards can be applied to @Slash, @On, @Once, @Discord (class-level), or globally.
    • Execution Order: When multiple guards are provided to a single @Guard decorator, they are executed in the order they are listed (top to bottom).
    • Usage: If a guard fails or performs logic to prevent execution, the decorated method will not be called.
    import { Client, Discord, Guard, On } from "discordx";
    import { NotBot } from "./NotBot";
    
    @Discord()
    class Example {
      @On()
      @Guard(NotBot) // Multiple guards can be passed here
      messageCreate([message]: ArgsOf<Events.MessageCreate>) {
        // ...
      }
    }
  7. Configure Gateway Intents for your Client

    main

    Intents determine what information your bot receives from Discord servers. They are not the same as permissions. When initializing the Client, you must specify an intents array. If you do not specify a certain intent, you will not receive the gateway events associated with that group.

    Note: If your application events are not triggering as expected, verify that you have included the necessary Intent in your configuration.

  8. Use Transformers to process command parameters

    main

    A Transformer acts as middleware for your parameters. You can pass a transformer function as the second argument to @SlashOption. This function takes the raw input and the interaction, and returns a transformed object (e.g., a database model instance).

    function DocumentTransformer(
      input: string,
      interaction: ChatInputCommandInteraction
    ): Document {
      return new Document(input, interaction);
    }
    
    @Discord()
    export class Example {
      @Slash({ description: "Save input into database", name: "save-input" })
      async withTransformer(
        @SlashOption(
          {
            description: "input",
            name: "input",
            required: true,
            type: ApplicationCommandOptionType.String,
          },
          DocumentTransformer
        )
        doc: Document,
        interaction: ChatInputCommandInteraction
      ): Promise<void> {
        await interaction.deferReply();
        doc.save();
      }
    }
  9. Use General decorators for bot lifecycle and event handling

    main

    General decorators are used to manage the bot instance, define scope, and listen to Discord events.

    • @Bot: Used to define or reference the bot instance.
    • @Discord: Used for Discord-related metadata or configuration.
    • @Guard: Used to implement middleware/guards to intercept and validate interactions.
    • @Guild: Used to scope logic to specific guilds.
    • @On: Used to listen to specific Discord events (e.g., message creation, member joins).
    • @Once: Used to listen to an event exactly once.
    • @Reaction: Used to listen to reaction events on messages.
  10. Implement Autocomplete options

    main

    Autocomplete allows you to dynamically return suggestions to a user as they type. You can implement this in two ways:

    1. Using a Resolver

    Pass a function to the autocomplete property within the @SlashOption configuration. This function receives the AutocompleteInteraction and you call interaction.respond([...]) to provide choices.

    2. Using a Boolean flag

    Set autocomplete: true in the @SlashOption configuration. In this mode, discordx will call your command handler with an AutocompleteInteraction instead of a standard CommandInteraction. You must then check interaction.isAutocomplete() inside your handler to process the suggestions.

    Note on this context: If you use a standard function for the resolver, this will refer to your class instance. If you use an arrow function, this will not be bound to your class.

    // Method 1: Resolver
    @SlashOption({
      autocomplete: function (interaction: AutocompleteInteraction) {
          interaction.respond([
            { name: "option a", value: "a" },
            { name: "option b", value: "b" },
          ]);
      },
      description: "autocomplete",
      name: "autocomplete",
      required: true,
      type: ApplicationCommandOptionType.String,
    })
    input: string,
    
    // Method 2: Boolean flag
    @Slash({ description: "autocomplete" })
    autocomplete(
      @SlashOption({
        autocomplete: true,
        description: "option-a",
        name: "option-a",
        required: true,
        type: ApplicationCommandOptionType.String,
      })
      searchText: string,
      interaction: CommandInteraction | AutocompleteInteraction
    ): void {
      if (interaction.isAutocomplete()) {
        // Handle autocomplete logic here
      }
    }
  11. Understand User instance behavior in simple commands

    main

    When resolving user instances within simple commands, the type returned depends on the context of the interaction:

    • In Direct Messages (DM):
      • If the user mentions the bot: You receive a ClientUser.
      • If the user mentions themselves: You receive a User.
      • Otherwise: An error is received.
    • In Guilds (Servers):
      • You will receive either a GuildMember or a User.