Django: a Telegram Bot with Authentication

Timur Bakibayev, Ph.D.
4 min readJun 4

How to integrate a Telegram bot inside your Django App

The problem

We want to create a Telegram bot that will be able to access the database.

If you simply write a function for the bot inside your Django app, how would you run it? You can't run it from the Django app, because it should be running in a separate process.

You can't run it from the normal Python app, because it needs access to the database.

Generated with Midjourney

We will be using pyTelegramBotAPI

There are many libraries for Telegram bots in Python, but we will be using pyTelegramBotAPI.

Install

pip install pyTelegramBotAPI

Usage

import telebot

bot = telebot.TeleBot("TOKEN", parse_mode=None)
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(func=lambda m: True)
def echo_all(message):
bot.reply_to(message, message.text)

This is a simple example of a bot that replies to every message with the same message.

How to integrate the bot into Django

There are two directions when we are talking about bots:

  1. The bot sends messages to the user (e.g. notifications)
  2. The user sends messages to the bot (e.g. commands), and the bot replies if needed. This one needs a separate process for listening.

First, let's make the bot respond to the user (direction 2)

For this, we will write a Management Command.

Create a file management/commands/bot.py

import telebot
from django.core.management.base import BaseCommand
from telebot.types import Message

bot = telebot.TeleBot("API_CHUCK_NORRIS")

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message: Message):
bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(func=lambda m: True)
def echo_all(message: Message):
bot.reply_to(message, message.text)

class Command(BaseCommand):
help = "Run the…
Timur Bakibayev, Ph.D.