首頁 > 後端開發 > php教程 > 如何使用 Python 發送 Telegram 訊息?

如何使用 Python 發送 Telegram 訊息?

Patricia Arquette
發布: 2024-12-23 00:42:27
原創
400 人瀏覽過

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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板