Name already in use
Discord.Net / docs / guides / getting_started / first-bot.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Making Your First Bot with Discord.Net
One of the ways to get started with the Discord API is to write a basic ping-pong bot. This bot will respond to a simple command «ping.» We will expand on this to create more diverse commands later, but for now, it is a good starting point.
Creating a Discord Bot
Before writing your bot, it is necessary to create a bot account via the Discord Applications Portal first.
Create a new application.
Give the application a name (this will be the bot’s initial username).
On the left-hand side, under Settings , click Bot .
Click on Add Bot .

Confirm the popup.
(Optional) If this bot will be public, tick Public Bot .

Adding your bot to a server
Bots cannot use invite links; they must be explicitly invited through the OAuth2 flow.
Open your bot’s application on the Discord Applications Portal.
On the left-hand side, under Settings , click OAuth2 .

Scroll down to OAuth2 URL Generator and under Scopes tick bot .

Scroll down further to Bot Permissions and select the permissions that you wish to assign your bot with.
[!NOTE] This will assign the bot with a special «managed» role that no one else can use. The permissions can be changed later in the roles settings if you ever change your mind!
Open the generated authorization URL in your browser.
Select a server.
Click on Authorize.
[!NOTE] Only servers where you have the MANAGE_SERVER permission will be present in this list.

Connecting to Discord
If you have not already created a project and installed Discord.Net, do that now.
For more information, see @Guides.GettingStarted.Installation.
Discord.Net uses .NET’s Task-based Asynchronous Pattern (TAP) extensively — nearly every operation is asynchronous. It is highly recommended for these operations to be awaited in a properly established async context whenever possible.
To establish an async context, we will be creating an async main method in your console application.
As a result of this, your program will now start into an async context.
[!WARNING] If your application throws any exceptions within an async context, they will be thrown all the way back up to the first non-async method; since our first non-async method is the program’s Main method, this means that all unhandled exceptions will be thrown up there, which will crash your application.
Discord.Net will prevent exceptions in event handlers from crashing your program, but any exceptions in your async main will cause the application to crash.
Creating a logging method
Before we create and configure a Discord client, we will add a method to handle Discord.Net’s log events.
To allow agnostic support of as many log providers as possible, we log information through a Log event with a proprietary LogMessage parameter. See the API Documentation for this event.
If you are using your own logging framework, this is where you would invoke it. For the sake of simplicity, we will only be logging to the console.
You may learn more about this concept in @Guides.Concepts.Logging.
Creating a Discord Client
Finally, we can create a new connection to Discord.
Since we are writing a bot, we will be using a DiscordSocketClient along with socket entities. See @Guides.GettingStarted.Terminology if you are unsure of the differences. To establish a new connection, we will create an instance of DiscordSocketClient in the new async main. You may pass in an optional @Discord.WebSocket.DiscordSocketConfig if necessary. For most users, the default will work fine.
Before connecting, we should hook the client’s Log event to the log handler that we had just created. Events in Discord.Net work similarly to any other events in C#.
Next, you will need to «log in to Discord» with the LoginAsync method with the application’s «token.»

[!NOTE] Pay attention to what you are copying from the developer portal! A token is not the same as the application’s «client secret.»
We may now invoke the client’s StartAsync method, which will start connection/reconnection logic. It is important to note that this method will return as soon as connection logic has been started! Any methods that rely on the client’s state should go in an event handler. This means that you should not directly be interacting with the client before it is fully ready.
Finally, we will want to block the async main method from returning when running the application. To do this, we can await an infinite delay or any other blocking method, such as reading from the console.
[!IMPORTANT] Your bot’s token can be used to gain total access to your bot, so do not share this token with anyone else! You should store this token in an external source if you plan on distributing the source code for your bot.
In the following example, we retrieve the token from a pre-defined variable, which is NOT secure, especially if you plan on distributing the application in any shape or form.
We recommend alternative storage such as Environment Variables, an external configuration file, or a secrets manager for safe-handling of secrets.
The following lines can now be added:
At this point, feel free to start your program and see your bot come online in Discord.
[!WARNING] Getting a warning about A supplied token was invalid. and/or having trouble logging in? Double-check whether you have put in the correct credentials and make sure that it is not a client secret, which is different from a token.
[!WARNING] Encountering a PlatformNotSupportedException when starting your bot? This means that you are targeting a platform where .NET’s default WebSocket client is not supported. Refer to the installation guide for how to fix this.
Building a bot with commands
To create commands for your bot, you may choose from a variety of command processors available. Throughout the guides, we will be using the one that Discord.Net ships with. @Guides.TextCommands.Intro will guide you through how to setup a program that is ready for CommandService.
For reference, view an annotated example of this structure.
It is important to know that the recommended design pattern of bots should be to separate.
Создание Discord – бота на .NET Core с деплоем на VPS-сервер

Сегодня вы ознакомитесь со статьей, в которой будет рассказано, как создать бота, используя C# на .NET Core, и о том, как его завести на удаленном сервере.
Статья будет состоять из предыстории, подготовительного этапа, написания логики и переноса бота на удаленный сервер.
Надеюсь, данная статья поможет многим начинающим.
Предыстория
Все началось в одну бессонную осеннюю ночь, которую я проводил на Discord – сервере. Так как я относительно недавно к нему присоединился, я стал его изучать вдоль и поперёк. Обнаружив текстовый канал «Вакансии», я заинтересовался, открыл его, и отыскал среди не интересующих меня предложений, это:
«Программист (разработчик бота)
Требования:
- знание языков программирования;
- способность к самообучению.
- умение разбираться в чужом коде;
- знание функционала DISCORD.
- разработка бота;
- поддержка и сопровождение работы бота.
- Возможность поддержать и повлиять на приглянувшийся проект;
- Приобретение опыта работы в команде;
- Возможность продемонстрировать и улучшить имеющиеся навыки.»
Подготовительный этап
/>
Discrod
Прежде, чем приступить к написанию нашего бота, его необходимо создать для Discord. Вам необходимо:
- Войти в Discord аккаунт по ссылке
- Во вкладе “Applications” нажать на кнопку “New Application” и назвать бота
- Получить токен бота, войдя в вашего бота и найдя в списке “Settings” вкладку “Bot”
- Сохранить где-нибудь токен
Также, необходимо создать приложение в Wargaming, чтобы получить доступ к API Wargaming. Тут тоже все просто:
- Заходим в аккаунт Wargaming по данной ссылке
- Заходим в «Мои приложения» и нажимаем на кнопку «Добавить новое приложение», дав имя приложения и выбрав его тип
- Сохраняем ID приложения
Тут уже имеется свобода выбора. Кто-то использует Visual Studio, кто-то Rider, кто-то вообще мощный, и пишет код в Vim (все же настоящие программисты используют только клавиатуру, верно?). Однако, чтобы не реализовывать Discord API, можно использовать неофициальную библиотеку для C# “DSharpPlus”. Его можно установить либо из NuGet, либо самому собрав исходники с репозитория.
Инструкция для Visual Studio
- Переходим во вкладку Проект – Управление пакетами NuGet;
- Нажимаем на обзор и в поле поиска вводим “DSharpPlus”;
- Выбираем и устанавливаем framework;
- PROFIT!
Подготовительный этап окончен, можно переходить к написанию бота.
Написание логики

Всю логику приложения рассматривать не будем, я лишь покажу, как работать с перехватом сообщений ботом, и как работать с Wargaming API.
Работа с Discord бот происходит через функцию static async Task MainTask(string[] args);
Чтобы вызвать данную функцию, в Main необходимо прописать
Далее, вам необходимо инициализировать своего бота:
Где token – токен вашего бота.
Потом, через лямбду, прописываем необходимые команды, которые должен выполнять бот:
Где e.Author.Username – получение никнейма пользователя.
Таким образом, когда вы отправите любое сообщение, которое начинается с &, бот будет приветствовать вас.
В конце данной функции, необходимо прописать await discord.ConnectAsync(); и await Task.Delay(-1);
Это позволит выполнять команды на фоне, не занимая основной поток.
Теперь необходимо разобраться с Wargaming API. Тут все просто – пишете CURL-запросы, получаете ответ в виде JSON – строки, вытягиваете оттуда необходимые данные и делаете над ними манипуляции.
Внимание! Все токены и ID приложений хранить в открытом виде строго не рекомендуется! Как минимум – Discord банит такие токены, когда они попадают во всемирную сеть, как максимум – бот начинает пользоваться злоумышленниками.
Деплой на VPS – сервер

После того, как вы закончили с ботом, его необходимо разместить на сервере, который постоянно работает 24/7. Это связанно с тем, что когда работает ваше приложение, то работает и бот. Как только вы выключаете приложение, засыпает и ваш бот.
Много VPS серверов существует на этом свете, как на Windows, так и на Linux, однако в большинстве случаев, на Linux в разы дешевле размещать.
На Discord – сервере мне посоветовали vscale.io, и я тут же создал на нем виртуальный сервер на Ubuntu и залил бота. Я не буду описывать, как работает данный сайт, а сразу перейду к настройки бота.
Первым делом, вам необходимо установить необходимый софт, который будет запускать нашего бота, написанного на .NET Core. Как это сделать, описано здесь.
Далее, вам необходимо залить бота на Git – сервис, вроде GitHub и ему подобные и склонировать на VPS — сервер, или, другими путями скачать вашего бота. Учтите, что у вас будет только консоль, GUI не будет. Совсем.
После того, как вы скачали вашего бота, вам необходимо его запустить. Для этого, вам необходимо:
- Восстановить все зависимости: dotnet restore
- Построить приложение: dotnet build name_project.sln -c Release
- Перейти к построенной DLL;
- dotnet name_of_file.dll
- Добавить запуск скрипта в /etc/init.d
- Создать сервис, который будет запускаться при старте.
Выводы
Я рад, что я взялся за это задание. Это был мой первый опыт разработки бота, и рад, что получил новые знания по C#, и работе с Linux.
How to write your own discord bot on .NET 6
You are using discord very often but your main servers are lacking of features? Its time to write them by yourself!
When starting with discord bot development, you will always get some touchpoints with JavaScript. But how do you overcome such a language barrier when you are a .NET developer or need real typization?
If you are a semi-professional, beginner or professional C# developer, you maybe want to try to develop the bot with .NET 6 and you will find some packages which give you the possibility to do so. I’ve started with Discord.Net which fits pretty well and performed great in my demos. It is frequently updated and maintained.
In the following example I will build a discord bot from scratch, which will have a simple greeting command.
Generate your own discord bot application
Before we are starting to create a .NET application, we will need to acquire a bot token from discord for our bot. This is solved via the discord developer portal. In the discord developer portal applications tab we can click New Application in the upper right corner which will open a dialog where we can put in the name of discord application. After we created the discord application, we need to create a bot for our application. This can be achieved by clicking at the left on bot and create a bot for our application. The generation was successful when the message A wild bot has appeared! is visible. Your bot token is directly under the name of the bot and can be copied. Take care, your bot token should be a secret!
Basic .NET Console Application Setup
First of all, we need to create the basic .NET console application setup. Create a console application which will initial have a Program.cs file.
We now add NuGet references to two packages. First of all we will need Discord.Net. I think this reference is pretty obvious. To make our project more comfortable, we will also add the Microsoft.Extensions.DependencyInjection package. As this will provide us the “new” best practice of Microsofts Dependency Injection.
Getting started to get our bot online
To get our bot online, there are a few steps to do, but in my opinion, it’s pretty more fast forward, as it’s in JavaScript. As we are in need to do some asynchronous calls for initialization, we will write an asynchronous main method which can be awaited, let’s call it MainAsync .
So our entry point of our console application should be the Main method, which then calls our asynchronous main method which should never return as the method should wait forever. As the comment in the code block states, this needs to be done to stay connected with our bot.
For general initialization (for example, a bootstrapper), we can also make use of the default constructor of the Program class. I also put the initialization of the DiscordClient class there.
We got some things to speak about now:
Which Discord client to use?
Discord.Net provides us with many implementations of the discord client. I would always suggest to use the DiscordShardedClient . Sharding is required for discord bots, which should grow up to handle a lot of guilds (servers).
What is sharding?
In the discord context sharding basically means, splitting one instance up to at most 1000 guilds (discord servers). Normally you won’t need some special things to do when starting with your bot. But as I always say, forewarned is forearmed. And if we are honest, we want our bot to be successful.
Bot token, do not keep it in the code
For simplification purposes, you could put the bot token into the code, which should normally NEVER BE DONE. Better take it from the config file, like in the sample I’ve provided. This can be achieved by referencing the ConfigurationBuilder and adding a appsettings.json file to your project. Don’t forget to set the build action of the file to Content and Copy always to achieve that the file is beeing copied to the output directory of your application build process.
Our bot should now be ready to connect to servers which invited him. In the discord developer portal at your bots page, you can go to OAuth2 → URL Generator you can select your scope ( bot ) and permissions ( send messages, read message history ) of the bot and generate the invitation link:
Putting the generated link into your browser will redirect you to a page where to choose which server your bot should be invited too. You can only select between servers, where you got the permission to add/invite people to.
When starting your discord bot via command line, you should be able to see the bot coming online at the server you invited him to.
After that we will enhance our bot with a sample command, which will listen to !hello and reply with a specified greetings message.
With Discord.Net it’s pretty simple to add a command to your bot. We create a folder Modules and also create a file ExampleCommands.cs in the folder.
After we told the bot, what to do with a specific command, we need to let him know, how to identify commands, this should be done in a CommandHandler.cs .
We are pulling the CommandService via dependency injection. The function HandleCommandAsync is bailing out the system and bot messages and checking if the message begins with a ! to identify if the message should be a command. Discord.Net will internally check if the command name prefixed by the ! is in any of the referenced modules and executes the command.
After that, we can enhance our Program.cs to take the CommandHandler to handle our commands. We also need to give our IOC a reference to an instance of the CommandService of Discord.Net.
If you followed all steps, you should be able to start your own discord bot and execute the !hello command via discord. There are much more things you can do and react to with your discord bot, check it out.
Building a Discord voice bot with Discord.NET
Getting started with Discord.NET to create a bot that uses voice on Discord.
I’ve been playing around with the Discord api recently, I wanted to see what could actually be done with it. I set a goal to make a discord bot that slightly annoys people by joining voice channels and randonly say Zapp Brannigan quotes.
For those who don’t know Discord is an:
I got started with Discord.NET and was able to get the bot connected very quickly. Discord.NET is an unofficial .NET API wrapper for discord which seem to be the most popular and widely used library for it so I went with it. Be sure to check out the documentation for details. For this to work with voice connections there are a few native dlls that you need to download and put with your application. These are simple enough to get from the voice documentation (or check out my full source link at the end).
First thing you need to do is get an instance of DiscordSocketClient for my project I am doing a .NET Core 2.2 console app with the built in dependency injection.
That is all the code you need to have your bot connect to discord!
I wanted my bot to detect when a user joined a voice channel and connect to that channel (if it wasn’t already). To do that I used the UserVoiceStateUpdated event on the DiscordSocketClient which can tell us when a users voice state updates (join/leave/move voice channels).
The code to handle the event then looks like this:
Now we are connecting to a voice channel when we detect a user joins it so lets look at having the bot actually send audio through. To do this the documentation for the library has an example using ffmpeg to read the sound files and pipes that into a stream that then gets sent to Discord.