How to create a Telegram bot using Python

telegram bot using Python

Hello guys..! Welcome to another great tutorial. In this tutorial, we are going to build a telegram bot using python. Here, we are not using any python module.

To create telegram bot we use telegram REST API. Here are the steps to follow

Steps to follow

  • Get token
  • Get chat results
  • Send replies

Read more

Facebook post automation using Python

URL shortner using Python

Get Token from Telegram to create telegram bot

First you need to register our telegram bot in our telegram desktop or mobile app. For that search Botfather in telegram app.

Now open that BotFather and click on start. It will show some commands to interact with telegram bot.

Now type the command /newbot – It will initialize the bot for us. It will ask for the name to your bot, so give a unique name to your bot.

Now it will ask bot username that should end with _bot. Give a unique name. Now it will generate a message and API doc links along with a secrete token for our telegram bot.

Now type “your bot name” in the telegram app and open it and click that start and send some messages to bot.

I know you didn’t get any reply from the bot.

Get chat results from telegram API

Now we got the authorization key to access our telegram chatbot. Here I gave one URL to access the chat results. you can use this URL in the web browser to see the API results.

#URL to get updates
https://api.telegram.org/bot<your token key>/getUpdates

# Example:
https://api.telegram.org/bot1396625443:AAHQWPv2KVJwV21R2Nt3HmvlHDCsSTZ4/getUpdates

once you run this URL in the browser, you will get a JSON result as ok. I see this message in the browser results then we are ready for the next step.

Now open your favorite coding editor and also terminal to run the code. If you don’t have the requests package in your python then install it by using the below command.

pip install requests

let’s start coding. Here we need a chat_id and message to get a reply from telegram chatbot. so let’s get them by using the python-requests package.

import requests:

URL = 'https://api.telegram.org/bot1396625443:AAHQWPv2KVJwV21R2Nt3HmvlHDCsSTZ4' 
# Don't forget to change the token key

def get_updates(url):
    response = requests.get(url+'getUpdates').json()
    return response['result']


data = get_updates(url)

print(data)

Run this script on cmd or terminal, Now you are able to see the chat results in JSON format in the command prompt or terminal.

Now we need to get that chat_id and message to get replies from bot. so let’s watch the JSON data to get keys.

# Continue
#get_updates() returns a list.

message = data[-1]['message']['text'].lower()  # getting chat_id from the data
chat_id = data[-1]['message']['from']['id']    # getting last message from the data.


Now we are ready to send replies by chat bot to users.

Send replies as telegram bot

To send replies we have another call

# send replies URL:

#Chat URL 

https://api.telegram.org/bot<your token>/sendMessage?chat_id=<chat_id>&text='Your message'

Example: 

https://api.telegram.org/bot1396625443:AAHQWUeWPv2KVJwV21R2vlHDCsSTZ4/sendMessage?chat_id=1056785&text=Welocome Jp

Once you formatted the chat url, now run this url in the browser, so that you will get reply from telegram bot with your message in the url.

Now let’s create the python script to send more replies as bot.

Note: Open your bot in telegram and type hi and send it to bot.

#continue

# Sending messages

def send_messsage(url,chat_id,message):
    if message == 'hi':
       reply = ' hello, how are you..?'
       send = requests.post(url+'sendMessage?chat_id='+chat_id+'&text='+reply
       return send
  

send_message(url,chat_id,message)

if you run this function then you will get a notification from telegram bot as ” hello, how are you..?“.

I hope you will get that reply. we need to run this script continuously so that our users will get auto replies from bot which are given to the bot.

Here i am giving the code that automatically send replies to your users, so please copy and paste it and add more if -elif , if you need.

update_id = None

def get_updates(url,offset):
    url = url+'getUpdates?timeout=100'
    if offset:
        url =url + '&offset={}'.format(offset+1)
    r = requests.get(url).json()
    return r



while True:
    print(".....")
    updates = get_updates(url, offset=update_id)
    print(updates)
    updates = updates['result']
    if updates:
        for item in updates:
            update_id = item['update_id']
            try:
                message = item['message']['text'].lower()
                c_id = item['message']['from']['id']
                send_message(url,message,c_id)
            except:
                message = None
            

if you run the script, it will execute continously so your users will get replies.

Now its time to deploy your script in cloud or any Linux server so that it will run 24X7 and your users will get replies from it.

I hope you get this telegram bot in successfully, to get more interesting tutorials on python subscribe our newsletter now. Thank you.

Leave a Reply