Building Your First Telegram Bot: A Step by Step Guide
![]() |
Building Your First Telegram Bot: A Step by Step Guide |
One of the more well-known instant messaging (IM) platforms today is Telegram because it lets you store messages in the cloud rather than just on your device and has good cross-platform compatibility. You can use Telegram on Android, iOS, Windows, and pretty much any other platform that can support the web version. The process of creating a chatbot on Telegram is extremely straightforward and only needs a few quick steps. The chatbot functions both independently and within Telegram groups and channels.
Here we learn how we can get different types of responses from the bot such as:
- Text
- Image
- Video
- Document
- Audio
- Poll
- Reply Buttons
- Inline Button Links
So let's see how to create a chatbot step by step
Follow the below steps in order.
Log in to your Telegram account and type the name "BotFather" in the search box.
![]() |
image by author |
Start BotFather and create a new bot and get the bot token.
![]() |
image by author |
Creating a flask app for the webhook response.
First of all, you will need to install python on your computer. After that see this article to install Flask according to your operating system.
$ pip install Flask
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello!" if __name__ == '__main__': app.run(threaded=True)
Run this code to check whether the flask app is running correctly or not. When you run the code you will get the link for the server like “http://127.0.0.1:5000/” click on that link you will be redirected to the webpage where you will see the response “Hello!”
![]() |
image by author |
Install and configure NGROK
Download Ngrok to your computer then set up a new account in Ngrok. Perform the authentication process with the received token. (see video)
After that go to Ngrok and type the command "ngrok http 5000" and after running this command you will get the links.
![]() |
image by author |
From that Ngrok links copy the HTTPS link and paste it to your browser. You will see the response “Hello!” the same as the previous step.
Set up a webhook.
Now you will need to set the webhook for the telegram bot. You can do it by running the link in your browser.
https://api.telegram.org/botYour Bot Token/setWebhook?url=URL that you got from Ngrok
After running the link in your web browser you will get the response shown in the below image:
![]() |
image by author |
Get JSON response.
Now, for whatever text we send to the Telegram bot, we must obtain the JSON answer from the bot. Open the following code in a code editor, add it to the same Ngrok link where you ran the previous code, and then run it.
After writing "hello" to your bot, now go to the code editor software, and you will file the below JSON into your terminal.
from flask import Flask from flask import request from flask import Response import requests app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': msg = request.get_json() print(msg) return Response('ok', status=200) else: return "Hello!" if __name__ == '__main__': app.run(debug=True
Here we can see how the message we wrote to the Telegram bot appears in the background text.
![]() |
image by author |
Setting up sending text Massage from a bot
How to write code to get a response for a "hello" message from the user and respond "Hello!, world" if anything other than "hi" is assigned.?
Apart from this, you can add other parameters.
from flask import Flask from flask import request from flask import Response import requests TOKEN = "your bot token" app = Flask(__name__) def parse_message(message): print("message-->",message) chat_id = message['message']['chat']['id'] txt = message['message']['text'] print("chat_id-->", chat_id) print("txt-->", txt) return chat_id,txt def tel_send_message(chat_id, text): url = f'https://api.telegram.org/bot{TOKEN}/sendMessage' payload = { 'chat_id': chat_id, 'text': text } k = requests.post(url,json=payload) return k @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': msg = request.get_json() chat_id,txt = parse_message(msg) if txt == "hello": tel_send_message(chat_id,"Hello!!") else: tel_send_message(chat_id,'Hello!, world') return Response('ok', status=200) else: return "Hello!" if __name__ == '__main__': app.run(debug=True)
Setting up image Retrieval from a bot
Now we can also get images from the Telegram bot. For that, the function for sending images should be added to the code.
Apart from this, you can add other parameters.
from flask import Flask from flask import request from flask import Response import requests TOKEN = "your bot token" app = Flask(__name__) def tel_parse_message(message): print("message-->",message) try: chat_id = message['message']['chat']['id'] txt = message['message']['text'] print("chat_id-->", chat_id) print("txt-->", txt) return chat_id,txt except: print("NO text found-->>") def tel_send_message(chat_id, text): url = f'https://api.telegram.org/bot{TOKEN}/sendMessage' payload = { 'chat_id': chat_id, 'text': text } k = requests.post(url,json=payload) return k def tel_send_image(chat_id): url = f'https://api.telegram.org/bot{TOKEN}/sendPhoto' payload = { 'chat_id': chat_id, 'photo': "https://telegra.ph/file/131533c0fc8d6b1ade492.jpg", 'caption': "This is a sample image" } k = requests.post(url, json=payload) return k @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': msg = request.get_json() try: chat_id, txt = tel_parse_message(msg) if txt == "hi": tel_send_message(chat_id,"Hello!!") elif txt == "image": tel_send_image(chat_id) else: tel_send_message(chat_id, 'Hello!, world') except: print("from index-->") return Response('ok', status=200) else: return "Hello!" if __name__ == '__main__': app.run(threaded=True)
Setting up audio Retrieval from a bot
You can send audio to the telegram in a similar manner. You can refer to the Documentation for additional parameters.
def tel_send_audio(chat_id): url = f'https://api.telegram.org/bot{TOKEN}/sendAudio' payload = { 'chat_id': chat_id, "audio": "https://od.lk/s/MzFfNDMyMzU2ODhf/sample%20music.mp3", } k = requests.post(url, json=payload) return k
Your index function should now include this code:
elif txt == "audio": tel_send_audio(chat_id)
![]() |
image by author |
Setting up video Retrieval from a bot
Add the code to the telegram to access the video. You can follow the Documentation if you want to add more parameters.
def tel_send_video(chat_id): url = f'https://api.telegram.org/bot{TOKEN}/sendVideo' payload = { 'chat_id': chat_id, "video": "https://od.lk/s/MzFfNDMyNjQ1MzVf/production%20ID_4974883.mp4", } k = requests.post(url, json=payload) return k Your index function should now include this code: elif txt == "video": tel_send_video(chat_id)
Setting up file Retrieval from a bot
Add the code to the telegram to access the file. You can follow the documentation if you want to add more parameters.
def tel_send_document(chat_id): url = f'https://api.telegram.org/bot{TOKEN}/sendDocument' payload = { 'chat_id': chat_id, "document": "https://od.lk/s/MzFfNDMyNjg2Mzdf/RH_StudyGuide_V2.pdf", } k = requests.post(url, json=payload) return k
Your index function should now include this code:
elif txt == "doc": tel_send_document(chat_id)
Setting up poll Retrieval from a bot
Add the code to the telegram to access the poll. You can follow the documentation if you want to add more parameters.
def tel_send_poll(chat_id): url = f'https://api.telegram.org/bot{TOKEN}/sendPoll' payload = { 'chat_id': chat_id, "question": "What is the correct file extension for python files?", "options": json.dumps([".pyth", ".pyt", ".py", ".pt"]), "is_anonymous": False, "type": "quiz", "correct_option_id": 2 } k = requests.post(url, json=payload) return k
Your index function should now include this code:
elif txt == "poll": tel_send_poll(chat_id)
Setting up button Retrieval from a bot
Add the button's code to the Telegram bot.
def tel_send_button(chat_id): url = f'https://api.telegram.org/bot{TOKEN}/sendMessage' payload = { 'chat_id': chat_id, 'text': "Are you robot?", 'reply_markup': {'keyboard': [[{'text':'Yes'}, {'text':'No'}]]} } k = requests.post(url, json=payload) return k
Your index function should now include this code:
elif txt == "inbutton": tel_send_inlinebutton(chat_id)
Setting up inline button Retrieval from a bot
Add the code to get the Inline Button to the telegram.
def tel_send_inlinebutton(chat_id): url = f"https://api.telegram.org/bot{TOKEN}/sendMessage" payload = { "chat_id" : chat_id, "text" : "Are you robot?", "reply_markup" : { "inline_keyboard" : [[ { "text" : "No", "callback_data" : "km_No" }, { "text" : "Yes", "callback_data" : "km_Yes" } ]] } } k = requests.post(url, json=payload) return k
Your index function should now include this code:
elif txt == "inbutton": tel_send_inlinebutton(chat_id)
Setting up inline button URL Retrieval from a bot
Add the code to get the Inline Button URL to the telegram.
def tel_send_inlineurl(chat_id): url = f"https://api.telegram.org/bot{TOKEN}/sendMessage" payload = { "chat_id" : chat_id, "text" : "Join us", "reply_markup" : { "inline_keyboard" : [ [ {"text" : "website", "url" : "https://hitechlk.com/"}, {"text" : "telegram", "url" : "https://t.me/lkhitech"} ] ] } } k = requests.post(url, json=payload) return k
Your index function should now include this code:
elif txt == "inlineurl": tel_send_inlineurl(chat_id)
Video Tutorial
The complete code included in this tutorial is also available in my GitHub repository, where you can test it and use the Telegram bot to send files to the server side and receive various responses.
Now you can have your bot work the way you want to go ahead and create the next big thing!
Comments
Post a Comment