Skip to content

Feature Examples

SentorX edited this page Nov 5, 2026 · 2 revisions

Feature Examples

Every feature here has a simple example to get you started and a going further example that looks more like a real bot. Copy one, run it, then change it.

New to Discord bots? Start with the Beginner's Guide, then come back here.

All examples go inside a class in your project, like this. You don't need to register anything: the library finds your commands when you build.

using SimpleDiscordNet;
using SimpleDiscordNet.Commands;
using SimpleDiscordNet.Entities;
using SimpleDiscordNet.Events;
using SimpleDiscordNet.Extensions;
using SimpleDiscordNet.Primitives;

public sealed class MyCommands
{
    [SlashCommand("hello", "Say hello")]
    public string Hello() => "Hello!";
}

Table of Contents

Commands

Buttons and Forms

Messages

Your Bot


Replying

The easiest way to reply is to return what you want to say.

Simple:

[SlashCommand("ping", "Check that the bot is alive")]
public string Ping() => "Pong!";

Going further: return an embed, and use ctx to find out about the server.

[SlashCommand("server", "Show server info")]
public EmbedBuilder Server(InteractionContext ctx)
{
    return new EmbedBuilder()
        .WithTitle(ctx.Guild?.Name ?? "Direct message")
        .WithDescription($"Requested by {ctx.Username}")
        .WithColor(DiscordColor.Blue);
}

If your code needs to wait for something, use async and return a Task:

[SlashCommand("joke", "Tell a joke")]
public async Task<string> JokeAsync()
{
    await Task.Delay(500); // Pretend this loads a joke from a website
    return "Why do programmers prefer dark mode? Because light attracts bugs.";
}

More in Returning a Reply.

Taking Input

Add parameters to your method, and Discord asks the user for them.

Simple:

[SlashCommand("greet", "Greet someone")]
public string Greet(string name) => $"Hello, {name}!";

Going further: ask for a real user, and make an option optional by giving it a default value.

[SlashCommand("hug", "Hug a friend")]
public string Hug(DiscordUser friend, int times = 1)
{
    return $"You hugged {friend.Username} {times} time(s)!";
}

You can also use [CommandOption] to give an option a description and limits:

[SlashCommand("roll", "Roll a die")]
public string Roll(
    [CommandOption("sides", "How many sides", MinValue = 2, MaxValue = 100)] int sides = 6)
{
    return $"You rolled {Random.Shared.Next(1, sides + 1)}";
}

Choice Lists

Use an enum when the user should pick from a fixed list. Discord shows a dropdown, and you get the enum value back.

Simple:

public enum Size
{
    Small,
    Medium,
    Large
}

[SlashCommand("pizza", "Order a pizza")]
public string Pizza(Size size) => $"One {size} pizza coming up!";

Going further: give it a default, and use switch to act on the choice. Names like ExtraLarge are shown as "Extra Large".

public enum Topping
{
    Cheese,
    Pepperoni,
    ExtraCheese
}

[SlashCommand("order", "Order a pizza")]
public string Order(Topping topping = Topping.Cheese)
{
    decimal price = topping switch
    {
        Topping.ExtraCheese => 9.50m,
        Topping.Pepperoni => 9.00m,
        _ => 8.00m
    };

    return $"{topping} pizza: ${price}";
}

Private Replies

Add [Ephemeral] so only the person who ran the command sees the reply.

Simple:

[Ephemeral]
[SlashCommand("secret", "Only you can see this")]
public string Secret() => "This is just for you.";

Going further: put it on a class to make every command in it private.

[Ephemeral]
public sealed class AccountCommands
{
    [SlashCommand("balance", "Check your balance")]
    public string Balance() => "You have 100 coins.";

    [SlashCommand("inventory", "See your items")]
    public string Inventory() => "You have a sword and a shield.";
}

Cooldowns

A cooldown stops people from using a command too often. If they try too soon, the library tells them how long to wait.

Simple: each person can run this once every 10 seconds.

[Cooldown(10)]
[SlashCommand("fish", "Go fishing")]
public string Fish() => "You caught a fish!";

Going further: share a cooldown across the whole server, and write your own message.

[Cooldown(3600, Scope = CooldownScope.Guild, Message = "This server already rang the bell in the last hour.")]
[SlashCommand("bell", "Ring the server bell")]
public string Bell() => "🔔 Ding dong!";

Cooldowns are kept in memory, so they reset when your bot restarts.

Limiting Who Can Use a Command

These attributes run before your method. If one fails, your code doesn't run, and the user gets a private message saying why.

Simple: only people with the Moderator role.

[RequireRole("Moderator")]
[SlashCommand("warn", "Warn a member")]
public string Warn(DiscordUser user) => $"{user.Username} has been warned.";

Going further: combine checks. This needs a role, makes sure the bot can actually ban, and adds a cooldown.

[RequireRole("Moderator", "Admin")]
[RequireBotPermissions(PermissionFlags.BanMembers)]
[Cooldown(5)]
[SlashCommand("ban", "Ban a member")]
public async Task<string> BanAsync(DiscordMember member, string reason = "No reason given")
{
    await member.BanAsync(reason: reason);
    return $"Banned {member.User.Username}: {reason}";
}

[RequireOwner] limits a command to you, which is handy for bot admin commands:

[RequireOwner]
[SlashCommand("shutdown", "Stop the bot")]
public string Shutdown()
{
    Environment.Exit(0);
    return "Goodbye!";
}

You can also put any of these on a class to cover all its commands.

Choosing Where a Command Works

By default, Discord decides where your global commands appear. These attributes let you choose.

Simple: a command that only makes sense in a server.

[GuildOnly]
[SlashCommand("rules", "Show the server rules")]
public string Rules() => "Rule 1: Be kind.";

Going further: [UserInstallable] lets people add your command to their own Discord account and use it anywhere, even in servers your bot isn't in.

[UserInstallable]
[SlashCommand("coin", "Flip a coin")]
public string Coin() => Random.Shared.Next(2) == 0 ? "Heads" : "Tails";

For this to work, turn on User Install in the Developer Portal, under Installation. These attributes only apply to global commands, so use SyncGlobalCommandsAsync.

Translating Commands

Discord can show your commands in each user's language.

Simple:

[Localized("de", "hallo", "Sag hallo")]
[SlashCommand("hello", "Say hello")]
public string Hello() => "Hello!";

Going further: translate options too, and add as many languages as you like. Names must be lowercase with no spaces.

[Localized("de", "wetter", "Wetter abrufen")]
[Localized("fr", "meteo", "Voir la météo")]
[SlashCommand("weather", "Get the weather")]
public string Weather(
    [Localized("de", "stadt", "Welche Stadt?")]
    [Localized("fr", "ville", "Quelle ville ?")]
    string city)
{
    return $"It's sunny in {city}!";
}

This translates what users see in the command list. Your replies stay as you wrote them.

A Help Command

Add one line, and your bot gets a /help command listing all its slash commands. Put it at the top of any file, under the using lines.

Simple:

using SimpleDiscordNet.Commands;

[assembly: GenerateHelp]

Going further: choose the name and title. Long lists split into pages by themselves.

using SimpleDiscordNet.Commands;

[assembly: GenerateHelp(Name = "commands", Title = "What I Can Do", Description = "See everything I can do")]

Handling Errors

If your code throws an exception, the library logs it and tells the user something went wrong.

Simple: catch a problem you expect, and give a helpful message.

[SlashCommand("divide", "Divide two numbers")]
public string Divide(int a, int b)
{
    if (b == 0) return "You can't divide by zero!";
    return $"{a} / {b} = {a / b}";
}

Going further: handle every error in one place. Add this to any class, once per bot.

[OnCommandError]
public async Task OnErrorAsync(InteractionContext ctx, Exception ex)
{
    Console.WriteLine($"Something broke: {ex}");
    await ctx.RespondAsync("Sorry, something went wrong on our side.");
}

Buttons That Carry Data

A button's ID can hold information. Put {names} in your handler, and they arrive as parameters.

Simple:

[SlashCommand("vote", "Start a vote")]
public MessageBuilder Vote()
{
    return new MessageBuilder()
        .WithContent("Do you like pizza?")
        .WithButton("Yes", "vote:yes")
        .WithButton("No", "vote:no");
}

[ButtonHandler("vote:{choice}")]
public async Task OnVoteAsync(InteractionContext ctx, string choice)
{
    await ctx.RespondAsync($"You voted {choice}!", ephemeral: true);
}

Going further: a role menu. The role's ID travels inside the button, so one handler covers every button.

[SlashCommand("roles", "Show the role menu")]
public MessageBuilder Roles(DiscordRole gamer, DiscordRole artist)
{
    return new MessageBuilder()
        .WithContent("Pick your roles:")
        .WithButton(gamer.Name, $"role:{gamer.Id}")
        .WithButton(artist.Name, $"role:{artist.Id}");
}

[ButtonHandler("role:{roleId}")]
public async Task OnRoleAsync(InteractionContext ctx, ulong roleId)
{
    await ctx.Member!.AddRoleAsync(roleId);
    await ctx.RespondAsync("Role added!", ephemeral: true);
}

Asking Yes or No

ConfirmAsync shows Yes and No buttons, then waits for the answer right inside your command.

Simple:

[SlashCommand("reset", "Reset your score")]
public async Task<string> ResetAsync(InteractionContext ctx)
{
    bool sure = await ctx.ConfirmAsync("Are you sure?");
    return sure ? "Your score is reset." : "Nothing changed.";
}

Going further: offer several choices with ChooseAsync, and set your own time limit. It returns null if nobody answers.

[SlashCommand("quiz", "Answer a question")]
public async Task<string> QuizAsync(InteractionContext ctx)
{
    string? answer = await ctx.ChooseAsync("What's the capital of France?", ["Paris", "Rome", "Madrid"], TimeSpan.FromSeconds(20));

    return answer switch
    {
        null => "Time's up!",
        "Paris" => "Correct!",
        _ => "Not quite. It's Paris."
    };
}

Only the person who ran the command can answer.

Showing Pages

PaginateAsync splits long content into pages with ◀ and ▶ buttons.

Simple:

[SlashCommand("story", "Read a story")]
public async Task StoryAsync(InteractionContext ctx)
{
    await ctx.PaginateAsync(["Once upon a time...", "There was a bot.", "The end."]);
}

Going further: build a page of embeds from a list.

[SlashCommand("leaderboard", "See the top players")]
public async Task LeaderboardAsync(InteractionContext ctx)
{
    string[] players = ["Ann", "Bo", "Cy", "Di", "Ed", "Flo", "Gus"];

    var pages = players.Chunk(3).Select((group, index) => new EmbedBuilder()
        .WithTitle($"Leaderboard: page {index + 1}")
        .WithDescription(string.Join("\n", group)));

    await ctx.PaginateAsync(pages);
}

Call this last in your method, because it waits until the buttons time out.

Forms (Modals)

A modal is a pop-up form. Describe it as a class, open it, and receive it filled in.

Simple:

[Modal("Say something")]
public sealed class MessageForm
{
    [ModalText("Your message")]
    public string Text { get; set; } = "";
}

public sealed class FormCommands
{
    [NoDefer]
    [SlashCommand("say", "Open a form")]
    public Task SayAsync(InteractionContext ctx) => ctx.OpenModalAsync<MessageForm>();

    [ModalHandler]
    public string OnSubmit(MessageForm form) => $"You said: {form.Text}";
}

[NoDefer] is required on whatever opens a modal, because a modal has to be Discord's first response.

Going further: a bug report with a dropdown, an optional field and a checkbox, opened from a button.

[Modal("Report a bug")]
public sealed class BugForm
{
    [ModalText("What happened?", MaxLength = 100)]
    public string Title { get; set; } = "";

    [ModalText("How can we reproduce it?", Paragraph = true, Description = "Optional, but it really helps")]
    public string? Steps { get; set; }

    [ModalSelect("How bad is it?", "Minor:low", "Annoying:medium", "Broken:high")]
    public string Severity { get; set; } = "";

    [ModalCheckbox("Message me when it's fixed")]
    public bool Notify { get; set; }
}

public sealed class BugCommands
{
    [SlashCommand("support", "Get help")]
    public MessageBuilder Support()
        => new MessageBuilder().WithContent("Found a problem?").WithButton("Report a bug", "open_bug_form");

    [NoDefer]
    [ButtonHandler("open_bug_form")]
    public Task OpenAsync(InteractionContext ctx) => ctx.OpenModalAsync<BugForm>();

    [Ephemeral]
    [ModalHandler]
    public EmbedBuilder OnBug(BugForm report)
    {
        return new EmbedBuilder()
            .WithTitle($"Thanks! Logged: {report.Title}")
            .AddField("Severity", report.Severity, inline: true)
            .AddField("Updates", report.Notify ? "Yes" : "No", inline: true)
            .AddField("Steps", report.Steps ?? "None given");
    }
}

See Modals for every field type.

Layout Messages

Layout messages arrange text, pictures and buttons without an embed.

Simple:

[SlashCommand("welcome", "Show a welcome card")]
public MessageBuilder Welcome()
{
    return new MessageBuilder()
        .WithText("# Welcome!")
        .WithText("We're glad you're here.");
}

Going further: a status card in a colored box, with a button beside the text.

[SlashCommand("status", "Show server status")]
public MessageBuilder Status()
{
    var card = new Container(
            new TextDisplay("## Game Server"),
            new TextDisplay("🟢 Online with 12 players"),
            new Separator(),
            new Section("Want to join?", new Button("Get invite", "get_invite")))
        .WithColor(DiscordColor.Green);

    return new MessageBuilder().WithComponents(card);
}

A layout message can't also have embeds or a poll.

Polls

Simple:

[SlashCommand("lunch", "Vote on lunch")]
public MessageBuilder Lunch() => new MessageBuilder().WithPoll("What's for lunch?", "Pizza", "Tacos", "Sushi");

Going further: add emojis, let people pick several answers, and run it for two days.

[SlashCommand("gamenight", "Plan game night")]
public MessageBuilder GameNight()
{
    var poll = new PollBuilder("What should we play?")
        .AddAnswer("Chess", "♟️")
        .AddAnswer("Cards", "🃏")
        .AddAnswer("Trivia", "🧠")
        .WithDuration(hours: 48)
        .AllowMultipleAnswers();

    return new MessageBuilder().WithPoll(poll);
}

To end a poll early, call EndPollAsync on the message. See Polls.

Threads

A thread is a side conversation inside a channel.

Simple:

[SlashCommand("discuss", "Start a discussion")]
public async Task<string> DiscussAsync(InteractionContext ctx, string topic)
{
    await ctx.Channel!.CreateThreadAsync(topic);
    return $"Started a thread about {topic}.";
}

Going further: a support ticket in a private thread. The bot needs the Create Private Threads permission.

[RequireBotPermissions(PermissionFlags.CreatePrivateThreads)]
[Ephemeral]
[SlashCommand("ticket", "Open a support ticket")]
public async Task<string> TicketAsync(InteractionContext ctx, string problem)
{
    var thread = await ctx.Channel!.CreateThreadAsync($"Ticket: {ctx.Username}", isPrivate: true);

    await thread!.SendMessageAsync($"{DiscordFormatting.MentionUser(ctx.UserId.ToString())} A moderator will be with you soon.\n\nProblem: {problem}");
    return "Your ticket is open!";
}

Mentioning someone in a private thread adds them to it.

Forum Posts

In a forum channel, every message is a new post with a title.

Simple:

[SlashCommand("announce", "Post in the forum")]
public async Task<string> AnnounceAsync(DiscordChannel forum, string title, string text)
{
    await forum.CreateForumPostAsync(title, new MessageBuilder().WithContent(text));
    return "Posted!";
}

Going further: apply a tag and add an embed. Available_Tags lists a forum's tags.

[SlashCommand("patchnotes", "Post patch notes")]
public async Task<string> PatchNotesAsync(DiscordChannel forum, string version)
{
    if (!forum.IsForum) return "Pick a forum channel.";

    var post = new MessageBuilder().WithEmbed(new EmbedBuilder().WithTitle($"Version {version}"));

    var tag = forum.Available_Tags?.FirstOrDefault(t => t.Name == "Updates");
    if (tag is not null) post.WithAppliedTags(tag.Id.ToString());

    await forum.CreateForumPostAsync($"Patch notes {version}", post);
    return "Posted!";
}

Pinning and Forwarding

Both work well as a right-click command on a message.

Simple:

[MessageContextMenu("Pin This")]
public async Task<string> PinAsync(InteractionContext ctx)
{
    await ctx.TargetMessage!.PinAsync();
    return "Pinned!";
}

The bot needs the Pin Messages permission.

Going further: forward a message to another channel. Replace the number with your own channel's ID.

[Ephemeral]
[MessageContextMenu("Send to Mods")]
public async Task<string> SendToModsAsync(InteractionContext ctx)
{
    const ulong modChannelId = 123456789012345678;

    await ctx.TargetMessage!.ForwardAsync(modChannelId);
    return "Sent to the mods.";
}

Searching

Simple: find members by the start of their name.

[SlashCommand("find", "Find a member")]
public async Task<string> FindAsync(InteractionContext ctx, string name)
{
    var members = await ctx.Guild!.SearchMembersAsync(name, limit: 5);
    return string.Join(", ", members.Select(m => m.User.Username));
}

Going further: search messages. This needs the Read Message History permission and the Message Content intent.

[SlashCommand("search", "Search messages")]
public async Task<EmbedBuilder> SearchAsync(InteractionContext ctx, string text)
{
    var results = await ctx.Guild!.SearchMessagesAsync(text, limit: 5);

    var embed = new EmbedBuilder().WithTitle($"Results for \"{text}\"");
    foreach (var message in results)
    {
        embed.AddField(message.Author.Username, message.Content);
    }
    return embed;
}

Reacting to Events

Mark a method, and it runs when something happens on Discord. No slash command needed.

Simple:

[OnConnected]
public void Ready() => Console.WriteLine("My bot is online!");

Going further: answer messages and welcome new members. These need matching intents when you build your bot: GuildMessages and MessageContent for messages, and GuildMembers for joins.

[OnMessageCreated]
public async Task OnMessageAsync(SimpleDiscordNet.Models.MessageCreateEvent e)
{
    if (e.Author.Bot == true) return; // Don't reply to bots, including yourself

    if (e.Content.Contains("hello", StringComparison.OrdinalIgnoreCase))
    {
        await e.Channel.SendMessageAsync("Hello there!");
    }
}

[OnMemberJoined]
public async Task OnJoinAsync(MemberEvent e)
{
    await e.User.SendDMAsync($"Welcome to {e.Guild.Name}!");
}

A moderation log: post what happens to a staff channel. Replace the number with your own channel's ID. The bot needs the GuildBans, GuildMembers and Guilds intents for these. See Required Intents.

public sealed class ModLog(DiscordBot bot)
{
    private const ulong LogChannelId = 123456789012345678;

    [OnBanAdded]
    public Task OnBanAsync(BanEvent e)
        => bot.SendMessageAsync(LogChannelId, $"🔨 {e.User.Username} was banned.");

    [OnMemberLeft]
    public Task OnLeaveAsync(MemberEvent e)
        => bot.SendMessageAsync(LogChannelId, $"👋 {e.User.Username} left.");

    [OnChannelDeleted]
    public Task OnChannelGoneAsync(ChannelEvent e)
        => bot.SendMessageAsync(LogChannelId, $"🗑️ #{e.Channel.Name} was deleted.");
}

Voice activity: when ChannelId is empty, the person has left voice.

[OnVoiceStateUpdated]
public void OnVoice(VoiceStateUpdateEvent e)
{
    string action = e.ChannelId is null ? "left voice" : "joined voice";
    Console.WriteLine($"User {e.UserId} {action}");
}

Logging problems: catch errors from anywhere in your bot.

[OnError]
public void OnError(Exception ex) => Console.WriteLine($"Problem: {ex.Message}");

[OnDisconnected]
public void OnDrop() => Console.WriteLine("Disconnected. Reconnecting by itself...");

See Event Attributes for every event.

Bulk Bans

Ban up to 200 people in one go, which is useful during a raid.

Simple:

[RequireBotPermissions(PermissionFlags.BanMembers | PermissionFlags.ManageGuild)]
[SlashCommand("banpair", "Ban two users")]
public async Task<string> BanPairAsync(InteractionContext ctx, DiscordUser first, DiscordUser second)
{
    await ctx.Guild!.BulkBanAsync([first.Id, second.Id], reason: "Raid");
    return "Done.";
}

Going further: remove their recent messages too, and report what happened.

[RequireRole("Admin")]
[RequireBotPermissions(PermissionFlags.BanMembers | PermissionFlags.ManageGuild)]
[SlashCommand("raidban", "Ban a list of user IDs")]
public async Task<string> RaidBanAsync(InteractionContext ctx, string userIds)
{
    ulong[] ids = userIds.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(ulong.Parse).ToArray();

    var result = await ctx.Guild!.BulkBanAsync(ids, deleteMessageSeconds: 3600, reason: "Raid");

    return $"Banned {result!.Banned_Users.Length}, failed {result.Failed_Users.Length}.";
}

Using Services

As a bot grows, you'll want to share things like a database or settings between commands. Ask for them in your class's constructor.

Simple: the bot itself is always available.

public sealed class StatusCommands(DiscordBot bot)
{
    [SlashCommand("botname", "Show the bot's name")]
    public string BotName() => $"I'm {bot.BotUser?.Username}!";
}

Going further: share your own class. This uses Microsoft.Extensions.DependencyInjection, which you can add with dotnet add package Microsoft.Extensions.DependencyInjection.

public sealed class ScoreBoard
{
    private readonly Dictionary<ulong, int> _scores = [];

    public int AddPoint(ulong userId)
    {
        _scores[userId] = _scores.GetValueOrDefault(userId) + 1;
        return _scores[userId];
    }
}

public sealed class GameCommands(ScoreBoard scores)
{
    [SlashCommand("point", "Earn a point")]
    public string Point(InteractionContext ctx) => $"You have {scores.AddPoint(ctx.UserId)} points!";
}

Then pass your services to the bot in Program.cs:

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection()
    .AddSingleton<ScoreBoard>()
    .BuildServiceProvider();

var bot = DiscordBot.NewBuilder()
    .WithToken(token)
    .WithServices(services)
    .Build();

Hidden Channels

Discord hides the details of channels your bot can't see. They still appear in the list, but with the name ___hidden___.

Simple: skip them when you list channels.

[SlashCommand("channels", "List channels")]
public string Channels(InteractionContext ctx)
{
    var names = ctx.Guild!.Channels.Where(c => !c.IsObfuscated).Select(c => c.Name);
    return string.Join(", ", names);
}

Going further: warn about channels the bot can't reach.

[RequireOwner]
[SlashCommand("audit", "Check the bot's access")]
public string Audit(InteractionContext ctx)
{
    int hidden = ctx.Guild!.Channels.Count(c => c.IsObfuscated);
    return hidden == 0 ? "I can see every channel." : $"I can't see {hidden} channel(s).";
}

Application Emojis

Application emojis belong to your bot, so they work in every server it's in. You can also upload them in the Developer Portal.

Simple: list your bot's emojis.

public sealed class EmojiCommands(IDiscordBot bot)
{
    [SlashCommand("emojis", "List the bot's emojis")]
    public async Task<string> EmojisAsync()
    {
        var emojis = await bot.GetApplicationEmojisAsync();
        return string.Join(" ", emojis.Select(e => $"<:{e.Name}:{e.Id}>"));
    }
}

Going further: upload one from a file.

public sealed class EmojiAdminCommands(IDiscordBot bot)
{
    [RequireOwner]
    [SlashCommand("addemoji", "Upload an emoji")]
    public async Task<string> AddEmojiAsync(string name)
    {
        byte[] image = await File.ReadAllBytesAsync($"emojis/{name}.png");
        string dataUri = $"data:image/png;base64,{Convert.ToBase64String(image)}";

        await bot.CreateApplicationEmojiAsync(name, dataUri);
        return $"Added {name}.";
    }
}

Next: See the Beginner's Guide if you're just starting, or Examples for more short recipes.

Clone this wiki locally