Automate your Telegram channel with a Django Telegram Bot

Mon 09 December 2019

In this post I will guide you in a very interesting and funny development task: automate your Telegram channel with a Django Telegram Bot.

Telegram is a popular instant messaging application. It’s not as widespread as Whatsapp, but its user base is constantly growing and according to Wikipedia:

The number of monthly Telegram users as of October 2019 is 300 million people worldwide

A very interesting aspect of the Telegram platform is the ability to create channels and bots to automate the broadcasting of messages to large audiences. These features open the possibility to better engage your users using Telegram, for example by sending them news, offers, etc. all from your existing Django web project! Let’s see how to do it.

1. Create a Telegram channel

Nothing special here: you can do this from the Telegram app on your phone. Just tap “New Channel” on the Telegram main menu. Choose a nice name and a clear description.

Create the Telegram channel
Create the Telegram channel

Then setup the channel as Public and choose a nice “permalink” for your channel:

Setup the Telegram channel
Setup the Telegram channel

2. Create a Telegram Bot

Now the funny part begins: search for a contact named “BotFather” on Telegram

Search for BotFather
Search for BotFather

This is a bot to manage bots, a sort of meta-bot. 🙂 Start a chat with him and write /help to know what are the available commands. To create a new bot you have to write the command /newbot.

The BotFather will ask you a couple of questions to setup your bot. Basically you’ll have to choose a “display name” and a username for your bot.

Create the Telegram bot
Create the Telegram bot

As you can see in the screenshot above, the BotFather will write you a token that you should save and keep secret. This token will be used to interact with your bot using the Telegram Bot API.

You can also set a description, an about text and even a nice profile picture for your bot; for example something like this. /help command is your friend to find out how you can do these things.

3. Make the bot an Admin for your Telegram channel

Your bot will be used to automatically post messages on your channel, so you have to add the bot to the group of channel’s administrators. Tap on the channel’s name and then on Administrators:

Edit the Telegram channel
Edit the Telegram channel

Then on Add Admin:

Edit the Telegram channel administrators
Edit the Telegram channel administrators

Now search for the bot you created at step 2:

Add the bot as the channel admin
Add the bot as the channel admin

And add it to the channel with the minimum required permission, that is only Post Messages for the scope of this tutorial:

Setup the bot permissions
Setup the bot permissions

Ok, you have completed all the steps needed on the Telegram app, and from now on you’ll work only on the Python/Django side.

4. Install python-telegram-bot

To interact with the Telegram bot API I strongly recommend to use a wrapper, so you don’t have to deal with low level details. There are three different projects for Python, but I chose python-telegram-bot because it looks quite simple to integrate and use.

Install with:

pip install python-telegram-bot

Or add the project to your requirements:

tornado==5.1.1 # dependency of python-telegram-bot

I also had to fix the version of tornado in my requirements, because the requirement made by python-telegram-bot is tornado>=5.1 and this installed tornado 6 in my case, which is not compatibile with my version on Python.

5. Edit your Django settings to add Telegram parameters

This is not strictly required, but I strongly suggest you to keep all the Telegram related parameters in your Django settings. Add a dictionary called TELEGRAM like this in your Django settings module:

    'bot_token': '123456789:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'channel_name': 'guguweb',

Of course you have to customize the bot_token parameter using the token you received from the BotFather at step 2, and the channel_name parameter with the actual name of your channel.

6. Send a message to the channel from your Django code

Suppose you have a Django powered website where you publish events for your community. An Event model could be something like this:

class Event(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    start_date = models.DateTime(null=True)

Now suppose that you want to send a message on your Telegram channel when you post a new event. To do this create a Django template that will be used to define the HTML for the Telegram message, with a content similar to this:

<a href="{{ event.url }}">{{ event.title }}</a>
{{ event.description|truncatewords:30 }}
<strong>Date:</strong>{{ event.start_date|date:'SHORT_DATE_FORMAT' }}

Consider that only a subset of HTML tags are supported by Telegram and that you cannot nest HTML tags. Save the template with the name telegram_message.html.

You can then define a function to actually create the message and send it to the Telegram bot:

import telegram # this is from python-telegram-bot package

from django.conf import settings
from django.template.loader import render_to_string

def post_event_on_telegram(event):
    message_html = render_to_string('telegram_message.html', {
        'event': event
    telegram_settings = settings.TELEGRAM
    bot = telegram.Bot(token=telegram_settings['bot_token'])
    bot.send_message(chat_id="@%s" % telegram_settings['channel_name'],
                     text=message_html, parse_mode=telegram.ParseMode.HTML)

The function takes an Event instance as the only argument, uses the Django template system to render the HTML, and then uses an instance of telegram.Bot to actually send the message. So simple, isn’t it?

If you plan to call the function from one of your views in a request-response cycle, I strongly suggest you to configure an asynchronous task to send the message, like I explained in my post Django asynchronous tasks without Celery:

Django asynchronous tasks without Celery
Django asynchronous tasks without Celery

7. Conclusions

In this post I’ve shown you how to automate your Telegram channel with a Django Telegram Bot. I think that this approach opens many interesting possibilities for better engaging the users of your Django web application.

Please don’t hesitate to ask questions or make comments in the form below or by contacting me. Of course you can also join my Telegram channel, the one that I created when writing this tutorial: I’ll use the channel to post updates from this blog, so if you find this post useful please join the channel. 😉

8. Do you want more power for your Django Telegram bot?

Of course you can! In a following post I will explain how to make a step further and make your Telegram bot more useful, by giving it the power to answer inquiries coming from Telegram users.

The bot (you guessed it) will use Django as the backend to receive messages from Telegram and send replies to the users. Stay tuned!