My Python Script Sent me a message on Telegram , When it finishes running … and here is how.

It is very annoying when you have to wait for a few minutes to get the result of your code , what about if you have to wait for a few hours, in this blog I will explain how to use telegram bots to send messages for you using python code so you will know the result of your script when you are having a good time.

First : Create a Telegram Bot

In the following steps I will explain how to Create a telegram bot , get the HTTP API Access Token , Chat ID , and sent your first Message.

  1. Start a conversation with the BotFather
The Bot Father home page
starting a conversation

2. Create a bot with a cool name

start interacting with the bot using commands like the image below and give the bot a cool name , then you will get a HTTP API access token to use when interacting with your bot .

creating a telegram bot

3. Get the chat ID

to get the bot Chat ID sent a GET request to the following URL :

https://api.telegram.org/bot<HTTP API ACCESS TOKENT>/getUpdates
Getting the Chat ID

Second : Create Python function

you can create a python file which contain a function to call Telegram API like the following example.

Don’t forget to install the requests library using the following pip command

pip install requests

e.g. telegram.py

import requests
def telegramMessage(message):
    URL = "https://api.telegram.org/bot<HTTP API ACCESS TOKENT>/sendMessage"
    data= { 'chat_id' :  <ChatID>,
            'text' : f'{message}' }
    r = requests.post(url = URL, data = data)
    messageResponse = r.text

And call the function in the main python code .

e.g. main.py

from telegram import * # importing the function to the main program 

telegramMessage("This is an awesome Telegram Message" ) 

The final Result

I hope this was helpful for you , thank you for reading .

Add a Comment

Your email address will not be published. Required fields are marked *