Skip to content

DiscordService

This file defines the DiscordService class, which manages the lifecycle and event routing for a Discord bot client in the @sodacore/core Discord integration. It initializes the Discord client, registers it with the dependency injection container, and routes all Discord interactions and events to the appropriate handlers.


Features

  • Discord Client Initialization: Creates and configures a Discord.js Client instance using provided configuration.
  • Event Routing: Handles all major Discord events and routes them to the correct handler methods via a Router instance.
  • Interaction Handling: Supports slash commands, subcommands, buttons, select menus, autocomplete, context menus, and modal submissions.
  • Dependency Injection: Uses @Inject and @Service decorators for integration with the Sodacore DI system.
  • Service Lifecycle: Implements init, start, and stop methods for controlled startup and shutdown.

Usage

typescript
import DiscordService from './service/discord';

const discordService = new DiscordService();
await discordService.init();
await discordService.start();
// ... later
await discordService.stop();

API

Methods

async init(): Promise<void>

Initializes the Discord client, sets up event listeners, registers the client in the DI container, and initializes the router.

async start(): Promise<void>

Logs in to Discord using the configured bot token and announces connection.

async stop(): Promise<void>

Disconnects the client from Discord and cleans up resources.

private handleInteraction(interaction: Interaction<CacheType>): void

Routes Discord interactions (commands, buttons, select menus, etc.) to the appropriate router handler.

private handleEvent(event: keyof ClientEventTypes, ...args: unknown[]): void

Routes generic Discord events to the router.


How It Works

  1. Initialization:

    • Checks for a valid bot token.
    • Initializes the router.
    • Creates a Discord client with merged default and custom options.
    • Registers event listeners for ready, interactionCreate, and any additional events specified in the config.
    • Registers the client instance in the DI container for use elsewhere.
  2. Event Handling:

    • handleInteraction dispatches each interaction type (command, button, select menu, etc.) to the corresponding router method.
    • handleEvent dispatches generic Discord events to the router.
  3. Lifecycle Management:

    • start logs in to Discord and announces readiness.
    • stop disconnects the client and logs shutdown.

Notes

  • Requires a valid Discord bot token and configuration.
  • Designed to be used as a service within the Sodacore dependency injection system.
  • All Discord interactions and events are routed through the Router class for modular handling.
  • Supports extension and customization via configuration and event hooks.

Released under the Apache-2.0 License.