Home > Backend Development > Python Tutorial > Sending message from Telegram bot to users

Sending message from Telegram bot to users

Patricia Arquette
Release: 2024-12-01 08:53:10
Original
375 people have browsed it

Telegram provides API for sending messages to users as bot. You may send messages via HTTP POST method using any programming language. I use Python and Requests library.

URL address for sending message:

https://api.telegram.org/bot<token_from_botfather>/sendMessage
Copy after login

Body of message:

{
    "chat_id": chat_id,
    "text": "Hello World!"
}
Copy after login

If you want to markup your message with Markdown - add "parse_mode" parameter in body of JSON:

{
    "chat_id": chat_id,
    "text": "Hello World!",
    "parse_mode": "Markdown"
}
Copy after login

Here steps needed for successfully complete the task:

  • Find BotFather in Telegram app
  • Create new bot and receive token
  • Send "/start" command to bot for start conversation. Otherwise, if you don't do this, you won't receive the messages
  • Write script and testing

Example of Python script:

import requests


def send_text_message(TOKEN, chat_id, message):
    url = 'https://api.telegram.org/bot{}/sendMessage'.format(TOKEN)
    data = {'chat_id': chat_id, 'text': message, 'parse_mode': 'Markdown'}
    response = requests.post(url, data=data)
    return response


send_text_message('token_from_botfather', recipient_id, 'Hello World!')
Copy after login

Result:

Sending message from Telegram bot to users

Now we are trying to send the document:

import requests


def send_document(TOKEN, chat_id, file):
    url = 'https://api.telegram.org/bot{}/sendDocument'.format(TOKEN)
    data = {'chat_id': chat_id}
    document = open(file, 'rb')
    files = {'document': document}
    response = requests.post(url, data=data, files=files)
    return response


send_document('token_from_botfather', recipient_id, '/path/to/any/document.file')
Copy after login

Result:

Sending message from Telegram bot to users

The above is the detailed content of Sending message from Telegram bot to users. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template