
Hello, Habr users!
Today you will find an article that explains how to create a bot using C# on .NET Core and how to set it up on a remote server.
The article will consist of a background, a preparation stage, writing the logic, and deploying the bot on a remote server.
I hope this article will help many beginners.
Background
It all started on a sleepless autumn night that I spent on Discord. Since I had recently joined, I began to explore it thoroughly. Discovering the text channel "Job Opportunities," I became interested, opened it, and found among the uninteresting offers this:
"Programmer (Bot Developer)
Requirements:
- knowledge of programming languages;
- ability to learn independently.
Requirements:
- ability to understand other people's code;
- knowledge of DISCORD functionality.
Tasks:
- development of the bot;
- support and maintenance of the bot's operation.
Your benefits:
- The opportunity to support and influence a project you like;
- Gaining experience working in a team;
- The ability to showcase and improve your existing skills."
This instantly caught my interest. Yes, this job was unpaid, but there were no obligations, and it wouldn’t hurt to add to the portfolio. So I wrote to the server admin, and he asked me to create a bot that would display player statistics in World of Tanks.
Preparation stage

Discord
Before starting to write our bot, it needs to be created for Discord. You need to:
- Log into your Discord account
- In the "Applications" tab, click on the "New Application" button and name your bot
- Obtain the bot token by entering your bot and finding the "Bot" tab in the "Settings" list
- Save the token somewhere
Wargaming
You also need to create an application in Wargaming to access the Wargaming API. This is also easy:
- Log into your Wargaming account
- Go to "My Applications" and click on the "Add New Application" button, naming it and selecting its type
- Save the application ID
Software
There is already freedom of choice here. Some use Visual Studio, some use Rider, some even powerful editors and write code in Vim (after all, real programmers only use the keyboard, right?). However, to avoid implementing the Discord API, you can use the unofficial C# library 'DSharpPlus'. It can be installed either from NuGet or by building the source from the repository.
For those who don't know or have forgotten how to install applications from NuGet.Instructions for Visual Studio
- Go to the Project tab – Manage NuGet Packages;
- Click on browse and enter 'DSharpPlus' in the search field;
- Select and install the framework;
- PROFIT!
The preparatory stage is complete, you can move on to writing the bot.
Writing the logic

We won’t cover all the application logic; I'll just show how to work with message interception by the bot and how to work with the Wargaming API.
Working with the Discord bot happens through the function static async Task MainTask(string[] args);
To call this function, you need to write in Main
MainTask(args).ConfigureAwait(false).GetAwaiter().GetResult();Next, you need to initialize your bot:
discord = new DiscordClient(new DiscordConfiguration
{
Token = token,
TokenType = TokenType.Bot,
UseInternalLogHandler = true,
LogLevel = LogLevel.Debug
}); Where token is the token of your bot.
Then, using a lambda, write the necessary commands that the bot should execute:
discord.MessageCreated += async e =>
{
string message = e.Message.Content;
if (message.StartsWith("&"))
{
await e.Message.RespondAsync("Hello, " + e.Author.Username);
}
};
Where e.Author.Username is used to obtain the user's nickname.
Thus, when you send any message starting with &, the bot will greet you.
At the end of this function, you need to write await discord.ConnectAsync(); and await Task.Delay(-1);
This will allow commands to run in the background without blocking the main thread.
Now you need to understand the Wargaming API. It's simple – you write CURL requests, get a response in the form of a JSON string, extract the necessary data from it, and perform manipulations on it.
Example of working with WargamingAPI
public Player FindPlayer(string searchNickname)
{
//https://api.worldoftanks.ru/wot/account/list/?application_id=y0ur_a@@_id_h3r3search=nickname
urlRequest = resourceMan.GetString("url_find_player") + appID + "&search=" + searchNickname;
Player player = null;
string resultResponse = GetResponse(urlRequest);
dynamic parsed = JsonConvert.DeserializeObject(resultResponse);
string status = parsed.status;
if (status == "ok")
{
int count = parsed.meta.count;
if (count > 0)
{
player = new Player
{
Nickname = parsed.data[0].nickname,
Id = parsed.data[0].account_id
};
}
else
{
throw new PlayerNotFound("Player not found");
}
}
else
{
string error = parsed.error.message;
if (error == "NOT_ENOUGH_SEARCH_LENGTH")
{
throw new PlayerNotFound("Minimum three characters required");
}
else if (error == "INVALID_SEARCH")
{
throw new PlayerNotFound("Invalid search");
}
else if (error == "SEARCH_NOT_SPECIFIED")
{
throw new PlayerNotFound("Empty nickname");
}
else
{
throw new Exception("Something went wrong.");
}
}
return player;
}
Warning! It is strongly discouraged to store all tokens and app IDs in plain view! At the very least, Discord bans such tokens when they hit the global internet; at the most, the bot begins to be used by malicious actors.
Deployment on VPS – server

Once you've finished with the bot, it needs to be hosted on a server that runs continuously, 24/7. This is because when your application is running, your bot is running as well. As soon as you turn off the application, your bot goes to sleep.
There are many VPS servers in this world, both on Windows and Linux; however, in most cases, it is significantly cheaper to host on Linux.
On the Discord server, I was recommended vscale.io, and I immediately created a virtual server on Ubuntu and uploaded the bot. I won't describe how this site works; instead, I will proceed directly to setting up the bot.
First of all, you need to install the necessary software that will run our bot, written in .NET Core. .
Next, you need to upload the bot to a Git service, like GitHub and similar, and clone it onto the VPS server, or download your bot by other means. Keep in mind that you will only have a console; there will be no GUI. At all.
After you have downloaded your bot, you need to run it. To do this, you need to:
- Restore all dependencies: dotnet restore
- Build the application: dotnet build name_project.sln -c Release
- Navigate to the built DLL;
- dotnet name_of_file.dll
Congratulations! Your bot is running. However, the bot unfortunately occupies the console, and exiting the VPS server is not straightforward. Also, in case of a server reboot, you will need to restart the bot. There are a couple of solutions to this situation. They all involve starting it on server boot:
- Add script execution to /etc/init.d
- Create a service that will run on startup.
I don't see the point in discussing them in detail, everything is described sufficiently on the internet.
Conclusions
I'm glad I took on this task. It was my first experience developing a bot, and I'm happy to have gained new knowledge in C# and working with Linux.
Link to the Discord server.
Thank you for your attention!
Source: habr.com
