Python telegram机器人发送消息

____tz_zs

使用 telegram 机器人发送消息给个人或者群,可作为邮件提醒的平替。

一、获取个人ID(是一串数字)

方法一,在telegram中与https://t.me/userinfobot对话

Id: 1234567890
First: <个人的昵称>
Lang: zh-hans

方法二,与如下获取群ID相同。先与我的机器人对话一次(如发送1234567),在浏览器访问https://api.telegram.org/bot<包括尖括号替换成机器人的token>/getUpdates可看到自己和机器人的对话记录。

{
  "update_id": 135799176,
  "message": {
    "message_id": 4,
    "from": {
      "id": 1234567890,
      "is_bot": false,
      "first_name": "<个人的昵称>",
      "username": "<个人的账号名>",
      "language_code": "zh-hans"
    },
    "chat": {
      "id": 1234567890,
      "first_name": "<个人的昵称>",
      "username": "<个人的账号名>",
      "type": "private"
    },
    "date": 1664441400,
    "text": "1234567"
  }
}

二、获取群ID(是-后接一串数字)

将机器人拉到群里后,任意人员在此群里发送一条信息(如发送77777),在浏览器访问https://api.telegram.org/bot<包括尖括号替换成机器人的token>/getUpdates可看到自己记录。

{
  "update_id": 135799169,
  "message": {
    "message_id": 4,
    "from": {
      "id": 1234567890,
      "is_bot": false,
      "first_name": "<个人的昵称>",
      "username": "<个人的账号名>",
      "language_code": "zh-hans"
    },
    "chat": {
      "id": <-群的ID>,
      "title": <群名>,
      "type": "supergroup"
    },
    "date": 1664439613,
    "text": "77777"
  }
}

三、postman发消息测试

curl -X POST “https://api.telegram.org/bot<包括尖括号替换成机器人的token>/sendMessage" -d "chat_id=<目标的id,一串数字,群id比个人id的前边多了-号>&text=消息消息消息消息消息"

机器人发送给个人,结果:

{
    "ok": true,
    "result": {
        "message_id": 3,
        "from": {
            "id": 5460335058,
            "is_bot": true,
            "first_name": "tzzs_msg_test",
            "username": "tzzs_tg_test_bot"
        },
        "chat": {
            "id": 1234567890,
            "first_name": "<个人的昵称>",
            "username": "<个人的账号名>",
            "type": "private"
        },
        "date": 1664440279,
        "text": "7777tzzstest"
    }
}

机器人发送给群,结果:

{
    "ok": true,
    "result": {
        "message_id": 8,
        "from": {
            "id": 5460335058,
            "is_bot": true,
            "first_name": "tzzs_msg_test",
            "username": "tzzs_tg_test_bot"
        },
        "chat": {
            "id": <-群的ID>,
            "title": <群名>,
            "type": "supergroup"
        },
        "date": 1664440446,
        "text": "tzzs群消息"
    }
}

四、python 发送消息

r = requests.post(f'https://api.telegram.org/bot{
      
      token}/sendMessage', json={
    
    "chat_id": chat_id, "text": message})
"""
token 为机器人的token
chat_id 为个人ID或群ID
message 为发送的消息。注意消息长度不能太长,超过最大限制会发送失败并报错。
"""

五、参考

https://core.telegram.org/bots
https://core.telegram.org/bots/api
https://zhuanlan.zhihu.com/p/146062288
https://hackmd.io/@truckski/HkgaMUc24?type=view
https://zaoldyeck.medium.com/%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E4%BD%A0%E6%80%8E%E9%BA%BC%E6%89%93%E9%80%A0-telegram-bot-a7b539c3402a

猜你喜欢

转载自blog.csdn.net/tz_zs/article/details/127110582