首页 >后端开发 >php教程 >如何使用 Python 发送 Telegram 消息?

如何使用 Python 发送 Telegram 消息?

Patricia Arquette
Patricia Arquette原创
2024-12-23 00:42:27313浏览

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.")

以上是如何使用 Python 发送 Telegram 消息?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn