Creating a Python Telegram bot and deploying it to a virtual machine

Who needs chatbots?

The chatbot market in Russia is growing at a breakneck pace and is expected to grow by 30% annually over the next three years. In 2020, the number of requests for chatbots increased by 17% compared to 2019. Voice bots are in great demand, the number of requests for them has quadrupled. In 2021, the number of requests for chat bots is expected to grow by 15-20% from organizations from the public sector, education, medicine, logistics, retail and e-commerce, industrial and mining companies.





Steps

  1. We create our telegram bot





  2. We write the code for our tasks and test its performance





  3. Choosing a reliable virtual machine service





  4. We transfer our bot to a virtual machine for its further work.





  5. We set up the continuous operation of the bot.





Step 1. Creating a bot in Telegram

I will describe the first three steps as briefly as possible, since there are many articles on this topic and usually this does not cause any difficulties for users. To create a bot, we need to write BotFather





Step 2. Let's write a simple chatbot and test it.

For work, we will use the telebot library, which can be installed using the following command:





$ pip install pytelegrambotapi







To install other libraries, if you are not limited to the basic functionality, God will help you.





Let's write a simple bot that will send us in response to various Emoji their blurry PNG copies:





import telebot
import PIL
from PIL import Image
from requests import get

#   
bot = telebot.TeleBot('1653707062:AAHxX29RP5HY-nVb21SSD8ZRbKpxKseSyS4')

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, '  Emoji,    .)
                     
@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == '  ':
        img = open('   1.png', 'rb')
        
        bot.send_document(message.chat.id, img) 
    elif message.text.lower() == '  ':
        img = open('   2.png', 'rb')
        bot.send_document(message.chat.id, img)    
   
    else:
        bot.send_message(message.chat.id, ',       Emoji')

bot.polling()
#    ,      habr
      
      



Our bot is ready, now it remains to test it. Follow the link sent by BotFather





, . : , . - .





3. !

?

( ) — , (, , ). . , , , .





24 7





?

. , . , , .





:





  • Mail cloud solutions - 3000 . . ( )





  • Yandex.Cloud - 2000 . .





  • Google Cloud Platform - 300$ .





, .





.

, - .





.

SSH. , ssh-.





:





$ ssh-keygen







Enter. . public-key .pub. « »





.





:





ssh -i ~/.ssh/ ubuntu@ IP







: ssh -i ~/.ssh/my_key ubuntu@22.222.222.222







:





, , .





  • Python. :





$ sudo apt update
$ sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev wget libbz2-dev
$ wget https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tgz
$ tar -xf Python-3.8.5.tgz
$ cd Python-3.8.5
$ ./configure --enable-optimizations
$ make  # ~15 
$ sudo make altinstall
$ cd /home

      
      



  • :





    $ python3.8 -m pip install --upgrade pip 
    $ pip install virtualenv
    $ mkdir 
    $ cd 
    $ virtualenv venv
    $ source venv/bin/activate
    $ python -V
    $ deactivate
    
          
          



  • Redis-server:





    $ sudo apt install redis-server
    $ redis-cli
    
          
          



, Redis-server, «ping»





PONG, , !





  • . CyberDuck





SFTP, IP , !! ssh-, .





  • , Python, . . .





  • , , .





    $ cd /home//  #    
    $ source venv/bin/activate  #  
    $ pip install -r requirements.txt  #  
    $ python main.py  #  
    
          
          



, , deactivate. . .





5. .

: nano /lib/systemd/system/.service







[Unit]
Description=  
After=network.target

[Service]
EnvironmentFile=/etc/environment
ExecStart=/home//venv/bin/python main.py
ExecReload=/home//venv/bin/python main.py
WorkingDirectory=/home//
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

      
      



CTRL+O -> Enter -> CTRL+X . .





  • : , .





    sudo systemctl enable 
    sudo systemctl start 
    
          
          



! 24/7, , . - , , . , «sudo» ( )





PS The topic of bot telegrams has become very interesting and relevant lately, so I will be glad to hear sane criticism about my first article at this time. If you have any ideas for writing new ones, I will be glad to hear them.





I want to give an example of my joint work with a friend on making a bot that can make electronic signatures within 2 seconds: Telegram: Contact @Facsimile_bot








All Articles