Home > Backend Development > PHP Tutorial > How to Send a Telegram Message Using Python?

How to Send a Telegram Message Using Python?

Patricia Arquette
Release: 2024-12-23 00:42:27
Original
368 people have browsed it

How to Send a Telegram Message Using Python?

# Define the Telegram API endpoint.
TELEGRAM_API_URL = "https://api.telegram.org/bot{token}/"

# Define the path to the file containing the Telegram API token.
TOKEN_FILE = "./token.txt"

# Define the message to be sent.
MESSAGE_TEXT = "Hello, world!"

# Read the Telegram API token from the file.
with open(TOKEN_FILE, "r") as f:
    token = f.read().strip()

# Construct the URL for the API request.
api_url = TELEGRAM_API_URL.format(token=token)

# Make the API request.
response = requests.post(api_url, data={"chat_id": "me", "text": MESSAGE_TEXT})

# Check if the request was successful.
if response.status_code == 200:
    # Extract the message ID from the response.
    message_id = response.json()["result"]["message_id"]

    # Print the message ID.
    print(f"Message sent. Message ID: {message_id}")
else:
    # Print an error message.
    print("Error sending message.")
Copy after login

The above is the detailed content of How to Send a Telegram Message Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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