Python: Send Message to Telegram

To send a message to a Telegram channel using Python, first of all it is required to create a Telegram bot.

While creating the Telegram bot you will get an apiToken and a chatID that will be used in a Python script to access the Telegram API and send the message.

In this note you will find the examples of the Python scripts for sending messages, images, etc. to Telegram through the API.

Cool Tip: How to send a message to a Telegram channel using PHP! Read more →

Send Message to Telegram using Python

To send a message to the Telegram channel use the following Python script as an example:

# send-message-to-telegram.py
# by www.ShellHacks.com

import requests

def send_to_telegram(message):

    apiToken = '5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs'
    chatID = '515382482'
    apiURL = f'https://api.telegram.org/bot{apiToken}/sendMessage'

    try:
        response = requests.post(apiURL, json={'chat_id': chatID, 'text': message})
        print(response.text)
    except Exception as e:
        print(e)

send_to_telegram("Hello from Python!")

You can create a send-message-to-telegram.py script with the code above and run it from a command line as follows:

$ python3 send-message-to-telegram.py

You can also send images, video, audio, documents, etc. to the Telegram channel through the API using Python.

For example, to send an image to the Telegram channel, use the Python code as follows:

# send-image-to-telegram.py
# by www.ShellHacks.com

import requests

def send_to_telegram(image):

    apiToken = '5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs'
    chatID = '515382482'
    apiURL = f'https://api.telegram.org/bot{apiToken}/sendPhoto'

    try:
        response = requests.post(apiURL, json={'chat_id': chatID, 'photo': image})
        print(response.text)
    except Exception as e:
        print(e)

send_to_telegram("https://en.wikipedia.org/static/images/project-logos/enwiki.png")

Cool Tip: How to send messages form the Linux command-line through the Telegram API! Create your personal notification bot! Read more →

Leave a Reply