Telegram bot with Flask

Telegram been on the spotlight for the last few months and bots it's been something i been writing since I started programming; from the good ol' IRC to my first project i did professionally: an msnp bot.

Table of Contents

My Example Project

You can try my own bot @danielm85_bot and try some simple public commands like:

# Some math operations
calc 2+2

# Covid country data
covid USA

# (or any 3-digit ISO country code)

# Weather
weather Barcelona

# (or any location name / country )

Python and Flask

Using a web frameworksmakes it really easy (and cheap!!) to deploy to any existing server, & Flask seems like the obvious option here, it is light and fast as you can get.

We need to create two routes: a webhook (POST) URL where we are going to receive a request each time someone writes a message in a private/group chat where our Bot is in; and another one-time use URL(private) that we are going to use to notify Telegram servers where or 'webhook URL' is located.

Creating the Bot

The way you create Telegram bots it's very quick and simple; All you need to do is to start a conversation with an official bot named BotFather and just follow a couple steps to configure stuff like username, name, display pic, et.

At some point the API Key will be available to you, with the format:


Our application

As i said I'm going to use Flask, and python-telegram-bot: and great API wrapper.

# File:

from flask import Flask, request
import telegram

URL = "https://our-public-secure-url/"

app = Flask(__name__)
bot = telegram.Bot(token=TOKEN)

# ----------------------------------
# Our public Webhook URL
# ----------------------------------
@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
    # retrieve the message in JSON and then transform it to Telegram object
    update = telegram.Update.de_json(request.get_json(force=True), bot)

    # TODO: do something with the message

    return 'ok'

# ----------------------------------
# Our Private to 'set' our webhook URL (you should protect this URL)
# ----------------------------------
@app.route('/setwebhook', methods=['GET', 'POST'])
def set_webhook():
    s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))
    if s:
        return "webhook ok"
        return "webhook failed"

Very straight-forward script, let's just $ flask run it.

Inside respond() you can use the good ol' command approach to process each message(like my project), or connect it to a NLP service like the ones provided by Watson, LUIS, or Wit.

Testing and Deployment

During development you can use a service like Ngrok, to make your local services publicly available so Telegram services can discover them.

After you have the project running locally or in a server, you'll need to open the URL:

# (this URL should be protected) 
$ wget https://our-public-secure-url/setwebhook

This notifies Telegram where our project is and will start receiving messages.

After that you can start chatting to your Bot and respond() will receive each message ready to process.

Note: Yes!, these must be HTTPS enabled URLs

Telegram Bot Boilerplate project.

On my GithHub i created a 'bot template' with a more organized skeleton that I used to create my Bot with some extra examples.

Telegram Bot Boilerplate

Related Posts
  • No related articles have been found, for now
The comments are closed on this section.
Hire me!

I'm currently open for new projects or join pretty much any project i may fit in, let me know!

Read about what I do, or contact me for details.