### Complete Program.cs for Bare Bones Setup Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md This is the complete Program.cs file demonstrating the bare-bones setup for component interactions. ```csharp using NetCord; using NetCord.Services; using NetCord.Services.ComponentInteractions; using System.Reflection; var client = new Client(TokenType.Bot, "YOUR_TOKEN"); var interactionService = new ComponentInteractionService(client); interactionService.AddInteraction("MyComponentInteraction"); interactionService.AddModules(Assembly.GetExecutingAssembly()); client.MessageReceived += async (message) => { await interactionService.ExecuteAsync(message); }; client.Start(); await Task.Delay(-1); ``` -------------------------------- ### Start Bot (Bare Bones) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/getting-started/making-a-bot.md Start your bot after manually creating the GatewayClient. This is the final step for the Bare Bones approach. ```csharp await client.StartAsync(); await Task.Delay(-1); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/netcorddev/netcord/blob/main/Documentation/README.md Run this command to install all necessary project dependencies before building. ```bash npm install ``` -------------------------------- ### Example Command Module Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/introduction.md An example module demonstrating how to define text commands in NetCord. ```csharp using NetCord.Services.Commands; namespace Example; public class ExampleModule : Module { [Command("ping")] public Task PingAsync() { return ReplyAsync("Pong!"); } } ``` -------------------------------- ### Example Application Command Module Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/introduction.md An example module showcasing how to structure and use application commands within a modular system. This demonstrates a simple "hello" command. ```csharp using NetCord.Services.ApplicationCommands; namespace Example; public class ExampleModule : ApplicationCommandModule { [SlashCommand("hello", "Says hello.")] public async Task HelloAsync(string name) { await RespondAsync($"Hello, {name}!"); } } ``` -------------------------------- ### Channel Menu Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle channel select menu interactions. ```csharp using NetCord.Services.ComponentInteractions; public class ChannelMenuModule : InteractionModule { [ChannelSelectMenuInteraction("MyChannelMenu")] public async Task OnChannelMenuSelect(ChannelSelectMenuInteractionContext context, ulong selectedChannel) { await context.RespondAsync($"Selected channel: {selectedChannel}"); } } ``` -------------------------------- ### Button Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle button interactions. ```csharp using NetCord.Services.ComponentInteractions; public class ButtonModule : InteractionModule { [ButtonInteraction("MyButton")] public async Task OnButtonClick(ButtonInteractionContext context) { await context.RespondAsync("Button clicked!"); } } ``` -------------------------------- ### Complete Program.cs for Application Commands Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/introduction.md This is the complete `Program.cs` file demonstrating the setup and usage of application commands with the .NET Generic Host. ```csharp using NetCord.Hosting.Services.ApplicationCommands; using NetCord.Services.Interactions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; var host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.AddApplicationCommands(); services.AddSlashCommand("ping", async interaction => await interaction.RespondAsync("Pong!")); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### Bare Bones Application Commands Setup Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/introduction.md Initialize `ApplicationCommandService` and add commands using `AddSlashCommand*`, `AddUserCommand*`, or `AddMessageCommand*` for minimal API commands, or `AddModules` to load from an assembly. This setup is for standalone applications without the .NET Generic Host. ```csharp using NetCord.Services.ApplicationCommands; using NetCord.Services.Interactions; var client = new Client(new Token("YOUR_TOKEN")); var commands = new ApplicationCommandService(); commands.AddSlashCommand("ping", async interaction => await interaction.RespondAsync("Pong!")); client.InteractionCreated += async interaction => { if (interaction is SlashCommandInteraction slashCommand) { await commands.ExecuteAsync(slashCommand); } }; await client.StartAsync(); ``` -------------------------------- ### Role Menu Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle role select menu interactions. ```csharp using NetCord.Services.ComponentInteractions; public class RoleMenuModule : InteractionModule { [RoleSelectMenuInteraction("MyRoleMenu")] public async Task OnRoleMenuSelect(RoleSelectMenuInteractionContext context, ulong selectedRole) { await context.RespondAsync($"Selected role: {selectedRole}"); } } ``` -------------------------------- ### User Menu Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle user select menu interactions. ```csharp using NetCord.Services.ComponentInteractions; public class UserMenuModule : InteractionModule { [UserSelectMenuInteraction("MyUserMenu")] public async Task OnUserMenuSelect(UserSelectMenuInteractionContext context, ulong selectedUser) { await context.RespondAsync($"Selected user: {selectedUser}"); } } ``` -------------------------------- ### Polish Localization JSON Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/localizations.md Example JSON file for Polish localizations. It defines translations for command names and descriptions, such as 'permissions' and 'animal'. ```json { "permissions": { "name": "uprawnienia", "description": "Wyświetla informacje o uprawnieniach." }, "animal": { "name": "zwierzę", "description": "Wyświetla losowe zwierzę." } } ``` -------------------------------- ### Modal Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle modal submissions. ```csharp using NetCord.Services.ComponentInteractions; public class ModalModule : InteractionModule { [ModalInteraction("MyModal")] public async Task OnModalSubmit(ModalInteractionContext context, string textInput) { await context.RespondAsync($"Submitted: {textInput}"); } } ``` -------------------------------- ### String Menu Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle string select menu interactions. ```csharp using NetCord.Services.ComponentInteractions; public class StringMenuModule : InteractionModule { [StringSelectMenuInteraction("MyStringMenu")] public async Task OnStringMenuSelect(StringSelectMenuInteractionContext context, string selectedOption) { await context.RespondAsync($"Selected: {selectedOption}"); } } ``` -------------------------------- ### Create User Menus (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Use this fluent syntax to create user menus. This example focuses on the initial creation of the menu. ```cs builder.AddChoices("Option 1", "Option 2").WithCustomId("my_select_menu")); ``` -------------------------------- ### Mentionable Menu Module Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md A module demonstrating how to handle mentionable select menu interactions. ```csharp using NetCord.Services.ComponentInteractions; public class MentionableMenuModule : InteractionModule { [MentionableSelectMenuInteraction("MyMentionableMenu")] public async Task OnMentionableMenuSelect(MentionableSelectMenuInteractionContext context, ulong selectedMentionable) { await context.RespondAsync($"Selected mentionable: {selectedMentionable}"); } } ``` -------------------------------- ### Creating Mentionable Menus (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This fluent syntax example demonstrates creating mentionable menus for selecting users or roles, with support for default selections. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(ActionRowBuilder.Create(MentionableSelectMenuBuilder.Create("Select a user or role")))) ``` -------------------------------- ### Register Sharded Event Handlers in Bare Bones Setup Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sharding.md For bare-bones setups, event handlers receive an additional GatewayClient parameter representing the shard that received the event. ```cs using NetCord; using NetCord.Gateway; client.MessageUpdateHandler += async (client, eventModel) => { if (eventModel is MessageUpdateEvent messageUpdateEvent) { // Handle message update } }; ``` -------------------------------- ### Creating Channel Menus (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This fluent syntax example shows how to create channel menus, allowing users to select channels with optional type filtering and default channel specification. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(ActionRowBuilder.Create(ChannelSelectMenuBuilder.Create("Select a channel")))) ``` -------------------------------- ### Configure Localizations Provider in Bare Bones Setup Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/localizations.md Configure the JsonLocalizationsProvider directly when setting up application commands in a bare-bones NetCord application. This is useful for simpler setups. ```csharp var client = new NetCord.DiscordClient(new Token("YOUR_BOT_TOKEN")); var applicationCommands = new ApplicationCommandService(client, new JsonLocalizationsProvider()); ``` -------------------------------- ### Creating Role Menus (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This fluent syntax example shows how to create role menus for selecting roles, including the option to set default roles. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(ActionRowBuilder.Create(RoleSelectMenuBuilder.Create("Select a role")))) ``` -------------------------------- ### Install NetCord via .NET CLI Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/getting-started/installation.md Use this command to add the NetCord package to your project using the .NET CLI. Ensure prerelease versions are included. ```bash dotnet add package NetCord --prerelease ``` -------------------------------- ### Create GatewayClient Manually (Bare Bones) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/getting-started/making-a-bot.md Manually create a GatewayClient for your bot when using the Bare Bones approach. This example includes adding a console logger. ```csharp using NetCord; using NetCord.Gateway; using NetCord.Logging; var client = new GatewayClient(new Token(TokenType.Bot, "YOUR_BOT_TOKEN")); client.UseDefaultLogging(); ``` -------------------------------- ### Create a base64-encoded attachment Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This example demonstrates creating an attachment using base64 encoding. The content will be decoded and displayed in the chat. ```csharp new Attachment("Hello, base64!", encoding: AttachmentEncoding.Base64) ``` -------------------------------- ### Example Module with Permissions Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/permissions.md This C# snippet demonstrates how to define permissions for application commands within a module. It shows how to set required permissions and whether a command can be used in DMs. ```csharp using DSharpPlus.SlashCommands; using DSharpPlus.SlashCommands.Attributes; using DSharpPlus.Entities; namespace Netcord.Examples.ApplicationCommands.Permissions; public class ExampleModule : ApplicationCommandModule { [SlashCommand("ping", "Replies with Pong!")] [SlashRequirePermissions(Permissions.ManageGuild)] [SlashRequireGuild] public async Task PingCommand(InteractionContext ctx) { await ctx.CreateResponseAsync("Pong!"); } } ``` -------------------------------- ### Use a Custom Command Module Base Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/custom-module-bases-and-contexts.md Example of how to use a custom command module base in your command module. This demonstrates accessing custom properties and methods. ```csharp using Discord.Commands; using Example.Modules.Bases; namespace Example.Modules; public class ExampleModule : CustomCommandModule { [Command("custominfo")] public async Task CustomInfoAsync() { await ReplyAsync($"Custom Property: {CustomProperty}"); await SayAsync("This is a custom message!"); } } ``` -------------------------------- ### Use a Custom Command Context Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/custom-module-bases-and-contexts.md Example of how to use a custom command context in your command module. This demonstrates accessing custom properties and methods of the custom context. ```csharp using Discord.Commands; using Example.Contexts; namespace Example.Modules; [Name("Custom Context Example")] public class ExampleModule : ModuleBase { [Command("customcontextinfo")] public async Task CustomContextInfoAsync() { await ReplyAsync($"Custom Context Property: {Context.CustomContextProperty}"); await Context.ReplyCustomAsync("This is a custom reply!"); } } ``` -------------------------------- ### API Usage for MessageProperties Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Shows a sample of how to use the API for MessageProperties. This is a direct usage example for constructing message properties. ```csharp await channel.SendMessageAsync(new MessageProperties { Content = "Hello World!" }); ``` -------------------------------- ### Manually Create ShardedGatewayClient Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sharding.md For a bare-bones setup, manually create an instance of ShardedGatewayClient. Its API is similar to GatewayClient, managing multiple shard instances. ```cs using NetCord; using NetCord.Gateway; var client = new ShardedGatewayClient(new Token("YOUR_BOT_TOKEN")); await client.StartAsync(); await Task.Delay(-1); await client.StopAsync(); ``` -------------------------------- ### Module-based Command for Greeting Source: https://github.com/netcorddev/netcord/blob/main/Resources/NuGet/README.md Implements a slash command using a module-based approach for more organized command structures. This example defines a 'greet' command within a module. ```cs public class GreetingModule : ApplicationCommandModule { [SlashCommand("greet", "Greet someone!")] public string Greet(User user) => $"{Context.User} greets {user}!"; } ``` -------------------------------- ### Guild Commands Module with Subcommands Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/subcommands.md Example demonstrating the structure of a module for guild commands, including the definition and usage of subcommands. Ensure subcommands are only used with slash commands. ```csharp using Netcord.Addons.ApplicationCommands; using Netcord.Gateway; using Netcord.Gateway.Guilds; namespace Example.GuildCommandsModule; public class GuildCommandsModule : ApplicationCommandsModule { [SlashCommand("test", "A test command.")] public Task TestCommandAsync(IGuildCommandContext context) { return context.RespondAsync("Hello World!"); } [SlashCommand("sub", "A command with subcommands.")] public class SubCommandGroup : ApplicationCommandsModule { [SubCommand("one", "The first subcommand.")] public Task SubCommandOneAsync(IGuildCommandContext context) { return context.RespondAsync("Subcommand one executed."); } [SubCommand("two", "The second subcommand.")] public Task SubCommandTwoAsync(IGuildCommandContext context) { return context.RespondAsync("Subcommand two executed."); } } } ``` -------------------------------- ### Handle Button Interactions Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md Example of handling a button interaction. Ensure the custom ID matches the one used when creating the button. ```csharp using NetCord.Services.ComponentInteractions; [ComponentInteraction("MyButton")] public class ButtonModule : InteractionModule { [ButtonInteraction("MyButton")] public async Task OnButtonClick(ButtonInteractionContext context) { await context.RespondAsync("Button clicked!"); } } ``` -------------------------------- ### Adding Embeds (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Example of how to add embeds to a message using the classic syntax. A message can contain up to 10 embeds. ```csharp await channel.SendMessageAsync("Hello World!", new Embed[] { new EmbedBuilder() .WithTitle("Example Embed") .WithDescription("This is a sample embed.") .Build() }); ``` -------------------------------- ### Variable Number of Parameters Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/parameters.md Shows how to use the 'params' keyword to accept a variable number of parameters. This allows for dynamic argument lists, such as deleting multiple messages based on IDs. ```csharp await DeleteMessagesAsync(931274046312701962, 963913427661766717); ``` -------------------------------- ### Add Component Interactions using Bare Bones Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md Instantiate ComponentInteractionService and add component interactions. This example uses ButtonInteractionContext. ```csharp using NetCord.Services.ComponentInteractions; var client = new Client(TokenType.Bot, "YOUR_TOKEN"); var interactionService = new ComponentInteractionService(client); interactionService.AddInteraction("MyComponentInteraction"); ``` -------------------------------- ### API Usage for InteractionMessageProperties Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Provides an example of using the API for InteractionMessageProperties, typically used in response to user interactions. ```csharp await context.RespondAsync(new InteractionMessageProperties { Content = "Hello World!" }); ``` -------------------------------- ### Sending Voice Data Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/voice.md Demonstrates how to send voice data using a VoiceClient. Ensure native dependencies are installed and the VoiceClient is properly managed. ```csharp using System; using System.Buffers; using System.IO; using System.Threading; using System.Threading.Tasks; using Discord.Net; using Discord.Net.Rest; using Discord.Net.WebSockets; using Discord.Net.Voice; using Discord.Net.Audio; namespace NetCord.Hosting.Services.Voice; public class VoiceModule { private readonly DiscordClient _client; public VoiceModule(DiscordClient client) { _client = client; } [SlashCommand("join", "Joins the voice channel you are in.")] public async Task JoinAsync(InteractionContext context) { var guild = context.Guild; var user = context.User; if (guild is null || user is null) { await context.RespondAsync("This command can only be used in a guild."); return; } var voiceState = user.GetVoiceState(); if (voiceState?.Channel is null) { await context.RespondAsync("You are not in a voice channel."); return; } var voiceClient = await _client.JoinVoiceChannelAsync(voiceState.Channel); await context.RespondAsync($"Joined {{voiceState.Channel.Name}}."); } [SlashCommand("leave", "Leaves the voice channel.")] public async Task LeaveAsync(InteractionContext context) { var guild = context.Guild; var user = context.User; if (guild is null || user is null) { await context.RespondAsync("This command can only be used in a guild."); return; } var voiceState = user.GetVoiceState(); if (voiceState?.Channel is null) { await context.RespondAsync("You are not in a voice channel."); return; } await _client.LeaveVoiceChannelAsync(voiceState.Channel); await context.RespondAsync("Left the voice channel."); } [SlashCommand("play", "Plays a voice file.")] public async Task PlayAsync(InteractionContext context, string fileName) { var guild = context.Guild; var user = context.User; if (guild is null || user is null) { await context.RespondAsync("This command can only be used in a guild."); return; } var voiceState = user.GetVoiceState(); if (voiceState?.Channel is null) { await context.RespondAsync("You are not in a voice channel."); return; } var voiceClient = await _client.JoinVoiceChannelAsync(voiceState.Channel); var audioService = new AudioService(voiceClient); await using var fileStream = File.OpenRead(fileName); await audioService.SendAsync(fileStream); await context.RespondAsync($"Playing {{fileName}}."); } [SlashCommand("stop", "Stops playing voice.")] public async Task StopAsync(InteractionContext context) { var guild = context.Guild; var user = context.User; if (guild is null || user is null) { await context.RespondAsync("This command can only be used in a guild."); return; } var voiceState = user.GetVoiceState(); if (voiceState?.Channel is null) { await context.RespondAsync("You are not in a voice channel."); return; } await _client.LeaveVoiceChannelAsync(voiceState.Channel); await context.RespondAsync("Stopped playing voice."); } } ``` -------------------------------- ### Minimal API Slash Command with DI Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/dependency-injection.md Parameters preceding the context parameter are treated as services in minimal APIs. This example shows injecting a service into a slash command. ```cs public async Task SlashCommand( MyService service, string message ) { return Results.Ok(service.Process(message)); } ``` -------------------------------- ### Specify Intents with .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/events/intents.md Configure gateway intents when using the .NET Generic Host. This example shows how to add intents to the Discord client configuration. ```csharp builder.Services.AddDiscordClient(new DiscordConfig { Token = "YOUR_BOT_TOKEN", Intents = GatewayIntents.Guilds | GatewayIntents.DirectMessages }); ``` -------------------------------- ### Upload attachment directly to Google Cloud Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This example demonstrates uploading an attachment directly to Google Cloud Platform. Note that Discord does not guarantee stability for this feature. ```csharp new Attachment("Hello, Google!", uploadTo: new GoogleCloudUpload("your-bucket-name", "your-gcs-path")) ``` -------------------------------- ### Complete Bot Code (Bare Bones) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/getting-started/making-a-bot.md This is the complete code for a bot using the Bare Bones approach, including client creation, logging, and starting the bot. ```csharp using NetCord; using NetCord.Gateway; using NetCord.Logging; var client = new GatewayClient(new Token(TokenType.Bot, "YOUR_BOT_TOKEN")); client.UseDefaultLogging(); await client.StartAsync(); await Task.Delay(-1); ``` -------------------------------- ### Define Optional Parameters with Default Values Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/parameters.md Use default values to mark parameters as optional. This example shows how to unban a user with or without a reason. ```csharp public async Task UnbanAsync(ulong userId, string reason = null) { // ... implementation to unban user } ``` -------------------------------- ### Create Custom Precondition Attribute Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Define a custom precondition by inheriting from `PreconditionAttribute`. This example shows how to create an attribute that requires the user to have an animated avatar. ```csharp using NetCord.Services.ApplicationCommands; namespace Preconditions.Preconditions; public class RequireAnimatedAvatarAttribute : PreconditionAttribute { public override async ValueTask CheckAsync(ApplicationCommandContext context) { if (context.User.GetAvatarUrl(Core.ImageFormat.Gif) is not null) { return PreconditionResult.FromSuccess(); } return PreconditionResult.FromError("User must have an animated avatar."); } } ``` -------------------------------- ### Setting Up HTTP Interactions in C# Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/http-interactions.md Configure your ASP.NET Core host builder to handle Discord HTTP interactions by adding the Discord REST client and mapping the HTTP interactions route. This snippet shows the essential setup for receiving interactions. ```csharp using NetCord.Hosting; using NetCord.Hosting.AspNetCore; using NetCord.Hosting.Services; var builder = WebApplication.CreateBuilder(args); // Add Discord REST client and configure HTTP interactions endpoint. builder.Services.AddDiscordRest(builder.Configuration["Discord:Token"]!) .UseHttpInteractions("/interactions"); // Add application command service with preconfigured HTTP contexts. builder.Services.AddHttpApplicationCommands(); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Remainder Parameter Example Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/parameters.md Demonstrates how to use a remainder parameter to capture any number of colons in a custom ID. This is useful for passing strings that might contain colons. ```csharp await RespondWithEmbedAsync("testing 1 2 3"); ``` -------------------------------- ### Apply Parameter Precondition to Command Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Apply a custom parameter precondition attribute to a command parameter. This example uses the `MustContainAttribute` on the 'name' parameter of the 'HelloCommand'. ```csharp [SlashCommand("hello", "Says hello.")] public async Task HelloCommand([MustContain("world")] string name) { await RespondAsync($"Hello {name}."); } ``` -------------------------------- ### Create Bug Report with Optional Parameters Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/parameters.md This example demonstrates creating a bug report with optional parameters like body and category. Omit parameters by using consecutive colons or a trailing colon. ```csharp public async Task BugReportAsync(string title, string body = null, string category = null) { // ... implementation to create bug report } ``` -------------------------------- ### Apply Precondition to Command Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Apply a custom precondition attribute directly to a command to enforce the condition only for that specific command. This example applies `RequireAnimatedAvatarAttribute` to the `AvatarCommand`. ```csharp [RequireAnimatedAvatar] [SlashCommand("avatar", "Get user avatar.")] public async Task AvatarCommand(User? user = null) { user ??= User; await RespondAsync(user.GetDisplayAvatarUrl()); } ``` -------------------------------- ### Apply Precondition to Minimal API Command Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Apply a custom precondition attribute to a minimal API-style command. This example shows how to apply `RequireAnimatedAvatarAttribute` to a command defined using the minimal API. ```csharp app.MapGet("/avatar", [RequireAnimatedAvatar] async (IUserService users) => { var user = await users.GetUserAsync(Context.User.Id); return Results.Ok(user.GetDisplayAvatarUrl()); }); ``` -------------------------------- ### Serve Project Documentation Source: https://github.com/netcorddev/netcord/blob/main/Documentation/README.md Run this command to serve the generated documentation locally, allowing you to preview it. ```bash npm run serve ``` -------------------------------- ### Set Message Flags (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Set message flags using the classic syntax. This example demonstrates setting flags to suppress embeds from URLs and make the message silent. ```cs MessageFlags.SuppressEmbeds | MessageFlags.Silent; ``` -------------------------------- ### Apply Precondition to Module Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Apply a custom precondition attribute to an entire module to enforce the condition for all commands within that module. This example applies the `RequireAnimatedAvatarAttribute` to `ButtonModule`. ```csharp [RequireAnimatedAvatar] public class ButtonModule : ApplicationModule { [Interaction("button")] public async Task ButtonInteractionAsync() { await RespondAsync("Hello World!"); } } ``` -------------------------------- ### Build Project Documentation Source: https://github.com/netcorddev/netcord/blob/main/Documentation/README.md Execute this command to generate the project's documentation. ```bash npm run build ``` -------------------------------- ### Apply Parameter Precondition to Minimal API Command Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Apply a custom parameter precondition attribute to a parameter in a minimal API-style command. This example applies `MustContainAttribute` to the 'name' parameter. ```csharp app.MapGet("/hello", [MustContain("world")] async (string name) => Results.Ok($"Hello {name}.")); ``` -------------------------------- ### Create Custom Parameter Precondition Attribute Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/preconditions.md Define a custom precondition attribute for parameters by inheriting from `ParameterPreconditionAttribute`. This example creates an attribute that ensures a string parameter contains a specific substring. ```csharp using NetCord.Services.ApplicationCommands; namespace Preconditions.ParameterPreconditions; public class MustContainAttribute : ParameterPreconditionAttribute { private readonly string _value; public MustContainAttribute(string value) { _value = value; } public override ValueTask CheckAsync(ApplicationCommandParameter parameter, ApplicationCommandContext context) { if (parameter.Value is string str && str.Contains(_value)) { return PreconditionResult.FromSuccess(); } return PreconditionResult.FromError($"Parameter must contain '{_value}'."); } } ``` -------------------------------- ### Minimal API-style Bot with Slash Command Source: https://github.com/netcorddev/netcord/blob/main/Resources/NuGet/README.md Sets up a bot using a minimal API-style approach for slash commands. Use this for simple, direct command implementations. ```cs var builder = Host.CreateDefaultBuilder(args) .UseDiscordGateway() .UseApplicationCommands(); var host = builder.Build(); host.AddSlashCommand("square", "Square!", (int a) => $"{a}² = {a * a}"); await host.RunAsync(); ``` -------------------------------- ### Creating String Menus (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This snippet demonstrates creating string menus using Netcord's fluent syntax. It's a more concise way to build messages. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().WithContent("Hello World!").AddComponents(ActionRowBuilder.Create(SelectMenuBuilder.Create("Select a string").AddOptions(SelectMenuOptionBuilder.Create("Option 1", "1")).AddOptions(SelectMenuOptionBuilder.Create("Option 2", "2"))))) ``` -------------------------------- ### Build Project Templates Only Source: https://github.com/netcorddev/netcord/blob/main/Documentation/README.md Use this command if you only need to build the project's templates without generating full documentation. ```bash npm run build-templates ``` -------------------------------- ### Respond to an interaction with a message Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Use InteractionCallback.Message to create a message response. For advanced message options, refer to the 'Sending Messages' guide. ```csharp await context.Interaction.SendResponseAsync(InteractionCallback.Message("Hello world!")); ``` -------------------------------- ### Creating User Menus (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Create user menus using classic syntax, allowing users to select other users. Default users can be specified. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(new ActionRowBuilder().AddComponents(new UserSelectMenuBuilder("Select a user")))) ``` -------------------------------- ### Creating Channel Menus (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Use classic syntax to create menus that include channels as options. Supports filtering by channel type and specifying default channels. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(new ActionRowBuilder().AddComponents(new ChannelSelectMenuBuilder("Select a channel")))) ``` -------------------------------- ### Listen to MessageCreate Event (Bare Bones) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/events/first-events.md Add this code before client.StartAsync() to listen for the MessageCreate event. This is a simple way to handle events without a hosting framework. ```csharp client.MessageCreate += async (message) => { await message.Channel.SendMessageAsync(" } // Message: " + message.Content); }; ``` -------------------------------- ### Creating Role Menus (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Use classic syntax to create role menus, which allow users to select roles. Default roles can also be specified. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(new ActionRowBuilder().AddComponents(new RoleSelectMenuBuilder("Select a role")))) ``` -------------------------------- ### Customizing Embeds (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Demonstrates how to customize embeds using the classic syntax in C#. ```csharp var embed = new Embed() { Title = "Embed Title", Description = "Embed Description", Color = new Color(255, 0, 0) }; await channel.SendMessageAsync(embed: embed); ``` -------------------------------- ### Bare Bones: Add Commands and Handler Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/introduction.md Instantiate CommandService and add commands and a command handler for basic command processing. ```csharp using NetCord; using NetCord.Services; using NetCord.Services.Commands; var client = new Client("YOUR_BOT_TOKEN"); var commandService = new CommandService(); commandService.AddModules(typeof(Program).Assembly); client.MessageReceived += async (message) => { if (message.Author.IsBot) return; await commandService.ExecuteAsync(message); }; client.Start(); ``` -------------------------------- ### Add Application Commands with .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/introduction.md Use `AddApplicationCommands` to integrate the application command service into your host builder. Then, utilize `AddSlashCommand*`, `AddUserCommand*`, or `AddMessageCommand*` for minimal API command additions, or `AddModules` to load commands from an assembly. ```csharp using NetCord.Hosting.Services.ApplicationCommands; var host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.AddApplicationCommands(); services.AddSlashCommand("ping", async interaction => await interaction.RespondAsync("Pong!")); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### Customizing Embeds (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Demonstrates how to customize embeds using the fluent syntax in C#. ```csharp await channel.SendMessageAsync(new EmbedBuilder() { Title = "Embed Title", Description = "Embed Description", Color = new Color(255, 0, 0) }.Build()); ``` -------------------------------- ### Responding with a Modal with Options (Classic) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Provide additional options like placeholder text, default value, and required status for modal inputs using the classic syntax. ```csharp await RespondWithModalAsync(new ModalParameters("My Modal") { new TextInputParameters("Short Input", TextInputStyle.Short) { Placeholder = "Enter text here.", DefaultValue = "Default text.", IsRequired = true }, new TextInputParameters("Paragraph Input", TextInputStyle.Paragraph) { Placeholder = "Enter a longer text here.", DefaultValue = "Default paragraph.", IsRequired = false } }); ``` -------------------------------- ### Responding with Autocomplete (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Use this classic syntax to respond to autocomplete interactions. Ensure the correct interaction type is handled. ```cs await RespondAutocompleteAsync(new ApplicationCommandOptionChoice[] { new("Option1", "value1"), new("Option2", "value2") }); ``` -------------------------------- ### Creating String Menus (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Use this snippet to create string menus with classic syntax. Ensure you have the necessary imports. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().WithContent("Hello World!").AddComponents(new ActionRowBuilder().AddComponents(new SelectMenuBuilder().WithPlaceholder("Select a string").AddOptions(new SelectMenuOptionBuilder("Option 1", "1")).AddOptions(new SelectMenuOptionBuilder("Option 2", "2"))))) ``` -------------------------------- ### Using IMessageProperties (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Demonstrates how to use IMessageProperties with the classic syntax for message composition. This approach is useful when you need fine-grained control over message properties. ```csharp using var client = new DiscordClient(new DiscordConfig { Token = "YOUR_TOKEN" }); client.MessageCreated += async (s, e) => { await e.Message.RespondAsync("Hello World!"); }; await client.ConnectAsync(); await Task.Delay(-1); ``` -------------------------------- ### Creating Mentionable Menus (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Create mentionable menus using classic syntax, which include users and roles as options. You can specify default users and roles. ```csharp await Context.Channel.SendMessageAsync(new DiscordMessageBuilder().AddComponents(new ActionRowBuilder().AddComponents(new MentionableSelectMenuBuilder("Select a user or role")))) ``` -------------------------------- ### Configure Select Menus (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Configure select menus using the classic syntax. This allows for specifying placeholders, min/max options, and disabling the menu. ```cs new SelectMenuBuilder().WithPlaceholder("Select an option").WithMinValues(1).WithMaxValues(1).WithCustomId("my_select_menu")); ``` -------------------------------- ### Using IMessageProperties (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Illustrates the use of IMessageProperties with the fluent syntax for sending messages. This method offers a more concise way to build message objects. ```csharp await e.Message.RespondAsync(new MessageProperties { Content = "Hello World!" }); ``` -------------------------------- ### Respond to Interaction with Classic Syntax Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Use this classic syntax to respond to an interaction after deferring it. Ensure the interaction is deferred before calling this. ```cs await context.RespondAsync("Hello World!"); ``` -------------------------------- ### Specify Intents in Bare Bones Application Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/events/intents.md Configure gateway intents for a bare-bones NetCord application. This snippet demonstrates direct instantiation and intent configuration. ```csharp var client = new DiscordClient(new DiscordConfig { Token = "YOUR_BOT_TOKEN", Intents = GatewayIntents.Guilds | GatewayIntents.DirectMessages }); ``` -------------------------------- ### Adding Attachments (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Demonstrates how to add file attachments to a message using classic syntax. ```csharp var file = new FileAttachment("path/to/your/file.txt"); await channel.SendMessageAsync("File attached!", attachments: new FileAttachment[] { file }); ``` -------------------------------- ### Configure Select Menus (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Configure select menus using the fluent syntax. This method provides options for placeholders, minimum and maximum selectable items, and disabling the menu. ```cs builder.WithPlaceholder("Select an option").WithMinValues(1).WithMaxValues(1).WithCustomId("my_select_menu")); ``` -------------------------------- ### Defining Command Aliases Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/aliases.md Shows how to define aliases for a command. This is useful for providing alternative names or shorter versions for commands. ```csharp public const string Alias = "alias"; ``` -------------------------------- ### Configure Command Prefix in appsettings.json Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/introduction.md Specify the command prefix in the configuration file, such as appsettings.json. ```json { "NetCord": { "Prefix": "!" } } ``` -------------------------------- ### Responding with a Modal (Classic) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Create a modal callback to present a form to the user using the classic syntax. Modals can include up to five components. ```csharp await RespondWithModalAsync(new ModalParameters("My Modal") { new TextInputParameters("Short Input", TextInputStyle.Short) { Placeholder = "Enter text here." } }); ``` -------------------------------- ### Add Commands with .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/introduction.md Use CommandServiceServiceCollectionExtensions.AddCommands to add the command service to your host builder. Then, use CommandServiceHostExtensions.AddCommand* or ServicesHostExtensions.AddModules to add commands. ```csharp using NetCord.Hosting.Services.Commands; var host = Host.CreateDefaultBuilder(args) .UseNetCord("YOUR_BOT_TOKEN") .ConfigureServices(services => { services.AddCommands(); }) .Build(); host.Run(); ``` -------------------------------- ### Responding with a Modal with Options (Fluent) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Provide additional options like placeholder text, default value, and required status for modal inputs using the fluent syntax. ```csharp await RespondWithModalAsync(x => { x.Title = "My Modal"; x.AddComponent(new TextInputComponent("Short Input", TextInputStyle.Short) { Placeholder = "Enter text here.", DefaultValue = "Default text.", IsRequired = true }); x.AddComponent(new TextInputComponent("Paragraph Input", TextInputStyle.Paragraph) { Placeholder = "Enter a longer text here.", DefaultValue = "Default paragraph.", IsRequired = false }); }); ``` -------------------------------- ### Defining Message Content (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Demonstrates how to define the main text content of a message using the classic syntax. ```csharp await channel.SendMessageAsync("Hello World!"); ``` -------------------------------- ### Static Linking Native Libraries on Windows Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/installing-native-dependencies.md Configure your project to statically link native libraries on Windows. Ensure the paths to 'libdave', 'libsodium', and 'opus' are correctly specified. ```xml ``` -------------------------------- ### Adding Components (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Add interactive components to messages using the classic syntax. ```csharp Components = new[] { new ActionRow(new Button("Click Me!", ButtonStyle.Success, new Emoji("👍"))), new ActionRow(SelectMenuBuilder.Create()) } ``` -------------------------------- ### Responding with a Modal (Fluent) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Create a modal callback to present a form to the user using the fluent syntax. Modals can include up to five components. ```csharp await RespondWithModalAsync(x => { x.Title = "My Modal"; x.AddComponent(new TextInputComponent("Short Input", TextInputStyle.Short) { Placeholder = "Enter text here." }); }); ``` -------------------------------- ### Add ShardedGatewayClient with .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sharding.md Use AddDiscordShardedGateway to add the ShardedGatewayClient when using the .NET Generic Host. This sets up the sharded client for your bot. ```cs using NetCord.Hosting.Gateway; var host = Host.CreateDefaultBuilder(args) .UseNetCordShardedGateway() .Build(); host.Run(); ``` -------------------------------- ### Configure Bot Token in appsettings.json Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/getting-started/making-a-bot.md Store your bot's token in an appsettings.json file for better configuration management. Ensure the token is kept secure. ```json { "Discord": { "Token": "YOUR_BOT_TOKEN" } } ``` -------------------------------- ### Adding Components (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Add interactive components to messages using the fluent syntax. ```csharp .WithButton("Click Me!", ButtonStyle.Success, new Emoji("👍")) .WithSelectMenu(SelectMenuBuilder.Create()) ``` -------------------------------- ### Add Discord Gateway to .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/getting-started/making-a-bot.md Use this method to add the bot to the host when using the .NET Generic Host approach. Requires Microsoft.Extensions.Hosting and NetCord.Hosting packages. ```csharp using NetCord.Hosting.Gateway; var builder = Host.CreateDefaultBuilder(args) .UseNetCordGateway() .Build(); await builder.RunAsync(); ``` -------------------------------- ### Listen to MessageReactionAdd Event (Bare Bones) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/events/first-events.md Add this code to listen for the MessageReactionAdd event. This approach is suitable for basic event handling without a hosting framework. ```csharp client.MessageReactionAdd += async (message, reaction, user) => { await message.Channel.SendMessageAsync($ " } // User {user} reacted to message {message.Id} with {reaction.Emoji}"); }; ``` -------------------------------- ### Respond to Interaction with Fluent Syntax Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Use this fluent syntax to respond to an interaction after deferring it. Ensure the interaction is deferred before calling this. ```cs await context.Interaction.RespondAsync("Hello World!"); ``` -------------------------------- ### Responding with Autocomplete (String) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Respond to autocomplete interactions by providing a list of options for string parameters. ```csharp await RespondWithAutocompleteAsync(new AutocompleteResult() { "Option 1", "Option 2" }); ``` -------------------------------- ### Adding Embeds (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Demonstrates adding embeds to a message using the fluent syntax. This approach allows for a more streamlined way to include rich content. ```csharp await channel.SendMessageAsync(new MessageProperties { Content = "Hello World!", Embeds = new[] { new EmbedBuilder() .WithTitle("Example Embed") .WithDescription("This is a sample embed.") .Build() } }); ``` -------------------------------- ### Define a Custom Command Module Base Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/custom-module-bases-and-contexts.md Create a custom module base to add methods and properties to your commands. You can also apply precondition attributes on them. ```csharp using Discord.Commands; namespace Example.Modules.Bases; public class CustomCommandModule : ModuleBase { // Add custom methods and properties here public string CustomProperty => "Hello from custom module base!"; public Task SayAsync(string message) { return Context.Channel.SendMessageAsync(message); } } ``` -------------------------------- ### Create a basic interaction response Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Use the InteractionCallback class to create a response and pass it to Interaction.SendResponseAsync. This is the fundamental way to respond to any interaction. ```csharp await context.Interaction.SendResponseAsync(new InteractionCallback("Hello world!")); ``` -------------------------------- ### Create a standard attachment Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md This code creates a basic attachment with text content. Attachments can be any readable stream. ```csharp new Attachment("Hello!") ``` -------------------------------- ### Setting Allowed Mentions to All (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Configures message to allow all mentions using classic syntax. ```csharp var messageProperties = new MessageProperties() { AllowedMentions = AllowedMentionsProperties.All }; await channel.SendMessageAsync("Hello World!", messageProperties); ``` -------------------------------- ### Add Component Interactions to .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/component-interactions/introduction.md Use AddComponentInteractions to add a component interaction service to your host builder. Then, use AddComponentInteraction or AddModules to add component interactions. ```csharp using NetCord.Hosting.Services.ComponentInteractions; var host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.AddComponentInteractions(); }) .Build(); host.AddComponentInteraction("MyComponentInteraction"); host.AddModules(Assembly.GetExecutingAssembly()); host.Run(); ``` -------------------------------- ### Application Command Handler Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/introduction.md A basic command handler for application commands. Ensure the interaction type matches your context if not using `ApplicationCommandContext`. ```csharp var commands = new ApplicationCommandService(); // Add commands here client.InteractionCreated += async interaction => { if (interaction is SlashCommandInteraction slashCommand) { await commands.ExecuteAsync(slashCommand); } }; ``` -------------------------------- ### Static Linking Native Libraries on Linux and MacOS Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/installing-native-dependencies.md Configure your project to statically link native libraries on Linux and MacOS. Specify the correct paths to 'libdave', 'libsodium', and 'opus'. ```xml ``` -------------------------------- ### Variable Number of Parameters Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/parameters.md Use the `params` keyword to accept a variable number of parameters in a command. ```csharp public async Task ExampleModule(params string[] args) ``` -------------------------------- ### Responding with a Pong Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Use InteractionCallback.Pong to respond to ping HTTP interactions from Discord, verifying endpoint availability. The NetCord.Hosting.AspNetCore package handles this automatically. ```cs await RespondAsync(InteractionCallback.Pong); ``` -------------------------------- ### Command Overloading with Priority Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/parameters.md Overload commands to accept different parameter types. Use `CommandAttribute.Priority` to set a priority for each overload. ```csharp [Command("add"), Priority(1)] public async Task AddAsync(int a, int b) { await Context.Message.ReplyAsync($"{a} + {b} = {a + b}"); } [Command("add"), Priority(0)] public async Task AddAsync(double a, double b) { await Context.Message.ReplyAsync($"{a} + {b} = {a + b}"); } ``` -------------------------------- ### Defining Action Rows (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Define action rows containing buttons for messages using the fluent syntax. ```csharp .WithButton("Primary", ButtonStyle.Primary) .WithButton("Secondary", ButtonStyle.Secondary) .WithButton("Success", ButtonStyle.Success) .WithButton("Danger", ButtonStyle.Danger) .WithLinkButton("Link", "https://example.com") ``` -------------------------------- ### Defining Action Rows (Classic Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Define action rows containing buttons for messages using the classic syntax. ```csharp Components = new IComponent[] { new ActionRow( new Button("Primary", ButtonStyle.Primary), new Button("Secondary", ButtonStyle.Secondary), new Button("Success", ButtonStyle.Success), new Button("Danger", ButtonStyle.Danger), new Button("Link", ButtonStyle.Link, "https://example.com") ) } ``` -------------------------------- ### Setting Allowed Mentions to All (Fluent Syntax) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Configures message to allow all mentions using fluent syntax. ```csharp await channel.SendMessageAsync("Hello World!", new MessageProperties() { AllowedMentions = AllowedMentionsProperties.All }); ``` -------------------------------- ### Add Gateway Handlers with .NET Generic Host Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/events/first-events.md Use this extension method to register all event handlers within a specified assembly for the .NET Generic Host. Ensure you have implemented the appropriate IGatewayHandler interfaces. ```csharp using NetCord.Hosting.Gateway; var builder = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.AddGatewayServices(token => { // You can configure your client here }); services.AddGatewayHandlers(typeof(Program).Assembly); }); await builder.Build().RunAsync(); ``` -------------------------------- ### Responding with Autocomplete (Numeric) Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/responding-to-interactions.md Respond to autocomplete interactions by providing a list of options for numeric parameters. ```csharp await RespondWithAutocompleteAsync(new AutocompleteResult() { 100, 200 }); ``` -------------------------------- ### Module Constructor Injection Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/dependency-injection.md Inject services into module constructors for use within command logic. Modules are created as transient services for each command/interaction. ```cs public class DataModule : Module { public DataModule(MyService service) { /* ... */ } } ``` -------------------------------- ### Optional Parameters Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/text-commands/parameters.md Mark parameters as optional by providing them with a default value. ```csharp public async Task ExampleModule(string arg1, int arg2 = 5) ``` -------------------------------- ### Optional Slash Command Parameters Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/services/application-commands/parameters.md Mark parameters as optional by providing a default value. This is useful for parameters that do not always require user input. ```csharp public async Task ExampleModule(string required, string optional = "default") => await RespondAsync($"Required: {required}, Optional: {optional}"); ``` -------------------------------- ### Configuring Public Key in appsettings.json Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/http-interactions.md Store your Discord bot's public key in the appsettings.json file for secure access. This key is used by the Discord API to verify incoming requests. ```json { "Discord": { "Token": "YOUR_BOT_TOKEN", "PublicKey": "YOUR_PUBLIC_KEY" } } ``` -------------------------------- ### Add title and description to an attachment Source: https://github.com/netcorddev/netcord/blob/main/Documentation/guides/basic-concepts/sending-messages.md Customize attachments by adding titles and descriptions using the `AttachmentProperties`. ```csharp new Attachment("Hello, world!", properties: new AttachmentProperties() { Title = "My Attachment Title", Description = "This is a description for my attachment." }) ```