Hi Khabrovchani!
Today you will read an article that will tell you how to create a bot using C # on .NET Core, and how to get it on a remote server.
The article will consist of a background, a preparatory phase, writing logic and moving the bot to a remote server.
I hope this article will help many beginners.
Background
It all started on one sleepless fall night that I spent on the Discord server. Since, I only relatively recently joined him, I began to study him along and across. Having found the “Jobs” text channel, I became interested, opened it, and found among proposals that were not interesting to me, these were:
"Programmer (bot developer)
Requirements:
• knowledge of programming languages;
• self-learning ability.
Wishes:
• ability to understand someone else's code;
• knowledge of the functionality of DISCORD.
Tasks:
• bot development;
• support and maintenance of the bot.
Your benefit:
• Opportunity to support and influence the project you like;
• Gaining teamwork experience;
• An opportunity to demonstrate and improve existing skills. ”
It instantly interested me. Yes, they didn’t pay for this work, but they didn’t require any obligations from you, and it will not be superfluous in the portfolio. Therefore, I wrote the server admin, and he was asked to write a bot that will show player statistics in World of Tanks.
Preparatory stage
Discrod
Before you start writing our bot, you need to create it for Discord. You need:
1. Log in to Discord account using the link
2. In the “Applications” tab, click on the “New Application” button and name the bot;
3. Get the bot token by logging into your bot and finding the “Bot” tab in the “Settings” list.
4. Save the token somewhere.
Wargaming
You must also create an application in Wargaming in order to access the Wargaming API. Here, too, everything is simple:
1. Go to your Wargaming account at this link
2. Go to “My application” and click on the button “Add a new application”, giving the name of the application and selecting its type;
3. Save the application ID.
Software
There is already freedom of choice. Someone uses Visual Studio, someone Rider, someone is generally powerful, and writes code in Vim (nevertheless, real programmers use only the keyboard, right?). However, in order not to implement the Discord API, you can use the unofficial C # library “DSharpPlus”. It can be installed either from NuGet, or by collecting the source from the repository yourself.
For those who don’t know or forgot how to install applications from NuGet.
Instructions for Visual Studio
1. Go to the Project tab - NuGet Package Management;
2. Click on the overview and enter “DSharpPlus” in the search field;
3. Select and install the framework;
4. PROFIT!
1. Go to the Project tab - NuGet Package Management;
2. Click on the overview and enter “DSharpPlus” in the search field;
3. Select and install the framework;
4. PROFIT!
The preparatory phase is over, you can proceed to writing the bot.
Spelling logic
We will not consider the entire logic of the application, I will only show how to work with message interception by the bot, and how to work with the Wargaming API.
Work with the Discord bot occurs through the function `` `` static async Task MainTask (string [] args); `` `
To call this function, in Main you need to write `` `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, through the lambda, we 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 - getting the user's nickname.
Thus, when you send any message that begins with &, the bot will welcome you.
At the end of this function, you need to register await discord.ConnectAsync (); and await Task.Delay (-1);
This will allow you to establish a connection with the bot and executing its commands in the background, without occupying the main thread.
Now you need to deal with the Wargaming API. Everything is simple here - write CURL requests, get the answer in the form of JSON strings, pull out the necessary data from there and do manipulations on them.
An 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(" "); } } else { string error = parsed.error.message; if (error == "NOT_ENOUGH_SEARCH_LENGTH") { throw new PlayerNotFound(" "); } else if (error == "INVALID_SEARCH") { throw new PlayerNotFound(" "); } else if (error == "SEARCH_NOT_SPECIFIED") { throw new PlayerNotFound(" "); } else { throw new Exception("Something went wrong."); } } return player; }
Attention! It is strictly not recommended to store all tokens and application IDs in an open form! At a minimum - Discord bans such tokens when they get to the world wide network, at a maximum - the bot starts to use malicious users.
Deploy on VPS - server
After you are done with the bot, you need to place it on a server that is constantly running 24/7. This is due to the fact that when your application works, the bot also works. As soon as you turn off the application, your bot will fall asleep.
Many VPS servers exist in this world, both on Windows and Linux, however, in most cases, Linux is several times cheaper to host.
On the Discord server, I was advised by vscale.io, and I immediately created a virtual server on Ubuntu on it and uploaded the bot. I will not describe how this site works, but I will immediately proceed to the bot settings.
First of all, you need to install the necessary software that will run our bot written in .NET Core. How to do this is described here: docs.microsoft.com/en-us/dotnet/core/install/linux-package-manager-ubuntu-1804
Next, you need to upload the bot to Git - a service like GitHub and the like, or, in other ways, download your bot. Note that you will only have a console, there will be no GUI. Absolutely.
After you have downloaded your bot, you need to run it. To do this, you need to:
- Restore all dependencies: dotnet restore
- Build application: dotnet build name_project.sln -c Release
- Go to the built DLL;
- dotnet name_of_file.dll
Congratulations! Your bot is running. However, the bot, unfortunately, occupies the console, and it will not be so easy to exit the VPS server. Also, in case of a server reboot, you will have to start the bot again. There are a couple of ways out of the situation. All of them are related to starting at server startup:
- Add script run to /etc/init.d
- Create a service that will start at startup.
I don’t see the point in detailing them; everything is described in sufficient detail on the Internet.
conclusions
I am glad that I took up this assignment. This was my first bot development experience, and I am glad that I have gained new knowledge in C # and working with Linux.
Link to Discord - server. For those who play Wargaming games.
Link to the repository where Discord bot is.
Link to the DSharpPlus repository.
Thanks for attention!