NetCord Documentation

repository·main·Indexed 19 days ago

https://github.com/netcorddev/netcord

A modern, high-performance C# library for interacting with the Discord API. NetCord is designed to be lightweight and asynchronous, supporting Native AOT and HTTP interactions. It provides a suite of NuGet packages including NetCord (core), NetCord.Services for command handling, and NetCord.Hosting for .NET Generic Host and ASP.NET Core extensions. The library supports both minimal API-style and module-based approaches for bot development, as well as comprehensive tools for handling interactions, modals, autocomplete, and rich message properties.

Tokens
33.3K
Snippets
99
Records
158
Agent score
65%

What's inside NetCord

  1. Overview of Discord Voice Integration in NetCord

    main

    NetCord provides capabilities for interacting with Discord voice channels, enabling bots to perform real-time audio tasks. Key capabilities include:

    • Connecting: Joining voice channels to participate in audio sessions.
    • Sending Voice: Streaming audio data (e.g., for music bots) to users in a channel.
    • Receiving Voice: Recording or processing incoming audio data from connected users.

    To use these features, you must ensure you have installed the necessary native dependencies as described in the installation guide.

  2. What is Sharding in NetCord

    main

    Sharding allows a Discord bot to split its responsibilities across multiple gateway connections to improve scalability and performance.

    In NetCord, sharding is managed by the ShardedGatewayClient, which acts as a controller for multiple instances of GatewayClient. Each individual shard is represented by a GatewayClient and handles a specific subset of guilds.

  3. What are Preconditions in NetCord

    main

    Preconditions are attributes used to determine whether a command or interaction can be invoked. They act as gates that validate the environment or the user before the command logic executes. Preconditions can be applied at multiple levels:

    • Modules: Applies the requirement to every command within that module.
    • Commands: Applies the requirement to a specific command.
    • Interactions: Applies to the interaction itself.
    • Parameters: Applies to specific arguments within a command.
  4. How component interaction contexts work

    main

    Component interactions in NetCord require maintaining context because the data provided by different interaction types (Buttons, Select Menus, Modals, etc.) varies significantly.

    Instead of using a single generic context and casting it, NetCord provides specialized context types. It is a best practice to use distinct services/contexts for different interaction types.

    Available context types include:

    • ButtonInteractionContext
    • StringMenuInteractionContext
    • UserMenuInteractionContext
    • RoleMenuInteractionContext
    • MentionableMenuInteractionContext
    • ChannelMenuInteractionContext
    • ModalInteractionContext (implied by ModalModule usage)
  5. Maintain stable voice connections during channel moves or region changes

    main

    Voice connections can break if a moderator moves the bot to a different channel or if the voice channel region changes. Discord handles the voice state, but you must re-establish the VoiceClient connection.

    Best Practices for Reconnection:

    1. Listen to both VoiceStateUpdate and VoiceServerUpdate events.
    2. Since these events may trigger independently and do not provide all data at once, combine the fresh data from the new event with existing data from your previous connection.
    3. Create a new VoiceClient instance with the combined data and call StartAsync*.
    4. Note: The new VoiceClient is completely independent. You must manually re-apply any ongoing audio tasks, operations, or event listeners that were attached to the old instance.
  6. What are intents and how do they work?

    main

    Intents are used to subscribe to specific Discord events (e.g., GatewayClient.MessageCreate or GatewayClient.GuildUserAdd). If you do not specify a particular intent, your bot will not receive the corresponding events.

    Privileged Intents: Some intents are considered 'privileged' and must be manually enabled in the Discord Developer Portal under the 'Bot' section before they will work in your application.

  7. Overload commands with different parameter types

    main

    You can define multiple methods for the same command name to handle different parameter types or counts. This is known as command overloading.

    Selection Logic:

    • By default, the command dispatcher selects the overload that matches the most parameters first, falling back to those with fewer parameters.
    • You can manually control which overload is preferred by setting the Priority property on the [Command] attribute.
    // Example of command overloading
    [Command("info", Priority = 1)]
    public Task Info()
    {
        return Task.CompletedTask;
    }
    
    [Command("info")]
    public Task Info(string subject)
    {
        return Task.CompletedTask;
    }
  8. Understand the different types of message properties

    main

    NetCord provides several message property types depending on the endpoint being used. All these types implement the @NetCord.Rest.IMessageProperties interface, which contains the properties common to all message types.

    Common property types include:

    • @NetCord.Rest.MessageProperties: Used with RestClient.SendMessageAsync to send messages to channels.
    • @NetCord.Rest.InteractionMessageProperties: Used for responding to interactions.
    • @NetCord.Rest.ReplyMessageProperties: Used with RestMessage.ReplyAsync to reply to existing messages.
    • @NetCord.Rest.WebhookMessageProperties: Used with RestClient.ExecuteWebhookAsync to send messages via webhooks.
    • @NetCord.Rest.ForumGuildThreadMessageProperties: Used with RestClient.CreateForumGuildThreadAsync to create forum posts.
  9. How Type Readers work in Netcord

    main

    Type Readers are the components responsible for parsing command and interaction arguments. While Netcord provides several built-in Type Readers for common types, you can implement and use custom Type Readers to handle specialized argument parsing logic.

    There are two ways to apply a custom Type Reader to an argument:

    1. Globally via Service Configuration: Add the custom Type Reader to your ...ServiceConfiguration.TypeReaders collection.
    2. Locally via Attributes: Specify a custom Type Reader for a specific argument using the ...ParameterAttribute.TypeReaderType property.
  10. How component interaction parameters work

    main

    Component interaction parameters allow you to pass data to components (like buttons or select menus) during their creation. This data is embedded in the component's custom ID.

    Key Concepts

    • Separator: By default, parameters are separated by a colon (:). You can customize this via @NetCord.Services.ComponentInteractions.ComponentInteractionServiceConfiguration1.ParameterSeparator`.
    • Type Conversion: NetCord uses built-in TypeReaders to automatically convert the string segments in a custom ID into specific C# types (e.g., long, string, bool).
    • Remainder: The final parameter in a sequence is treated as a "remainder," meaning it can contain colons without being split into further parameters. This is ideal for passing strings that contain colons.
    • Variable Parameters: Using the params keyword in your method signature allows a component to accept an arbitrary number of arguments.
    • Optional Parameters: You can define optional parameters by assigning them default values in your method. To omit an optional parameter in a custom ID, use consecutive colons (::) or a trailing colon (:) to indicate the position of the missing value.