Creating a Discord bot on .NET Core with deployment to a VPS server

Creating a Discord bot on .NET Core with deployment to a VPS server

Hello Khabrovites!

Today you will see an article that will show you how to create a bot using C# on .NET Core and how to run it on a remote server.

The article will consist of a background, a preparatory stage, writing logic and transferring the bot to a remote server.

I hope this article will help many beginners.

prehistory

It all started on one sleepless autumn night that I spent on the Discord server. Since I recently joined him, I began to study him up and down. Having found the text channel "Vacancies", I became interested, opened it, and found among the offers that did not interest me, these are:

"Programmer (bot developer)
Requirements:

  • knowledge of programming languages;
  • ability for self-learning.

Wishes:

  • ability to understand other people's code;
  • knowledge of DISCORD functionality.

Tasks:

  • bot development;
  • support and maintenance of the bot.

Your benefit:

  • Opportunity to support and influence the project you like;
  • Gaining experience of working in a team;
  • Opportunity to demonstrate and improve existing skills.


This immediately interested me. Yes, they didn’t pay for this work, but they didn’t demand any obligations from you, and it won’t be superfluous in the portfolio. Therefore, I wrote to the server admin, and he asked me to write a bot that will show the player's statistics in World of Tanks.

Preparatory stage

Creating a Discord bot on .NET Core with deployment to a VPS server
Discrod
Before we start writing our bot, we need to create it for Discord. You need:

  1. Login to Discord account here to register:
  2. In the "Applications" tab, click on the "New Application" button and name the bot
  3. Get a bot token by logging into your bot and finding the “Bot” tab in the “Settings” list
  4. Save the token somewhere

Wargaming

Also, you need to create an application in Wargaming to get access to the Wargaming API. Here, too, everything is simple:

  1. Login to your Wargaming account by this link
  2. We go to "My Applications" and click on the "Add a new application" button, giving the name of the application and selecting its type
  3. Saving 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 (after all, real programmers use only the keyboard, right?). However, in order not to implement the Discord API, you can use the unofficial C# library “DSharpPlus”. You can install it either from NuGet, or by building the sources yourself from the repository.

For those who don't know or have forgotten how to install applications from NuGet.Instructions for Visual Studio

  1. Go to the tab Project - Manage NuGet Packages;
  2. Click on the review and in the search field enter “DSharpPlus”;
  3. Select and install framework;
  4. PROFIT!

The preparatory stage is over, you can proceed to writing the bot.

Writing logic

Creating a Discord bot on .NET Core with deployment to a VPS server

We will not consider the entire logic of the application, I will only show how to work with the interception of messages by the bot, and how to work with the Wargaming API.

Working with the Discord bot occurs through the static async Task MainTask(string[] args);
To call this function, in Main you need to register

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 your bot's token.
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 is getting the user's nickname.

This way, when you send any message that starts with &, the bot will greet you.

At the end of this function, you must write await discord.ConnectAsync(); and await Task.Delay(-1);

This will allow you to execute commands in the background without taking up the main thread.

Now we need to deal with the Wargaming API. Everything is simple here - write CURL requests, get a response in the form of a JSON string, pull out the necessary data from there and perform 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 clear text! At a minimum, Discord bans such tokens when they enter the worldwide network, and at a maximum, the bot begins to be used by attackers.

Deploy to VPS - server

Creating a Discord bot on .NET Core with deployment to a VPS server

Once you are done with the bot, it needs to be hosted on a server that is constantly running 24/7. This is due to the fact that when your application is running, the bot is also running. As soon as you turn off the application, your bot falls asleep too.

Many VPS servers exist in this world, both on Windows and on Linux, however, in most cases, it is much cheaper to host on Linux.

On the Discord server, I was advised 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 will go straight 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 it is described here.

Next, you need to upload the bot to a Git service, like GitHub and the like, and clone it to a VPS server, or download your bot in other ways. Please note that you will only have a console, no GUI. At all.

After you have downloaded your bot, you need to run it. For this, you need:

  • Restore all dependencies: dotnet restore
  • Build application: dotnet build name_project.sln -c Release
  • Go to built DLL;
  • dotnet name_of_file.dll

Congratulations! Your bot is running. However, the bot, unfortunately, occupies the console, and it's not easy to exit the VPS server. Also, in case of a server restart, you will have to start the bot in a new way. There are a couple of ways out of the situation. All of them are related to the launch at server startup:

  • Add run script to /etc/init.d
  • Create a service that will run at startup.

I don’t see the point in dwelling on them in detail, everything is described in sufficient detail on the Internet.

Conclusions

I'm glad I took on this assignment. This was my first bot development experience, and I'm glad that I got new knowledge in C #, and working with Linux.

Link to Discord server. For those who play Wargaming games.
Link to the repository where the Discord bot is located.
Link to the DSharpPlus repository.
Thank you for attention!

Source: habr.com

Add a comment