Build And Deploy A Telegram Bot
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
bot.py
requirements.txt
Procfile
Inside the requirements.txt file write these lines, as these are the packages we are going to use
python-telegram-bot==12.7
requests==2.26.0
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 bot.py
file.
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
import requests
import re
import osPORT = 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()
From python-telegram-bot
docs about the Updater
class
This class, which employs the
telegram.ext.Dispatcher
, provides a frontend totelegram.Bot
to the programmer, so they can focus on coding the bot. Its purpose is to receive the updates from Telegram and to deliver them to said dispatcher.
Using the add_handler
function to the dispatcher, we basically add a new command.
The line 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
context.bot.send_photo(chat_id=chat_id, photo=url)
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 urldef 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__':
main()
at the bottom of your bot.py
file.
Deploying
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 /bop
.
Shameless Self-Promotion
- Follow me on Twitter to get more of my content
- To read every story I and other writers post on Medium, join Medium membership via my referral link.
- Follow me on my blog to read all my work without any memberships needed.
- My girlfriend and I recently opened a greeting card shop together.
In case a loved one has a birthday soon or you need some Christmas cards in advance, we got you covered. - You can also support me by getting me some double espressos.
Subscribe to DDIntel Here.
Join our network here: https://datadriveninvestor.com/collaborate
Ten articles before and after
Домашняя бухгалтерия в telegram. Теги. – Telegram 中文版
How to Bulk Invite Members in your Telegram Group or Channel – Telegram 中文版
Python and Telegram bot, how to collaborate them to make processes simplified? – Telegram 中文版
Building a Covid-19 Fact-Check Tele Bot Using Machine Learning – Telegram 中文版
PyCryptoBot Telegram Bot. This really is a very exciting new… – Telegram 中文版
Call Me with Home Assistant, Zoom and Telegram Bot – Telegram 中文版
¡La adaptación masiva de las finanzas descentralizadas ya ha ocurrido! – Telegram 中文版