How to Write Your Own Discord Bot on .NET

Introduction

Discord is a popular platform for communication and collaboration among communities, gamers, and developers. One of the most exciting features of Discord is the ability to create custom bots that can automate tasks, manage server activities, and enhance user experiences. In this tutorial, we'll guide you through the process of creating your own Discord bot using .NET 6, the latest version of the .NET framework. By the end of this tutorial, you'll have a basic bot up and running on your Discord server.

Prerequisites

Before we dive into creating a Discord bot using .NET 6, make sure you have the following prerequisites in place.

  1. Discord account: You'll need a Discord account to create and manage your bot.
  2. Visual Studio or Visual Studio Code: You can choose either of these code editors for development.
  3. .NET 6 SDK: Download and install the .NET 6 SDK from the official .NET website (https://dotnet.microsoft.com/download/dotnet/6.0).
  4. Discord Developer Portal: Create a bot application in the Discord Developer Portal (https://discord.com/developers/applications).
  5. Discord Server: You should have administrative privileges on a Discord server where you can invite your bot.

Let's get started!

Step 1. Create a New .NET 6 Console Application

Open your preferred code editor (Visual Studio or Visual Studio Code) and create a new .NET 6 console application. You can do this by running the following command in your terminal.

dotnet new console -n MyDiscordBot

Step 2. Install Discord.Net NuGet Package

To interact with the Discord API, we'll use the Discord.Net library. Add this library to your project by running the following command in your project directory.

dotnet add package Discord.Net

Step 3. Initialize the Discord Bot

In your Program.cs file, add the necessary using statements.

using System;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;

class Program
{
    private DiscordSocketClient _client;

    static async Task Main(string[] args)
    {
        var program = new Program();
        await program.RunBotAsync();
    }

    public async Task RunBotAsync()
    {
        _client = new DiscordSocketClient();
        _client.Log += LogAsync;

        await _client.LoginAsync(TokenType.Bot, "YOUR_BOT_TOKEN");
        await _client.StartAsync();

        await Task.Delay(-1);
    }

    private Task LogAsync(LogMessage log)
    {
        Console.WriteLine(log);
        return Task.CompletedTask;
    }
}

Replace "YOUR_BOT_TOKEN" with the token you obtained from the Discord Developer Portal.

Step 4. Connect Your Bot to a Discord Server

To invite your bot to a server, visit the OAuth2 section in the Discord Developer Portal. Select the "bot" scope, and copy the generated OAuth2 URL. Paste this URL in your browser, choose a server to invite the bot, and grant the necessary permissions.

Step 5. Respond to Commands

Now, let's add a basic command to respond to messages. Modify the RunBotAsync method to include event handling for received messages.

public async Task RunBotAsync()
{
    _client = new DiscordSocketClient();
    _client.Log += LogAsync;
    _client.Ready += ReadyAsync;
    _client.MessageReceived += MessageReceivedAsync;

    await _client.LoginAsync(TokenType.Bot, "YOUR_BOT_TOKEN");
    await _client.StartAsync();

    await Task.Delay(-1);
}

private async Task MessageReceivedAsync(SocketMessage message)
{
    if (message.Content.ToLower() == "hello")
    {
        await message.Channel.SendMessageAsync("Hello, Discord!");
    }
}

In this example, the bot will respond with "Hello, Discord!" when someone sends the message "hello."

Step 6. Run Your Bot

Build and run your bot by executing the following command in your project directory.

dotnet run

Your bot should now be online and responsive to the specified command in your Discord server.

Conclusion

Congratulations! You've successfully created a basic Discord bot using .NET 6. From here, you can continue to expand and customize your bot by adding more functionality, commands, and event handlers. Be sure to consult the Discord.Net documentation for more advanced features and best practices. Have fun exploring the world of Discord bot development with .NET 6.