How to make a Telegram bot for the server and how to run it.

Introduction

In this article, I would like to cover the topic of how you can make your Telegram bot visible and accessible to others, that is, its placement and maintenance on the server. So anyone can try out your bot.
I will show an example of deploying a Telegram bot on a beget VPS server. Because I know him well. But this article is universal for any hosting provider.
And without further ado, let's get started with deployment.

Preparing the server for operation and deploying it

So, you have a ready-made project with a bot; it starts and works for you. But you can’t leave the computer (and therefore the program) on forever. This means we deploy it on other computers that we don’t mind. Yes, I'm talking about servers, hosting, and VPS.
And so, we came to the question of how to deploy a server. And where to get it. In a beget cloud tab in your personal cabinet.
  • Click on the cloud tab.
  • Then click on the create button. beget click on cloud
  • Customize the server for yourself. setup beget's VPS

Adding a project to the server

After the server has been created and configured for you. You will need to go to it. To do this, copy external IP, and enter it in the console

ssh root@YOUR_IP
		
You will be asked for your password. It is usually sent by registered mail. Enter it.
Updating packages and external dependencies

sudo apt update
sudo apt upgrade
		
Go to your home directory.

cd /home
		

Transferring a project to a server

Using Git

Cloning the project

git clone https://github/YourUserName/YourRepoName
		
And correspondingly

git pull												
		
To update the project

Without Git

Create an empty directory.

mkdir NewProject										
		
And let's go there.

cd NewProject											
		
To transfer project files, use the hosting file manager or, like me, use the scp command.

scp -r /path/to/project root@YOur_IP:/path/where/to/save					
		
/path/to/project is the project folder on the local machine. YOur_IP is the IP issued by the hosting /path/where/to/save is the location where the project folder will be moved on the server

Setting up a virtual Python environment

If you do not use a virtual environment when creating bots (which is, of course, not recommended), then you can safely skip this step.
After all project files have been transferred. We will need to make sure that all the necessary python packages are installed.
To do this, let's create a virtual environment.

python -m venv .venv										
		
Let's activate it.

source .venv/bin/activate									
		

Installing dependencies

Without dependency file

If there is no dependency file, which was made by the pip freeze command, then you will have to personally install all the packages that need to be installed.

pip install aiogram
pip install OTHERE_PACKAGES
		
and so on

With dependency file

If there is a dependency file. Usually, dependency files are made by this command.

pip freeze > req.txt										
		
And installing dependencies by:

pip install -r req.txt										
		

Checking the status of the bot on the server

To check if everything is working. Let's follow the same steps as when developing on a local machine.
Go to the project directory on the server

ssh root@You.Ip.add.es									
cd /YOur/project/Folder									
		
Activate the virtual environment (if used).

source .venv/bin/activate									
		
Launch the bot.

python main.py										
		
Open Telegram and give commands to the bot. If he answers, well, then everything worked

Automating project updates

A small digression on the topic

Everything works, and in principle, we could stop there. But the server has the property of rebooting from time to time. Yes, and you will also have to restart your bot too.
We are busy people, right? Why do we need to remember and constantly check whether the bot is working or not? It is better to automate this task, like any other.

Creating the necessary files

To do this, we will create a systemd service, a daemon, and a script that this service will run.
Let's create a service.

touch /lib/systemd/system/bot_name.service							
		
Let's edit the file.

vim /lib/systemd/system/bot_name.service							
		
Paste the following code there:

[Unit]
Description=Telegram bot 
After=syslog.target
After=network.target

[Service]
Type=simple
WorkingDirectory=/Where/Your/Bot/Project/Exist/
ExecStart=/Where/Your/Bot/Project/Exist/start.sh
RestartSec=60
Restart=always

[Install]
WantedBy=multi-user.target
		
/Where/Your/Bot/Project/Exist/ is just your project directory.
/Where/Your/Bot/Project/Exist/start.sh is just the location of the bot startup script.
Next, we will create a script for launching the bot. Usually, I create it in the project directory in advance.

touch start.sh											
		
Let's add an execution bit to it. Let's give it the opportunity to be launched from the terminal.

chmod +x start.sh										
		
Let's add the following content to the script:

#!/usr/bin/env bash

cd /Where/Your/Bot/Project/Exist/ 
source .venv/bin/activate
python main.py
		

Initializing the service and starting it

There are just a couple of commands left to run.

systemctl enable bot_name.service								
systemctl start bot_name.service								
		
It is not clear from the output of these commands whether the service started successfully or not. To check and find out for sure, run the command

systemctl status bot_name.service								
		
systemctl's service status
If active(running). This means the service has started successfully. You can also see that the service is enabled. This means that every time the system starts or reboots, this service will start automatically.

Preparing the project for long-term support

Many people, including me before, underestimated this step. Until you personally encounter monotony and repetition of steps, that could be avoided if everything was done and configured correctly.
Here are the typical steps for everyone who is going to update their Telegram bots.
  • Login to the server (ssh or specialized hosting admin panel).
  • Go to the project directory.
  • Transfer new files from the local computer to the server (ssh-move or hosting file manager).
  • Make sure you don't break anything.
  • Make sure you have transferred everything.
  • Find out that something else needs to be improved, and repeat the process again.
And this is without databases. Yes, and I combined some steps into one. So, for example, transferring files to the server is quite a difficult task. It becomes even more dangerous if you do not make backups. God forbid you make a mistake and overwrite something. Everything is gonna be lost.
For myself, I identified three main problems when updating projects:
  • Access problem
  • Validation problem
  • Backup problem
The first problem can be solved using an ssh client and RSA-generated passwords. The second and third can be solved by introducing Git into the project.

Setting up an SSH login without a password

Of course, web interfaces are convenient, beautiful, and functional, but damn, they are very difficult to automate. Of course, you could use selenium, but why if you can write a regular Python or bash/powershell script?
The ideal solution to this problem is SSH access to the server. I am 100% sure that you, my reader, know what a terminal is and how to work with it.
By default, a password is required to access the server. But introducing it every time is a real pain in the ***. Therefore, we will configure access to the server through the generated key pair. One for the local machine, the other for the server.
Let's generate a pair.

ssh-keygen -t rsa										  
		
When asked to enter a key name, enter the full path to it + the key name
When asked to enter a password and other things, do not enter anything.
After generating the key, go to the directory where the key was generated.

cd ~/dima/.ssh/										
		
Copy the public key to the target server.

ssh-copy-id -i my_id.pub root@111.11.11.11							
		
You should now be able to log in without entering a password.

Implementation of Git technology. Its practical use.

I combined two problems into one because both of them can be solved by integrating one single version control technology, and I’m talking about git.
This tool takes care of tracking all changed, deleted, and added files. Also, if you need to roll back changes, just run the appropriate command.
I'm not going to tell you all the features of working with git. But I will show you the minimum that is necessary to easily and quickly update the project. Spoiler, literally, 3 commands.

Initializing Git on a local, home machine/computer.

First, we initialize an empty repository.

git init												
		
Create a repository on GitHub and copy the link of the repository.
Add a copied link.

git remote add REF_NAME https://github/YourUserName/YourRepoName			
		
Where REF_NAME is any name of your link
Adding files.

git add .											
		
Creating the first commit

git commit -m β€œYour comment”								
		
Sending changes to the server for the first time

git push -u REF_NAME BRANCH_NAME							
		
REF_NAME is the name of your link, which you named three steps ago.
BRANCH_NAME is the name of the branch, the default is master

Cloning a Git repository already on the server

After logging into the server, 3 commands left to remember
To create a local copy on the server

git clone https://github/YourUserName/YourRepoName					
		
Go to the directory of the local copy of the repository.

cd YourRepoName										
		
To update the project

git pull												
		

Conclusion

This is how I deploy my Telegram bots on servers. All my bots that I publish here have their own github repository, and in these repositories, you can find corresponding examples of launch scripts and services (daemons).
I hope this article helped you deploy your first Telegram bot. Bye.

heart
0
3 connected dots
0

Used termins