Telegram Bot (quick start manual)

Vitaly Panyukhin
Analytics Vidhya
Published in
4 min readApr 14, 2020

Flask (Python), python-telegram-bot library, webhooks, deployment to Heroku

Flow between app components

Telegram is super cool! Not only because of the community gathered around him, but as well for Bots functionality. In general — Bots are useful when you don’t want to care about client app development, about motivating people to download you app and kept it updated. Yes, in 2020 everybody just hate to have one more icon on mobile phone screen, so to use Telegram as a communication and user interaction channel might be a good idea.

Unfortunately, as most stuff in 2020 you can’t just start coding the business logic, even if it is simple casual app. This manual will show how to use simple and free building blocks to boilerplate your app.

We will use Heroku as a platform where our App will be running. This is absolutely free for small projects and as PaaS solution it fully cares about how to setup web server, SSL and other infrastructure stuff.

So let’s code!

Open Telegram, find BotFather in chat search and send /newbot command. Name new bot somehow. As a reply you will get the token and the link to the Bot.

Use this token to access the HTTP API:
1214342961:ACGCc7nACifIsyr1ZSxGiLNPIszbWqkDNNo
---
Done! Congratulations on your new bot. You will find it at t.me/test_creatiww_bot.

Now we need to create few project files to have the following structure. For the sake of simplicity it will be as flat as possible. This is much better to place Python packages with a logic in accordance with the hierarchical structure of folders and files, but since we only have just 1 file, it will be located in a root folder with all the other files in the project.

$ tree -a -L 1
.
├── .git
├── .gitignore <--we don't want to commit venv folder
├── Procfile <--instructions for Heroku how to run the app
├── app.py <--business logic is here
├── requirements.txt <--libraries required by app
└── venv <--virtual environment files

To make this happen enter these commands in the terminal:

# create project folder
$ mkdir tbot; cd tbot
# activate Python virtual environment
$ python3 -m venv ./venv
$ source venv/bin/activate
# install required libraries
$ pip install python-telegram-bot flask gunicorn
# freeze requirements into the file
$ pip freeze > requirements.txt
# create file with instructions for Heroku how to run the app
$ echo "web: gunicorn app:app" > Procfile
# let's exclude virtual environment file from the repository
$ echo "venv/" > .gitignore
# initiate git repository
$ git init
# create file
$ touch app.py

Then paste the code into setup.py. We will use Flask web framework and python-telegram-bot library.

app.py

from flask import Flask, request
import telegram
import os
import json
TOKEN = os.environ['TOKEN']
bot = telegram.Bot(token=TOKEN)
app = Flask(__name__)@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
msg_id = update.message.message_id
msg = update.message.text.encode('utf-8').decode()
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
return 'ok'
@app.route('/', methods=['POST'])
def index():
return 'ok'
if __name__ == '__main__':
app.run(threaded=True)

Create account on Heroku and new application. Name it somehow, in our example the name is “tbot-creatiwww”. Before we deploy the code we need to setup environment variables with the Token that BotFather gave to us. Token is used in all API calls to Telegram backend.

$ heroku config:set TOKEN="1214342961:ACGCc7nACifIsyr1ZSxGiLNPIszbWqkDNNo"

And setup Webhook to let Telegram understand where our App is located.

# set
$ curl https://api.telegram.org/bot$(heroku config:get TOKEN)/setWebhook\?url=$(heroku apps:info -s | grep web_url | cut -d= -f2)$(heroku config:get TOKEN)
# test
$ curl https://api.telegram.org/bot$(heroku config:get TOKEN)/getWebhookInfo

Finally we are ready to deploy the code.

# add files to repository and push it to Heroku
$ heroku git:remote -a tbot-creatiwww
$ git add .
$ git commit -am "make it better"
$ git push heroku master

That’s it!

Heroku will start to build the project by pooling the dependency and will up the required services. We can track the errors and other logs by running this command:

$ heroku logs --tail  --app tbot-creatiwww

Final step is to test our Bot.

Just find our new bot via Telegram client (BotFather should provide the link while creation) and send him some messages. If everything works well you should receive the same message back as a reply.

All project files are available here: https://github.com/Creatiwww/tbot

--

--