How to create a simple Telegram bot in Python using nginx (and GCP)

Jason Jurotich
May 28, 2020 · 5 min read

I know that there are tons of stories on Telegram bots, and I don’t plan on going through the first steps in detail which everyone seems to have down pat, but I do want to underline in this story two things, one is asynchronous responses, (receiving responses after a good amount of time has passed), and two, using nginx to coordinate requests which I find less common in stories on this topic.

I also want to clarify from the beginning that I am not an expert on nginx. In fact, I havn’t found too much information on it yet, but it works well, so I wanted to explain how I set it up.

So, getting the first ordinary steps out of the way, you need to go to Telegram and find the good old Bot Father (BotFather), add him, and then you’ll have the following options:

So, just click on /newbot and it will ask you to name it and give it a username. Just make sure the username ends in “bot”…

The most important part here is the token. That is what we will use to communicate with the Bot through nginx. I have covered it up mostly (it starts with a 9), which is probably not necessary because I don’t use it, but I need to underline that it is VERY important that it remains private, or someone else can control the bot. Don’t take that lightly.

Now… you need to set up a VM instance in Google Cloud Platform… (I know, you thought you could escape it here, but no, we use GCP for pretty much all my tutoriales). So, once again, if you have not set up a project in GCP, created a Compute Engine VM instance, and set up ports to pass through the firewall, please head on over to my story here to get that set up and then come back to continue on with this tutorial.

The advantage here is that, unlike the Hangouts Chat Bot that we saw in a previous story, this one can be used by normal, personal Gmail accounts.

Ok, so now that we have the token, lets get nginx up and running, along with the Python library we will use to create the bot in Python. First, make sure that your (Ubuntu) system is updated before installing. We’ll SSH into the VM instance by clicking on “SSH” under “Connect” (see photo above).

We’ll update everything in the VM instance in our Compute Engine on the GCP:

sudo apt update -y && sudo apt-get update -y && sudo apt-get upgrade -y && sudo apt dist-upgrade -y && sudo apt-get autoremove -y && sudo apt-get clean -y && sudo apt-get autoclean -y

Then we need to make sure we have the essentials installed, including nginx and our Python Telegram bot library:

sudo apt-get install software-properties-common build-essential cmake git wget curl mosh vim nginx python3-pip && pip3 install python-telegram-bot

After, we need to get OPENSSL ready to go. The public and private keys will reside in the home directory if we run this there.

openssl req -newkey rsa:2048 -sha256 -nodes -keyout PRIVATE.key -x509 -days 365 -out PUBLIC.pem -subj “/C=US/ST=STATE/L=CITY/O=BUSINESS NAME/CN=EXTERNAL IP OF VM INSTANCE

Nginx has two folders that you’ll use if you constantly change its configuration:

/etc/nginx/sites-available/
/etc/nginx/sites-enabled/

In the first folder we need to put a text file which will have the configuration (for now, we will just call it TEXT.txt, but you can call it what you want).

cd /etc/nginx/sites-available/ && sudo vim TEXT.txt

It is very important that you use sudo with Vim here, or you won’t be able to edit the file. In the text file, we’ll put the following:

server {
listen 80;
listen 443 ssl;
server_name EXTERNAL IP OF VM INSTANCE;
ssl_certificate /home/jj/PUBLIC.pem;
ssl_certificate_key /home/jj/PRIVATE.key;

location /TELEGRAMTOKEN {
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://0.0.0.0:5000/TELEGRAMTOKEN/;
}
}

We have to put the directory and file of our public and private keys we got from OPENSSL, as well as the External IP of the VM instance from GCP and the token we got from the BotFather.

Then, we will cd ~ back to our home directory and then performing this to activate our new configuration.

sudo ln -s /etc/nginx/sites-available/TEXT.txt /etc/nginx/sites-enabled/TEXT.txt

To activate it, we’ll use the following and then check the status:

sudo systemctl restart nginx && sudo systemctl status nginx

If you needed to edit the file later on because of adding another token, you would then have to do the following, because you have to remove the file from enabled before putting it again:

sudo rm /etc/nginx/sites-enabled/TEXT.txt && sudo ln -s /etc/nginx/sites-available/TEXT.txt /etc/nginx/sites-enabled/TEXT.txt && sudo systemctl restart nginx && sudo systemctl status nginx

Then, we can create a file (vim testtelbot.py) and put the following in.

import os
import telegram
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters)
TOKEN = "TELEGRAMTOKEN"
PORT = int(os.environ.get('PORT', '5000'))
SERVER = 'EXTERNAL IP OF VM INSTANCE/'
CERT = '/home/jj/PUBLIC.pem'
def htel(update, context):
update.message.reply_text('Help is here')
def echo(update,context):
dom = update.message.text
update.message.reply_text(dom)
def tbot():
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("help", htel))
dp.add_handler(MessageHandler(Filters.text, echo))
updater.start_webhook(listen="0.0.0.0", port=5000, url_path=TOKEN)
updater.bot.setWebhook(SERVER+TOKEN,certificate=open(CERT, 'rb'))
updater.idle()
tbot()

Then, we just have to run our python script, and we are done! Our bot only repeats what we put in the chat, but we’ll make it do other things in the future. This was just to get things set up.

python3 testtelbot.py

You can either use a crontab or a screen to keep the Bot active in the background without any problem. I usually just keep it running in a screen and jump in when I have to edit it.

You can see a video on how to set this up here.

Later on, we will create a Telegram Bot to sell things using Stripe using what we set up here, with just editing our testtelbot.py file, so keep an eye out for our next stories. Cheers.

Jason Jurotich

Written by

Masters in Philosophy, Author, Professor, Consultant, Tech Promoter and Programming Novice. www.jjir.org

JJ INNOVATIVE RESULTS

How can we use tech better? We’ll offer ways to hack what you use today to work better and smarter.

Jason Jurotich

Written by

Masters in Philosophy, Author, Professor, Consultant, Tech Promoter and Programming Novice. www.jjir.org

JJ INNOVATIVE RESULTS

How can we use tech better? We’ll offer ways to hack what you use today to work better and smarter.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store