DEV Community

Cover image for Telegram bot with Django

Posted on

Telegram bot with Django

Hi everyone. Recently I faced a problem with integrating the Telegram bot with Django. At first look, it looks very simple. There are several ways you can connect them. I think most of you will use API to integrate them. But it is a hard way of implementing this. Using this method you will need to open API in Django, make the authorization through REST API, write methods separately for Telegram bot and so more... It is an effective way if you have a simple Django application. But in my project, It would take much more time, because it was a complicated project. So I started looking for a simpler way of implementing it. After surfing the internet for several days and finding several wrong ways of it, I found the right method. And this method made my work much simpler, so I don't need to open the API from Django and write separate methods for the Telegram bot. The bot works directly from the Django server. It turns on when you start the Django server and turns off when you shut the server off. And I want to share this method with you.

First, you should set a webhook for your bot, so Telegram knows where to send requests for your bot. In this step, you will need a production server set, because the localhost is not reachable for Telegram. If you want to set webhook with your local machine, I recommend you use NGROK. It allows you to make your local server for public usage. After you configure your production server go to . This website should return a response like below

{"ok":true,"result":true,"description":"Webhook was set"}
Enter fullscreen mode Exit fullscreen mode

After the webhook is set, just copy the code from my GitHub Gist and paste it to your Django project. And, of course, write your bot token in the appropriate place.

I hope you will like this method.

Top comments (0)