Simple Telegram Bot using API’s

Ashu Anand
5 min readMar 24, 2022

I wanted a mechanism for myself where I can get some custom alerts for my stock analysis as per my script and I can execute some command as per my requirement. For the same I thought about easiest way of creating a Telegram Bot using Python.

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

Click Start to activate the bot. The @Botfather will response back with a standard message as below.

Select /newbot. @Botfather will ask you to name your bot. Provide the name for the bot.

@Botfather will ask for the username for the Bot. Provide the username.

Once you will provide the bot username, the bot will be created and you will get a link for your bot as “t.me/my_first_bot”

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:”

This token will look like “1234567890:ABCdE1FgHIJKlMnoPQR234-stQuv_wX1yzA”.

This is your Bot unique token and should not be shared with anyone.

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 in the search and Click start. The bot will respond you with your 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

Create a file with below fields and update the value of BOT_API_KEY with bot token and USER_CHAT_ID with your chat id. Save this file as Config.yaml

---
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

This function telegram_get_message will take 2 parameters.

Tele_Token: This is the API_KEY for the Bot

p_offset_id: This is the offset number or like a chat number which in sequence. This should always be 1 greater then last one so that we do not get previous messages again.

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

This function takes 3 parameters

Tele_Token: This is the API_KEY for the Bot

Tele_Chat_id: This will be your personal chat id

Message: Message which the bot will send to you

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)

Once the entire code base is done it is time to run the code. Once you will run the code, go to your Telegram messenger and search for your bot and click start.

This bot will be active for 20 second as I am running this loop for 10 times with sleep function for 2 sec each. Later on I will be moving my final version of code to 24*7 system so that I can use it as per my requirement.

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).

Do write your comment so that I can learn from my mistakes.

--

--

Ashu Anand

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