Nyxx Discord API Wrapper

repository·main·Indexed 43 days ago

https://github.com/nyxx-discord/nyxx

A complete, robust, and efficient Dart wrapper around the Discord API for building bots and applications. Nyxx provides a structured architecture featuring Clients (NyxxRest, NyxxOAuth2, NyxxGateway), Managers for API interaction, and a builder system for creating and updating Discord models. It includes built-in support for sharding via isolates, Gateway event handling with intents, and a plugin system for extending functionality.

Tokens
14.3K
Snippets
35
Records
80
Agent score
55%

What's inside Nyxx

  1. Explore related nyxx packages

    main

    The nyxx ecosystem includes several specialized packages to extend your bot's functionality:

    • nyxx_commands: A command framework for handling both simple & complex commands.
    • nyxx_extensions: Provides pagination, emoji utilities, and other miscellaneous helpers.
    • nyxx_lavalink: Provides Lavalink support for playing audio in voice channels.
  2. Understand the relationship between Entities, Managers, and Models

    main

    In Nyxx, the API is structured around three interconnected concepts:

    1. Entities: Classes representing API structures (often subclasses of SnowflakeEntity). They contain structured data and provide convenience methods that act on that data. Many entity methods are shortcuts to corresponding Manager methods.
    2. Managers: Specialized objects that contain the logic for parsing related Models and provide the actual Dart APIs for interacting with Discord endpoints.
    3. Models: Immutable structures containing data returned by the API.

    Key Behavior: Immutability Entities are immutable. Methods that appear to 'update' an entity (such as WritableSnowflakeEntity.update) do not modify the existing instance. Instead, they return a new instance containing the updated data. You must use the returned instance for any subsequent operations.

  3. Use specialized constructors for ApplicationCommandBuilder

    main

    The ApplicationCommandBuilder is a shared builder used for different types of commands (Chat, User, or Message commands). The specific behavior is determined by the ApplicationCommandBuilder.type field.

    Because certain fields are only compatible with specific command types, you should use the provided named constructors instead of the default constructor. These named constructors ensure that only the allowed fields for that specific command type are accessible, preventing invalid API requests.

  4. How builder naming and type arguments work

    main

    Builders in Nyxx follow a predictable naming convention based on the model they correspond to:

    • CreateBuilder: Named as {Model}Builder (e.g., GuildCreateBuilder).
    • UpdateBuilder: Named as {Model}UpdateBuilder (e.g., GuildUpdateBuilder).

    The type argument used in the builder (e.g., Builder<Model>) indicates which model the builder is intended to produce. Note that some builders are "upload-only" and do not correspond to a specific model; in these cases, the builder uses itself as its own type argument.

  5. How to listen for Discord Gateway events

    main

    Events received from Discord's Gateway API fall into two categories:

    1. Session State Events (GatewayEvent subclasses): These are primarily used by nyxx internally to manage the connection. You can listen to them via Gateway.messages by looking for EventReceived events.
    2. State Change Events (DispatchEvent subclasses): These represent actual data changes in Discord, such as a new Message being created or a User updating their Activity.

    To listen for DispatchEvents, you should use:

    • The Gateway.events stream.
    • Or the event-specific convenience streams provided on NyxxGateway (e.g., client.onXXXEvent).

    Note: The Gateway.messages stream only emits RawDispatchEvents that have not yet been parsed into high-level objects.

  6. How Managers work in Nyxx

    main

    Managers are the primary interface for interacting with Discord's HTTP endpoints. They act as a bridge between the raw Discord API and your Dart code by providing:

    1. Deserialization: Converting JSON responses from Discord into typed [Models].
    2. API Wrappers: Providing Dart methods that correspond to specific Discord HTTP endpoints.
    3. Caching: Managing local [Cache]s for the [Entities] they oversee.

    Managers are typically organized around specific [Entity] types (e.g., a Guild Manager for Guild entities), though some may simply group related endpoints together.

  7. How the Gateway connection is managed

    main

    The Gateway class manages the overall connection to Discord's Gateway API. It coordinates one or more Shard instances, receives GatewayEvents from them, parses them, and forwards them to Gateway.events or via NyxxGateway.onXXXEvent streams.

    Key components of the Gateway architecture:

    • Gateway: The central coordinator for shards and event distribution.
    • Shard: Maintains a single websocket connection to Discord. Multiple shards can be used for resiliency and load balancing.
    • Isolates: Each shard's websocket connection and reconnection logic runs in a separate Dart Isolate. This offloads decompression, JSON/ETF deserialization, and initial parsing from the main isolate.
    • Event Flow: Initial parsing happens in the worker isolate. The Gateway in the main isolate performs final parsing, such as converting RawDispatchEvents into DispatchEvents that are linked to the client.
  8. Use partial entities to avoid unnecessary API fetches

    main

    A partial entity is a lightweight reference to an entity that contains only its ID. You can use a partial entity to call methods that only require an ID (like fetching related resources) without performing a full GET request to fetch the entity's complete model first.

    To create a partial entity, use the [] operator on a Manager and provide the entity's Snowflake ID.

    To convert a partial entity into a full model (fetching the complete data from the API), use the .get() method on the partial entity.

    // Accessing a partial Guild to fetch its channels without fetching the Guild model first
    client.guilds[GUILD_ID].fetchChannels();
    
    // To get the full Guild model from the partial entity:
    // client.guilds[GUILD_ID].get();
  9. How to create a custom Nyxx plugin

    main

    To create a custom plugin, create a subclass of NyxxPlugin and specify the type of client it is compatible with using the type parameter.

    If your plugin requires state that is unique to each client instance, you should:

    1. Create a subclass of NyxxPluginState to hold that state.
    2. Override NyxxPlugin.createState to return an instance of your state subclass.

    You can then override methods in both NyxxPlugin and NyxxPluginState to execute logic at specific points in the client's lifecycle, such as intercepting HTTP requests or Gateway events.

  10. Understand the core architecture of nyxx

    main

    The nyxx library is built around a central Client that manages the lifecycle of components used to access the Discord API. All clients implement the Nyxx interface.

    Key architectural components include:

    • Clients: Created via static methods on the Nyxx class to produce specific types like NyxxRest, NyxxOAuth2, or NyxxGateway.
    • Configuration: Clients are configured using ApiOptions (for Discord API interaction settings) and ClientOptions (for client-side behavior like plugins and caching).
    • HttpHandler: Every client exposes an HttpHandler used for performing HTTP requests to Discord.
    • Managers: The primary way users interact with the library. Managers provide deserialization for Models and Entities and offer concrete Dart APIs that map to Discord API endpoints.
    • Caching: Managers manage individual Cache instances. You can access cached items via Manager.cache, Manager.get, or the shorthand SnowflakeEntity.get.
    • Builders: While Models and Entities represent data received from Discord, Builders are used to create the structures sent to Discord.
    • Gateway: Used by clients that connect to Discord's Gateway API to manage connection lifecycles and receive events.
    • Plugins: A mechanism to encapsulate and extend functionality, with several built-in plugins available.
  11. Use Builders for creating and updating entities

    main
    When using a Manager to perform mutation operations like create or update, you should use [Builders] to specify the properties of the entity you are sending to Discord. This ensures type safety and follows the expected structure of the Discord API.
  12. Understand the difference between CreateBuilders and UpdateBuilders

    main

    Nyxx uses builders to construct models that are serialized and sent to the Discord API. Builders generally fall into two categories:

    1. CreateBuilders: Used for creating new instances. These often contain required fields that must be provided to successfully create the entity.
    2. UpdateBuilders: Used to update existing instances. These generally consist of optional fields, allowing you to modify only specific parts of an entity.

    Builders are typically named after the [Model] they represent. For example, a UserCreateBuilder would be used to create a user, while a UserUpdateBuilder would be used to update one.