ホームページ >バックエンド開発 >Python チュートリアル >Telegram ボットからユーザーにメッセージを送信する

Telegram ボットからユーザーにメッセージを送信する

Patricia Arquette
Patricia Arquetteオリジナル
2024-12-01 08:53:10391ブラウズ

Telegram は、ボットとしてユーザーにメッセージを送信するための API を提供します。任意のプログラミング言語を使用して、HTTP POST メソッド経由でメッセージを送信できます。 Python と Requests ライブラリを使用します。

メッセージ送信用の URL アドレス:

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

メッセージの本文:

{
    "chat_id": chat_id,
    "text": "Hello World!"
}

メッセージを Markdown でマークアップしたい場合 - JSON の本文に「parse_mode」パラメータを追加します:

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

タスクを正常に完了するために必要な手順は次のとおりです:

  • Telegram アプリで BotFather を見つける
  • 新しいボットを作成してトークンを受け取る
  • 会話を開始するには、「/start」コマンドをボットに送信します。そうしないと、メッセージを受信できなくなります
  • スクリプトを作成してテストする

Python スクリプトの例:

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!')

結果:

Sending message from Telegram bot to users

今、ドキュメントを送信しようとしています:

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')

結果:

Sending message from Telegram bot to users

以上がTelegram ボットからユーザーにメッセージを送信するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。