How to integrate Telegram Bot with Python using requests

Aravind Kumar Vemula
3 min readDec 26, 2020

A simple project using requests in python to send/receive the message from the Bot.

Starting with a simple intro of Telegram and Python

Telegram is a cross-platform cloud-based instant messaging, video calling, and VoIP service.

Python is an interpreted, high-level and general-purpose programming language. Python’s design philosophy emphasizes code readability with its notable use of significant whitespace.

Lets start with the creating a Bot

  • Now open Telegram App and search for BotFather and open it
  • Now click on start and you will get a details information and commands for creating bot, deleting bot and etc …
  • Type or select /newbot to create a bot
  • Now it will send you a message, that to choose a name for your bot and type your own bot name (Eg: chat,chitti,Alex)
  • Now it will ask you to enter the username for your bot with the given condition like Alex_bot or Chat_bot or AlexBot
  • If the username is already take try it using different name but it should satisfy the condition
  • When it accept your username it will send you a API token key like
142523231:AEX************
  • In that message at top you will see a link like t.me/AlexBot this will redirect to your bot chat, then click on /start to start chat with the bot

Let’s start coding

  • Create a empty python file and name it any thing (Eg: TeleBot.py)
  • import the required modules
import request as req
  • Now create a two variables
Url = ''
Key = ''
  • Lets try to get the bot information using requests
def BotInfo():
res = req.get(Url+Key+'/GetMe')
result = res.json()
print(['FirstName '+result['result']['first_name'],"Username "+result['result']['username'])
BotInfo()
  • This will give like FirstName Alex, Username AlexBot

Lets try in the web browser

  • Open a new Browser and type the https://api.telegram.org/bot+Key+/GetMe here the Key is API Token and /GetMe used to get the information of the Bot
  • Getting the queries where user asked to bot and here /GetUdpates will give a queries https://api.telegram.org/bot+Key+/getUpdates
  • Here in this Json file text is the query from the user asked to bot

Lets start coding!

  • Open the python file which you have created (Eg: TeleBot.py )
  • Lets send a message to user from bot
  • When we sending a message to user we need to get the id of the user
def UserId():
res = req.get(Url+Key+'/GetUpdates')
result = res.json()
result = result['result'][len(result['result'])-1] # To get the latest message id
return result['message']['from']['id']
def Sendmessage(answer):
id = UserId()
pos = {"chat_id":id,"text":answer}
res = req.post(Url+Key+"/sendmessage",data=pos)
Sendmessage("Hello")
  • Here /sendmessage is to send message of type json with chat_id and text
  • Now you will see a message in telegram from bot
  • Enjoy playing with it.

Thanks for reading the post…

Follow me in Github, Twitter, Linkedin.

--

--