DEV Community

#!z@nko...;
#!z@nko...;

Posted on Edited on

Build your Telegram bots in a Django way!


Hi guys! I hope you're doing well.

In this post I want to talk about my library, dj_telegram_bot. It helps you build Telegram bots right inside your Django project, and it feels like a normal Django app.


Why I made it

Imagine you want to add a Telegram bot to your Django project. The first thing you do is look for an existing library and use it. But most of them don't fit well with Django, so you still have to take care of a lot of things yourself.

Here is what you get with dj_telegram_bot:

  • Decorator routing: commands, messages, buttons, inline queries and * wildcards. You can write functions or classes.
  • Built-in guards: @staff_required, @superuser_required, @sponsor_required (makes users join your channels first), and @before_handler for your own checks.
  • Edit from the admin: messages and keyboards live in the database. You can build them visually and change them without a redeploy.
  • Fully typed: every Telegram type is a Pydantic model.
  • And more: maintenance mode, an optional user model, SOCKS5 proxy, and local Bot API server (TDLib) support.

I use it myself, and I really like the ORM, the simplicity, and how fast I can deploy.

Here is what the admin panel looks like:

With this you can easily build your own Telegram bot or connect your website to Telegram.

Your first bot in 2 minutes

The getting started guide shows how to install it, connect the webhook, and answer /start:

https://zankoan.github.io/dj_telegram_bot/getting-started/

After that, create a directory named bot_handlers in your app and add a file, for example test.py:

from dj_telegram_bot.core.handlers import command_handler

@command_handler("start")
def start(ctx):
    ctx.bot.send_message(ctx.chat_id, "Hello!")
Enter fullscreen mode Exit fullscreen mode

Run your Django server and send /start to the bot. You will get "Hello!". It's just a normal function with a decorator.

Prefer classes? You can use them too

If you like CBV in Django, you can write your handlers in a class:

from dj_telegram_bot.core.handlers import UpdateHandler, command_handler

class Home(UpdateHandler):
    @command_handler("start")
    def start_bot(self):
        self.bot.send_message(self.chat_id, "Hello!")
Enter fullscreen mode Exit fullscreen mode

Control who can use your handlers

Just put the guards under the route decorator:

from dj_telegram_bot.core.guards import sponsor_required, staff_required
from dj_telegram_bot.core.handlers import command_handler

@command_handler("stats")
@staff_required
def stats(ctx):
    ctx.bot.send_message(ctx.chat_id, "Only staff can see this.")

@command_handler("start")
@sponsor_required
def start(ctx):
    ctx.bot.send_message(ctx.chat_id, "Welcome!")
Enter fullscreen mode Exit fullscreen mode

sponsor_required is my favorite. It makes users join your channels before the handler runs. If they didn't join, the bot sends them a message with a button for each channel.

More details here:

https://zankoan.github.io/dj_telegram_bot/access-control/

Manage keyboards from the admin

Another thing I love is the keyboard management. As you saw in the screenshots, there is a keyboard section in the admin panel. You can create your custom keyboards on a web page and edit them anytime, with no code change. Keyboards are fully supported.

This is how you send one:

from dj_telegram_bot.contrib.services import MessageService
from dj_telegram_bot.core.handlers import command_handler
from dj_telegram_bot.core.keyboard import KeyboardBuilder

@command_handler("start")
def start(ctx):
    msg = MessageService.get_msg_by_step("home")
    markup = KeyboardBuilder(msg).build()
    ctx.bot.send_message(ctx.chat_id, msg.text, reply_markup=markup)
Enter fullscreen mode Exit fullscreen mode

For more details, see the admin docs:

https://zankoan.github.io/dj_telegram_bot/admin/

Fully typed

Every Telegram type is a Pydantic model, based on the Telegram API docs. So your editor can autocomplete and help you while you write your bot.

Under the hood

Here is how an update moves through the library:

Telegram ──webhook──▢ TelegramWebhookView
                          β”‚
                       Dispatcher        picks a handler class by update type
                          β”‚
                    before handlers      your checks, run on every update
                          β”‚
                   Router.find(...)      exact β†’ step β†’ wildcard
                          β”‚
                     your function or method
Enter fullscreen mode Exit fullscreen mode
  1. Telegram sends an update to /telegram/webhook/.
  2. The Dispatcher wraps it in a handler object for its type (command, message, callback, inline query or chosen inline result).
  3. Every @before_handler runs. If one returns True, processing stops.
  4. The Router finds a matching route and calls it.

Where to go next

New to the library? Read these three pages in order:

  1. Getting started: install, connect the webhook and answer /start.
  2. Handlers: reply to commands, messages and buttons.
  3. Examples: copy a working example for what you are building.

Try it and tell me what you think

If you enjoy it or find it useful, please give it a star on GitHub and share it with your friends. It really helps the project grow.

Feel free to contribute if you want. Issues and ideas are welcome too!

Top comments (0)