Discord.Net Documentation

repository·dev·Indexed 26 days ago

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

An unofficial .NET API wrapper for the Discord API providing high-level abstractions for interacting via WebSockets and REST. The library includes a command system with support for preconditions, dependency injection, and rich embed construction via EmbedBuilder, as well as utilities for comparing Discord entities and handling voice binaries.

Tokens
48.3K
Snippets
66
Records
348
Agent score
85%

What's inside Discord.Net

  1. Introduction to Message Components V2

    dev
    Message Components V2 is a framework for adding interactive elements to messages sent by your bot. Compared to V1, V2 provides significantly more control over the placement and display of elements such as images, text fields, buttons, and combo boxes. Components are passed as a parameter when sending messages.
  2. Understand Discord.Net implementation splits

    dev

    Discord.Net is divided into three distinct packages. Depending on your use case, you will interact with different sets of classes and interfaces:

    • Discord.Net.Core: Contains the base interfaces that model the Discord API. These are consistent across all implementations. Use these if you are writing implementation-agnostic libraries or addons.
    • Discord.Net.Rest: Contains concrete classes used strictly for the REST portion of Discord's API. Entities in this package are prefixed with Rest (e.g., RestChannel). Use this if you are implementing REST-based interactions.
    • Discord.Net.WebSocket: Contains concrete classes used primarily with Discord's WebSocket API or for entities kept in cache. This is the primary implementation used when developing bots. Entities in this package are prefixed with Socket (e.g., SocketChannel).
  3. Understand Parameter TypeConverters

    dev

    TypeConverters are responsible for registering command parameters to Discord and parsing user inputs into method parameters.

    By default, the @Discord.Interactions library provides TypeConverters for:

    • Implementations of IUser, IChannel, IRole, and IMentionable
    • string
    • Numeric types: float, double, decimal, sbyte, byte, int16, int32, int64, uint16, uint32, uint64
    • bool, char
    • enum
    • DateTime and TimeSpan
  4. Understand the difference between Socket and REST entities

    dev

    Discord.Net uses two distinct types of entities depending on how they are retrieved:

    • Socket Entities: Created via the Gateway (e.g., through DiscordSocketClient events). These entities are stored in the client's global cache for later use and are generally preferred for performance.
    • REST Entities: Retrieved via REST API calls. These are transient and will be disposed after use. Use these sparingly to avoid hitting API rate limits.

    Note on Channels: In events like MessageReceived, the message's Channel property is provided as a SocketMessageChannel. If you need guild-specific channel information (like a SocketTextChannel), you must cast the channel object to the more specific type.

  5. Understand application command types and scopes

    dev

    Application commands in Discord.Net consist of three types:

    1. Slash commands: Composed of a name, description, and a block of options (arguments) used to validate user input.
    2. Context menu User commands: Accessed by right-clicking (or long-pressing on mobile) a user.
    3. Context menu Message commands: Accessed by right-clicking (or long-pressing on mobile) a message.

    Command Scopes:

    • Global commands: Available in every guild that has authorized your application.
    • Guild commands: Restricted to a specific guild.

    Interactions: When a command is used, your application receives an Interaction. This object contains the submitted values and metadata such as guild_id, channel_id, and member information.

  6. Understand the Discord.NET channel interface inheritance tree

    dev
    Discord.NET uses an interface-based hierarchy for channels. To interact with specific channel types (like Text, Voice, or Category channels), you must understand the inheritance tree to correctly cast or type your channel objects. The hierarchy starts from the base IChannel interface and branches out into specialized interfaces such as ITextChannel, IVoiceChannel, IThreadChannel, and others.
  7. Access Discord.Net API Documentation

    dev
    The Discord.Net API documentation is automatically generated from the dev branch of the repository. It contains detailed documentation for all members and objects within the library. For developers looking to interact with Discord, the most common entry points and entities include the DiscordSocketClient, SocketGuildChannel, SocketGuildUser, SocketMessage, and SocketRole.
  8. Update ephemeral messages using UpdateAsync

    dev

    Ephemeral messages (messages sent with ephemeral: true) cannot be retrieved via REST or other means because they are not stored by Discord. To modify an ephemeral message that contains components, you must use the UpdateAsync method provided by the interaction object (e.g., SocketMessageComponent).

    UpdateAsync allows you to modify the message's content and components in response to a component interaction, effectively replacing the existing ephemeral message with updated content.

    public async Task SelectMenuHandler(SocketMessageComponent arg)
    {
        switch (arg.Data.CustomId)
        {
            case "select-1":
                var value = arg.Data.Values.First();
                // ... define new menu/components ...
    
                // Use UpdateAsync to update the message and its original content and components.
                await arg.UpdateAsync(x =>
                {
                    x.Content = $"Thank you {arg.User.Mention} for rating us {value}/5 on the gaming scale";
                    x.Components = new ComponentBuilder().WithSelectMenu(menu).Build();
                });
                break;
        }
    }
  9. Create a Select Menu using SelectMenuBuilder

    dev

    Use SelectMenuBuilder to define a select menu with a placeholder, a custom ID, minimum/maximum selection values, and various options. Once the menu is built, add it to a ComponentBuilder to be sent as part of a message.

    var menuBuilder = new SelectMenuBuilder()
        .WithPlaceholder("Select an option")
        .WithCustomId("menu-1")
        .WithMinValues(1)
        .WithMaxValues(1)
        .AddOption("Option A", "opt-a", "Option B is lying!")
        .AddOption("Option B", "opt-b", "Option A is telling the truth!");
    
    var builder = new ComponentBuilder()
        .WithSelectMenu(menuBuilder);
    
    // To send it in a command:
    await ReplyAsync("Whos really lying?", components: builder.Build());