I use this mini project to learn how to use telegram bot. Click on this link to test my bot @CardiRonaBot - idea inspired from this video.
The functionalities are simple:
- Echoes whatever the user says
- Typing
/audio
sends back a random audio file
Much of the source code originates from python-telegram-bot. However, instead of polling, I used webhook instead. This is because polling is inefficient and the data is not real-time while webhook can act as a push notification, removing the need to constantly check for updates on the Telegram server.
- Get the Telegram bot API token from BotFather
- Download source code and install requirements:
pip3 install -r requirements.txt
- You may also consider creating a virtual python environment.
- Create an environment file:
touch .env
.
- Copy the contents over, similar to the template below.
- Use your own credentials. Remember to keep your token information private!
TOKEN=1456236133:BAEMGzl4H-ii69FLhmM799cegl2CnRULffk
URL=https://0511a20g14a3.ngrok.io
- Download ngrok.
- Run
./ngrok http 5000
on one terminal. Copy the link and replace the value for theURL
field in the.env
file.
- This opens up your local port to the public, which allows for external requests to be forwarded to your
localhost
endpoint. This is very useful for quick debugging. localhost
should work fine too if you are testing on the same network.
- Run
python3 bot.py
on another terminal.
- Your bot should be working now.
For production, I used heroku instead of ngrok. This way, you don't have to leave your terminal running. And the best part is that heroku is free to use!
- Make sure to add the
Config Vars
key-value pairs, namelyTOKEN
andURL
. - The value in the
URL
field will take the form like so:https://cardib-rona-telebot.herokuapp.com
.