Simple Telegram Bot using API’s

Step 1: Create your Telegram Bot using Telegram messenger

Open your Telegram app and search for @Botfather with the verified check mark.

@Botfather with verified blue check box

Step 2: Copy the Token from the response

From the above link copy the token which will be provided after the line “Use this token to access the HTTP API:”

Step 3: Get your Telegram messenger chat id.

Currently this tutorial is about sending the message to only one user which is myself, hence I need to get my chat id.

Search for @idbot
Your Chat Id will be at the bottom “P.S. Your ID: “

Step 4: Start coding

Currently there are many libraries which can be used to create this Bot which can respond, but I wanted to practice and make this as my own project so that I can work with API’s

  • Create a config file which will store the API related values
---
BOT_API_KEY : 'bot1234567890:ABCdE1FgHIJKlMnoPQR234-stQuv_wX1yzA'
BOT_URL : 'https://api.telegram.org/'
BOT_GET_UPDATE : '/getUpdates'
BOT_SEND_MSG : '/sendMessage'
USER_CHAT_ID : [1234567890]
  • Import and Global Variables
import requests
import json
import yaml
import time
  • Open the config file to read the details from the bot.
with open('Config.yml') as env_setup:
try:
env_det=yaml.safe_load(env_setup)
except:
print('Error')
API_KEY=env_det['BOT_API_KEY']
  • Function for Receiving the message
def telegram_get_message(tele_token,p_offset_id):
url=env_det['BOT_URL']+tele_token+env_det['BOT_GET_UPDATE']
data={'offset':p_offset_id}
try:
response=requests.request("POST",url,params=data)
telegram_data=json.loads(response.text)
return telegram_data
except:
return
  • Function for Sending the message
def telegram_send_message(tele_token,tele_chat_id,message):
url=env_det['BOT_URL']+tele_token+env_det['BOT_SEND_MSG']
data={"chat_id": tele_chat_id, "text": message}
try:
response=requests.request("POST",url,params=data)
telegram_data=json.loads(response.text)
return telegram_data['ok']
except:
return telegram_data
  • Time to write the code to execute the above functions
# Loop so that this bot can run for some time. I will be running this bot for 10 times with a sleep for 2 sec.
for _ in range(10):
response_data=''

# Dictonary to create a queue for user request.
data_request={}

# Getting the response from the user
response_data=(telegram_get_message(API_KEY,p_offset))

# Parsing the user response to extract his queries.
for i in response_data['result']:

# Getting the offset_id from the result and incrementing it with 1
p_offset=int(i['update_id'])+1

chat_id=i['message']['chat']['id']

# We just want that this bot respond to only to us, hence making sure that Chat id is mine.
if chat_id!=env_det['USER_CHAT_ID']:
continue

# If my queue is empty then start building it based on my chat id
if chat_id not in data_request:
data_request[chat_id]=[i['message']['text']]
else:
data_request[chat_id].append(i['message']['text'])

# Start the loop based on the queue and start responding.
for idx,val in data_request.items():
for user_request in val:
telegram_send_message(API_KEY,env_det['USER_CHAT_ID'], 'Hi. I am currently in a built Stage')
time.sleep(2)

Step 5: Expand your bot as per your requirement

You can code your bot to look for weather, search stock price or execute some command on your system (This is dangerous and should not be done).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashu Anand

Ashu Anand

Developer, Engineer and an Analyst who is enthusiast enough to try new thing. Love to play sports and developing my Trading bot.