5 Minutes Project
We are going to build a Telegram bot with python and deploy it to Heroku.
The bot I am going to build will be able to send random pictures or videos of dogs using dog.ceo API, in less than 50 lines of code!
No time to waste, let’s dive in.
Your project directory should consist of three files
Inside the requirements.txt file write these lines, as these are the packages we are going to use
A Procfile is a file that specified the commands that are executed by the app on startup.
We will simply need it to execute our
The content of your Procfile should be as follows
web: python3 bot.py
So far so good, moving on to the bot itself.
As a starter, use these imports and global constants
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
PORT = int(os.environ.get('PORT', 5000))
TOKEN = os.environ["TOKEN"]
API_ENDPOINT = 'https://dog.ceo/api/breeds/image/random'
Once we deploy our bot, I’ll talk about these constants again.
Our bot will consist of three major parts
- Defining what commands are allowed
- Defining the functionality of each of the commands
- Fetching the images or video we wish to send
Defining what commands are allowed
Let’s break down the below snippet
def main(): updater = Updater(TOKEN, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler('bop', bop)) updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN) updater.bot.setWebhook('https://your-app-name.herokuapp.com/' + TOKEN) updater.idle()
python-telegram-bot docs about the
add_handler function to the dispatcher, we basically add a new command.
dp.add_handler(CommandHandler(‘bop’, bop)) simply defines a new command that will be triggered with
/bop , and as a result, will trigger a function
bop that we will soon implement.
Next, we set a webhook that will listen on
0.0.0.0 with the specified port.
Defining the functionality of each of the commands
In this section, we are going to define the function
bop that will be triggered when you execute the command
/bop within telegram.
def bop(update, context):
url = get_image_url()
chat_id = update.message.chat.id
This one is fairly simple and straightforward.
we get the image URL from the API and sent it through our bot chat, not much to cover here.
Fetching the images or video we wish to send
Let’s break down the below snippet
def get_url(): contents = requests.get(API_ENDPOINT).json() url = contents['message'] return url def get_image_url(): allowed_extension = ['jpg', 'jpeg', 'png'] file_extension = '' while file_extension not in allowed_extension: url = get_url() file_extension = re.search("([^.]*)$", url).group(1).lower() return url
The purpose of
get_image_url is to verify that the URL we got from the API is within the file extensions we expect it to be.
This function wraps the
get_url function which is actually making the API call and getting the URL.
Friendly reminder: don’t forget to add
if __name__ == '__main__':
at the bottom of your
Before we get to deploying our bot to Heroku, make sure you pushed everything to your Github repository.
Next, you will have to obtain the token for the telegram bot.
Add The Bot Father to your telegram and use the command
/newbot . after specifying a name and a user name, the bot father will generate a token for your bot — keep it safe.
Go into your Heroku dashboard, click “New” and “Create new app”
Give your app a name and click “Create app”
You’ll be redirected to the deployment page of your newly created app.
Click on Github under “Deployment method” and connect your GitHub repository containing the bot you just created
Remember the global constants I promised to talk about again? that’s the time.
Click on “settings” and then under “Config vars” click on “Reveal Config Vars”
Now add the variable “TOKEN” as a key, and the token you got from the bot father as the value
And that’s it, your bot should be up and running, go and check it out.
The source code for my bot can be found on my Github.
You can add @boogram_bot to your telegram and enjoy some random dogs pictures with the command
- Follow me on Twitter to get more of my content