Telegram echo bot with FastAPI
Creating an echo bot in Telegram is so simple that it’ll take you less than 15 mins. 🚀
Start a conversation with the BotFather
Search for @BotFather
in Telegram and press start. The BotFather will respond to you with a list of commands.
Create a bot and get your access token
Click on /newbot
command in the message or from the menu and answer a few questions to the BotFather.
In the end, you’ll receive an authentication token for your bot. Save it and keep it safe with you.
Create a webhook using FastAPI
Create a file named main.py
and copy paste the following code and replace then TOKEN
with the access token you received from the BotFather.
This essentially uses FastAPI to create a POST
endpoint in the path /webhook/
which will be called by Telegram whenever a new message is sent to the bot.
Every time Telegram sends an Update to the webhook, we get the text and call the Bot API using httpx to send it back.
Host it on your server
Host this main.py
file to your server. There are several ways to do this. One of the most popular options is
Deta.
They have a generous tier for individual creators and it’s very easy to deploy.
Test the webhook
Once it is deployed, you can test if the webhook is working by calling the API with the path {BASE_URL}/webhook/
from a client like Postman or Insomnia.
If everything is fine, it will return back whatever you had in the request body.
Set the webhook URL for the bot
Once you confirm the webhook is working, you need to set it up as the webhook URL for your bot.
You can do this by calling the setWebhook
method:
https://api.telegram.org/bot{YOUR_TOKEN}/setWebhook?url={YOUR_WEBHOOK_ENDPOINT}
And that’s it!
You can now open the bot and send messages to it. It will echo everything that it receives. And then you start adding meaningful functionality to your bot.
Subscribe to my newsletter
Join other Technical Artists, Developers and CG enthusiasts who receive my latest posts on Blender, Python, scripting, computer graphics and more directly to their inbox.