Creating a Discord bot with C#/.Net Core and DSharpPlus (2023)

Bizzycola

Posted on • Updated on • Originally published at lchant.com

#csharp #netcore #dsharpplus #discordbot

Introduction

Today I'll be showing you how to setup a basic Discord bot using C#, .net core and DSharpPlus. We'll be using reflection to automatically load module classes with your commands in them.

So, first off, for those who have built discord bots with C# before, you might ask why I didn't elect to use Discord.Net (the more popular discord library). Discord.Net is a great library and it has its own pros and cons in comparison.

The reason I like DSharpPlus is the interactive library allowing you to easily await input and reactions from users, as well as (and this is not really important, just something I like) the ease of sending a "Typing.." message before the actual content. This is useful when you have a command that might take a little while, because the "Typing..." indicator shows the users that your bot has received the command and is processing the result.

Note this post is also on my blog.

Creating the discord application

So, to use create a bot, we must first head over to the Discord developer portal and create an app.

Click the New Application button and give your app a name(you'll be able to set your bots nickname and avatar image later, for now just name it what you'd like and hit Create).

You'll now be presented with a page where you can edit your applications name and description. Feel free to do this, then on the left-hand menu, click the "Bot" link.

You'll now have a mostly blank page that has the option to add a bot to this application. Hit Add Bot and hit yes when it asks you to confirm. Here you can set your bots username and profile picture. Keep this page around, you'll need the Token from the bot page as well as the client ID and token from the General Information page a little later.

Okay, now, to add the bot to your discord server(you must have the Manage Server permission to add a bot), change the CLIENTIDHERE in the following url then visit it in your browser whilst logged into discord. Select your server and add the bot: https://discordapp.com/api/oauth2/authorize?client_id=CLIENTIDHERE&scope=bot&permissions=3072

Creating the Project

I'm going to assume that if you're following this tutorial you have an editor(such as VS or VS Code, etc) and have the latest stable version of .net core installed(at this time I believe it's 2.2).

Start off by CDing to the directory in which you wish to create your project and type dotnet new console. At this point, if you wish, you can ensure it works by also running dotnet restore, dotnet build and dotnet run.

(Video) How to make a discord bot in 10 minutes using C# | Discord.Net

Before we get to coding, we're also going to install the DSharpPlus dependancies. In this guide, I'll be showing you how to use both the CommandsNext and Interactive modules of DSharpPlus so we'll go ahead and add those as well with the following commands:

dotnet add package DSharpPlusdotnet add package DSharpPlus.CommandsNextdotnet add package DSharpPlus.Interactivity

Now, we're also going to add Microsoft's configuration libraries as well to ease loading a JSON config file in which we'll store our Discord connection details. Add the packages like so:

dotnet add package Microsoft.Extensions.Configurationdotnet add package Microsoft.Extensions.Configuration.Binderdotnet add package Microsoft.Extensions.Configuration.Json

At this point you may also run dotnet restore again but dotnet should probably do that for you when you add the packages.

Getting to the Code

Okay, so both DSharpPlus and Discord.Net both use asynchronous code. Newer versions of C# allow you to make your main method async nowadays so this shouldn't be too much of an issue.

Lets start with Program.cs. Feel free to rename this file/the class to something else before continuing if you wish.

using System;using System.Linq;using System.IO;using System.Threading;using System.Threading.Tasks;using DSharpPlus;using DSharpPlus.CommandsNext;using DSharpPlus.Interactivity;using Microsoft.Extensions.Configuration;internal class Program{ /* This is the cancellation token we'll use to end the bot if needed(used for most async stuff). */ private CancellationTokenSource _cts { get; set; } /* We'll load the app config into this when we create it a little later. */ private IConfigurationRoot _config; /* These are the discord library's main classes */ private DiscordClient _discord; private CommandsNextModule _commands; private InteractivityModule _interactivity; /* Use the async main to create an instance of the class and await it(async main is only available in C# 7.1 onwards). */ static async Task Main(string[] args) => await new Program().InitBot(args); async Task InitBot(string[] args) { try { Console.WriteLine("[info] Welcome to my bot!"); _cts = new CancellationTokenSource(); // Load the config file(we'll create this shortly) Console.WriteLine("[info] Loading config file.."); _config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: false, reloadOnChange: true) .Build(); // Create the DSharpPlus client Console.WriteLine("[info] Creating discord client.."); _discord = new DiscordClient(new DiscordConfiguration { Token = _config.GetValue<string>("discord:token"), TokenType = TokenType.Bot }); // Create the interactivity module(I'll show you how to use this later on) _interactivity = _discord.UseInteractivity(new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, // What to do when a pagination request times out PaginationTimeout = TimeSpan.FromSeconds(30), // How long to wait before timing out Timeout = TimeSpan.FromSeconds(30) // Default time to wait for interactive commands like waiting for a message or a reaction }); // Build dependancies and then create the commands module. var deps = BuildDeps(); _commands = _discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _config.GetValue<string>("discord:CommandPrefix"), // Load the command prefix(what comes before the command, eg "!" or "/") from our config file Dependencies = deps // Pass the dependancies }); // TODO: Add command loading! RunAsync(args).Wait(); } catch(Exception ex) { // This will catch any exceptions that occur during the operation/setup of your bot. // Feel free to replace this with what ever logging solution you'd like to use. // I may do a guide later on the basic logger I implemented in my most recent bot. Console.Error.WriteLine(ex.ToString()); } } async Task RunAsync(string[] args) { // Connect to discord's service Console.WriteLine("Connecting.."); await _discord.ConnectAsync(); Console.WriteLine("Connected!"); // Keep the bot running until the cancellation token requests we stop while (!_cts.IsCancellationRequested) await Task.Delay(TimeSpan.FromMinutes(1)); } /* DSharpPlus has dependancy injection for commands, this builds a list of dependancies. We can then access these in our command modules. */ private DependencyCollection BuildDeps() { using var deps = new DependencyCollectionBuilder(); deps.AddInstance(_interactivity) // Add interactivity .AddInstance(_cts) // Add the cancellation token .AddInstance(_config) // Add our config .AddInstance(_discord); // Add the discord client return deps.Build(); }}

Wow, that's a lot of code! I've added comments to help you understand whats going on (If you get confused at any point in this guide, let me know in the comments and I can update it with more information if needed).

Adding the Config File

Okay, now if you ran the bot you'd find a few issues. First off, we don't have a config file yet so lets create one.

In your project directory, create a file entitled config.json.
Now, place the following code into the file and replace the values with those you found on the Discord developer portal(except for the command prefix, set that to the character you want before your commands. Perhaps "!", "$" or "/" will do):

(Video) how to make a discord bot (dsharp - c#) [Ep 1 S1]

{ "discord": { "token": "BOT TOKEN HERE", "appId": "CLIENT ID HERE", "appSecret": "CLIENT SECRET HERE", "CommandPrefix": "/" }}

Now, we need this config file to be copied to our output directory when we build the project. Open the .csproj file in an editor of your choice and add the following ItemGroup inside the tags:

<ItemGroup> <None Update="config.json" CopyToOutputDirectory="PreserveNewest" /></ItemGroup>

You may also set "CopyToOutputDirectory" to "Always" if you don't want it to only copy when the file is updated.

Adding Commands

Okay, now we have our config and our bot would likely launch, but now we need a way to interact with it.

Create a new directory in your project titled "Commands"(or modules).
In that directory, create a file named "IModule.cs". This is the interface our commands will extend from so we can load them via reflection code. Just create a an empty interface titled "IModule" like so:

public interface IModule {}

Now, create another file in the Commands directory and call it BasicCommands.Module.cs
In that module, add the following code:

using DSharpPlus.CommandsNext;using DSharpPlus.CommandsNext.Attributes;using DSharpPlus.Entities;using DSharpPlus.Interactivity;using System;using System.Threading.Tasks;/* Create our class and extend from IModule */public class BasicCommandsModule : IModule{ /* Commands in DSharpPlus.CommandsNext are identified by supplying a Command attribute to a method in any class you've loaded into it. */ /* The description is just a string supplied when you use the help command included in CommandsNext. */ [Command("alive")] [Description("Simple command to test if the bot is running!")] public async Task Alive(CommandContext ctx) { /* Trigger the Typing... in discord */ await ctx.TriggerTypingAsync(); /* Send the message "I'm Alive!" to the channel the message was recieved from */ await ctx.RespondAsync("I'm alive!"); }}

Now head back to Program.cs and we'll add in some fancy reflection code to load in anything that extends from our IModule interface.

In the InitBot method, add the following code just above RunAsync(args).wait();:

(Video) How To Make A C# Discord Bot - Setting Up - Part 1

Console.WriteLine("[info] Loading command modules..");var type = typeof(IModule); // Get the type of our interfacevar types = AppDomain.CurrentDomain.GetAssemblies() // Get the assemblies associated with our project .SelectMany(s => s.GetTypes()) // Get all the types .Where(p => type.IsAssignableFrom(p) && !p.IsInterface); // Filter to find any type that can be assigned to an IModulevar typeList = types as Type[] ?? types.ToArray(); // Convert to an arrayforeach (var t in typeList) _commands.RegisterCommands(t); // Loop through the list and register each command module with CommandsNextConsole.WriteLine($"[info] Loaded {typeList.Count()} modules.");

Okay, now run dotnet build and dotnet run. Your bot should come online and and if you type your command prefix and then alive you should see some output(example with /: /alive)!

Interactivity

So, as I mentioned earlier, I like the ability in DSharpPlus to wait for input from a user after a command has been executed. I'm going to show you a basic example for how to wait for a message from a user and read it.

Head back over to your BasicCommands module and add this new method:

[Command("interact")][Description("Simple command to test interaction!")]public async Task Interact(CommandContext ctx){ /* Trigger the Typing... in discord */ await ctx.TriggerTypingAsync(); /* Send the message "I'm Alive!" to the channel the message was recieved from */ await ctx.RespondAsync("How are you today?"); var intr = ctx.Client.GetInteractivityModule(); // Grab the interactivity module var reminderContent = await intr.WaitForMessageAsync( c => c.Author.Id == ctx.Message.Author.Id, // Make sure the response is from the same person who sent the command TimeSpan.FromSeconds(60) // Wait 60 seconds for a response instead of the default 30 we set earlier! ); // You can also check for a specific message by doing something like // c => c.Content == "something" // Null if the user didn't respond before the timeout if(reminderContent == null) { await ctx.RespondAsync("Sorry, I didn't get a response!"); return; } // Homework: have this change depending on if they say "good" or "bad", etc. await ctx.RespondAsync("Thank you for telling me how you are!");}

If you want to accept arguments from commands, you can add parameters after the CommandContext(EG:

Interact(CommandContext ctx, int age, [remainder]string fullName);

  • [remainder] just says use take all the rest of the arguments and place them in the string).

Okay, so now if you go run the bot and type /interact it'll ask you how you are and wait a whole minute for a response!

Conclusion

So now you've got this down, feel free to check out the DSharpPlus Documentation on how to use some other features and build yourself a fancy bot!

Let me know what you thought of this. In my bots I've implemented background scheduled tasks, a logger that supports multiple outputs and a reminder command that uses those scheduled tasks to alert the user when a reminder is due.

(Video) On .NET Live - Build Discord bots using .NET and Azure

I've also built game bots with scoring systems, games, leaderboards, etc. So, if you want a guide on how to do anything like those, feel free to let me know in the comments and I might write one up.

Hope you enjoyed, be sure to let me know what awesome bots you create! And if you have feedback on the article that'd be great too, it's my first dev.to article!

(Video) How To Make Discord Bot in C# [DSharp+] #HowToMakeADiscordBot

FAQs

Can I make a Discord bot using C#? ›

Programming Your C# Discord Bot

If you haven't done that yet, you can do it now: Create a new project in Visual Studio / Visual Studio Code and add your library of choice to the project through the NuGet package manager.

What language are Discord bots coded in? ›

In conclusion, Discord bots are coded in Python. However, if you don't know Python, you can consider a chatbot building platform such as Appy Pie Chatbot.

How do you make a Discord bot in C++? ›

Let's break this program down step by step:
  1. Start with an empty C++ program. ...
  2. Create an instance of dpp::cluster. ...
  3. Attach to an event. ...
  4. Attach to another event to receive slash commands. ...
  5. 5 . ...
  6. Add code to start the bot! ...
  7. Compile and run your bot. ...
  8. Inviting your bot to your server.

Is making a Discord bot hard? ›

Creating a Discord bot is a relatively simple task. You do need a little bit of programming knowledge to set things up, but the complexity of the code depends on the kind of bot you're trying to make.

What language does mee6 use? ›

Languages
CSS52%
Python36%
HTML9%
2 Other3%

How do you make a chatbot in C#? ›

To create a new Bot Project, here are the steps:
  1. First of all go to File, New, then Project or press CTRL +SHIFT + N.
  2. Now one dialog box will open. From that select Visual C# Project and you will find an option Bot Application, choose that and give the name of the project.
2 Jun 2020

Is C++ good for Discord bots? ›

D++ is a lightweight and simple library for Discord written in modern C++. It is designed to cover as much of the API specification as possible and to have a incredibly small memory footprint, even when caching large amounts of data.

How do you code bots in Discord? ›

How to Create a Discord Bot Account
  1. Give the application a name and click “Create”.
  2. Go to the “Bot” tab and then click “Add Bot”. ...
  3. Keep the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked). ...
  4. This token is your bot's password so don't share it with anybody.
8 Mar 2021

Can you make a Discord bot with Python? ›

Create a new python file for main bot code and name it as you want and import necessary modules. discord: Library provided by discord for using feature-rich discord API. os: We are using environment variables os module is used for importing those.

How do I host my Discord bot for free? ›

To do this we need to follow a few steps.
  1. Navigate to our bots directory.
  2. Create a Procfile.
  3. Create a requirements.txt file.
  4. Initialize a git repository.
  5. Commit to the repository.
  6. Sign into heroku from command line.
  7. Push git to heroku.
  8. Turn our bot on from heroku dashboard.

Does Discord require coding? ›

Although automation is the main reason to use a Discord bot, you can really program one to do anything (anything that you can cram in some JavaScript code, at least). You don't need any programming knowledge to get started, either.

How do you make a Discord bot without coding? ›

Make Discord Bot Without Coding 24/7 Online 2022 - YouTube

Is discord.py shutting down? ›

Discord.py is RETURNING! - YouTube

Is Discord API free? ›

Are there examples of free Discord APIs? DiscordBot offers all of its endpoints for free, but the price for other APIs in the Discord collection can vary. While most of the big games represented on the list have free APIs, others are paid or freemium.

Does Discord use node JS? ›

discord.js is a powerful Node.js module that allows you to interact with the Discord API very easily. It takes a much more object-oriented approach than most other JS Discord libraries, making your bot's code significantly tidier and easier to comprehend.

How do I make my own MEE6 bot? ›

  1. Go to Discord's developer portal and create an application. Go to https://discord.com/developers/applications, login with your Discord account if this is not already the case, and press the "New Application" button. ...
  2. Add a bot to your application. ...
  3. IMPORTANT: Enable Intents. ...
  4. Get your token.

Does MEE6 have an API? ›

What is mee6-levels-api? An unofficial wrapper around the Mee6 levels API to fetch the leaderboard, role rewards and user xp data. Visit Snyk Advisor to see a full health score report for mee6-levels-api, including popularity, security, maintenance & community analysis.

Is Yagpdb open source? ›

Writing code for the bot

You can also write code for the bot - it's open source. The bot is written in Go and you can view its code on GitHub.

How do I create a chatbot in Visual Studio? ›

In Visual Studio Code, open a new terminal window. Go to the directory in which you want to create your bot project. Create a new echo bot project using the following command. Replace <your-bot-name> with the name to use for your bot project.

How do I create a bot using Microsoft bot framework? ›

Channel Integrations
  1. Embed Azure Bot in Website.
  2. Connect Azure Bot with Microsoft Teams Channel.
  3. Connect Azure Bot with Telegram Channel.
  4. Connect Azure Bot with Alexa Channel | Create Alexa Skill.
  5. Connect Azure Bot with SharePoint Site.
  6. Connect Azure Bot with SharePoint using Direct Line Channel and SharePoint Framework.

How do you make a bot online Discord? ›

Creating a Discord Bot Account
  1. Create an application in the developer portal.
  2. Fill in some basic details about the application (note the CLIENT ID shown here—we'll need it later).
  3. Add a bot user connected to the application.

How do you make a Discord Bot Python 2022? ›

Navigate to https://discord.com/developers/applications and log in.
  1. Click on New Application .
  2. Enter the application's name.
  3. Click on Bot on the left side settings menu.
  4. Click Add Bot and confirm with Yes, do it! .

How do Discord bots work? ›

Discord bots are AI-driven tools that can help you automate tasks on your Discord server. They make it a lot easier to build a community that is truly engaged and can be used to moderate your server, welcome new members, or even ban people who are creating a bad environment for everyone else.

How do you make Discord bot 24/7 online free? ›

How to get your discord bot online 24/7 - FOR FREE - YouTube

How do you make a Discord bot without coding on your phone? ›

How To Make Your OWN Discord BOT Without Coding on Mobile - 2022

How do I use Discord API? ›

  1. Step 1: Set Up a New App. Using the Discord API requires a developer profile and a Discord app under the profile. ...
  2. Step 2: Set Up API Authentication. ...
  3. Step 3: Generate an App Authorization (Invite) Link. ...
  4. Step 4: Request an Authorization Token for the User.
6 May 2022

Is discord.py easy? ›

discord.py is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async / await syntax.

What is Hikari Discord? ›

An opinionated, static typed Discord microframework for Python3 and asyncio that supports Discord's V8 REST API and Gateway. Built on good intentions and the hope that it will be extendable and reusable, rather than an obstacle for future development.

How do you make a Discord bot with node js? ›

Discord Preparation
  1. Step 1: Log in to Discord and create a server. ...
  2. Step 2: Add a new developer application. ...
  3. Step 3: Give the application a name. ...
  4. Step 4: Create a bot. ...
  5. Step 5: Create a bot token. ...
  6. Step 6: Set the bot's scope and permissions. ...
  7. Step 7: Copy the invite URL and paste it into the browser.

Does it cost money to make a Discord bot? ›

You do not need to install anything on your computer, and you do not need to pay anything to host your bot.

How much do Discord bots cost? ›

All of the above features come for free, though a $4/month premium plan can be purchased to unlock more customization of tickets and translation features. The $6/month supreme plan adds in a custom bot username, icon, application, and playing status so that you can promote your brand with the bot.

How much does it cost to host a Discord bot? ›

From $2.99 monthly. Your bot hosting package will be delivered instantly after your payment. Letting us host your Discord bot means we run your code 24/7, on our super powerful server computers.

How do you make a Discord bot without coding 2022? ›

Log in to Discord and head over to the Discord Developer Portal and click the New Application button in the top right of the page.
  1. Click the New Application button to create your Discord Application.
  2. Click the Reset Token button to copy a new Bot Token.

How do you make a click bot? ›

How to Create a Simple Click and Keyborad Bot for Online Games ...

How do you make a bot like Karuta? ›

BotGhost Allows you to create your very own Karuta Discord bot without any coding required.
  1. Creating an Application. How to create a Discord Application. ...
  2. Generating a Bot. Turning your Application into a Discord Bot. ...
  3. Privileged Gateway Intents. ...
  4. Getting a Token. ...
  5. Creating your Bot. ...
  6. Inviting your Bot.
7 Jul 2021

How do I create a bot on Discord? ›

Creating a Bot account is a pretty straightforward process.
  1. Make sure you're logged on to the Discord website.
  2. Navigate to the application page.
  3. Click on the “New Application” button.
  4. Give the application a name and click “Create”.
  5. Create a Bot User by navigating to the “Bot” tab and clicking “Add Bot”.

How do you code bots in Discord? ›

How to Create a Discord Bot Account
  1. Give the application a name and click “Create”.
  2. Go to the “Bot” tab and then click “Add Bot”. ...
  3. Keep the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked). ...
  4. This token is your bot's password so don't share it with anybody.
8 Mar 2021

How do I program my Discord bot? ›

How to make your own Discord bot:
  1. Turn on “Developer mode” in your Discord account.
  2. Click on “Discord API”.
  3. In the Developer portal, click on “Applications”. ...
  4. Name the bot and then click “Create”.
  5. Go to the “Bot” menu and generate a token using “Add Bot”.
  6. Program your bot using the bot token and save the file.
20 Jan 2022

Can you code a Discord bot in Lua? ›

Discordia is a Lua wrapper for the official Discord API, and provides a high-level, object-oriented, event-driven interface for developing Discord bots.

How do you make a Discord bot without coding? ›

Make Discord Bot Without Coding 24/7 Online 2022 - YouTube

How do I host a Discord bot for free? ›

To do this we need to follow a few steps.
  1. Navigate to our bots directory.
  2. Create a Procfile.
  3. Create a requirements.txt file.
  4. Initialize a git repository.
  5. Commit to the repository.
  6. Sign into heroku from command line.
  7. Push git to heroku.
  8. Turn our bot on from heroku dashboard.

How do you make a Discord bot with node js? ›

Discord Preparation
  1. Step 1: Log in to Discord and create a server. ...
  2. Step 2: Add a new developer application. ...
  3. Step 3: Give the application a name. ...
  4. Step 4: Create a bot. ...
  5. Step 5: Create a bot token. ...
  6. Step 6: Set the bot's scope and permissions. ...
  7. Step 7: Copy the invite URL and paste it into the browser.

Is discord.py shutting down? ›

Discord.py is RETURNING! - YouTube

How do you make Discord bot 24/7 online free? ›

How to get your discord bot online 24/7 - FOR FREE - YouTube

How do you make a Discord bot without coding on your phone? ›

How To Make Your OWN Discord BOT Without Coding on Mobile - 2022

How do I use Discord API? ›

  1. Step 1: Set Up a New App. Using the Discord API requires a developer profile and a Discord app under the profile. ...
  2. Step 2: Set Up API Authentication. ...
  3. Step 3: Generate an App Authorization (Invite) Link. ...
  4. Step 4: Request an Authorization Token for the User.
6 May 2022

Can you make a Discord bot with Python? ›

Create a new python file for main bot code and name it as you want and import necessary modules. discord: Library provided by discord for using feature-rich discord API. os: We are using environment variables os module is used for importing those.

Can Discord bots read messages? ›

We know that many bots and apps function specifically to read, moderate, and otherwise manage messages sent by Discord users. We expect to grant those requests for message content without issue.

What is Discord St? ›

Discord Street is described as 'Discover new Discord Servers to join and chat in, or list your own server! The number one Discord server list' and is an app in the social & communications category. There are nine alternatives to Discord Street for Online / Web-based and Discord.

What can Discord bots do? ›

Discord bots make it easy to build a community that is active and engaged. The messages can be used to welcome new members to the server, control interactions between members, and ban users. You can use them to add memes, games, music, and other forms of entertainment content to your server.

Videos

1. How To Make A C# Discord Bot - Commands - Part 2
(Dapper Dino)
2. How To Make A C# Discord Bot - Interactivity - Part 3
(Dapper Dino)
3. Learn C# with CSharpFritz - Build a Chatbot with .NET 6
(dotnet)
4. How to shard your dsharp plus discord bot
(SharkJets)
5. How to make a Discord game with graphics in c#
(SharkJets)
6. BOT Discord.NET 2022 #2 - PRIVATE MESSAGES TO USERS By BOT - GitHub DOWNLOAD SCRIPT - C SHARP
(ZETALVX - Tools, Programming, Games, Hack)
Top Articles
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated: 08/09/2023

Views: 6106

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.