telegram bot接口开发指南

cooolr 于 2022-05-10 发布

第一步: 在BotFather新建机器人并获取token

第二步: 设置webhock转发消息到本地接口

https://api.telegram.org/bot{token}/setWebhook?url=https://www.baidu.com/telegram_bot_api

第三步: 开发https本地接口接收消息


import requests
from flask import Flask
from flask import request

TOKEN = ""

app = Flask(__name__)

def send_message(chat_id, message):
    url = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
    data = {"chat_id": chat_id, "text": message}
    r = requests.post(url, json=data)
    return r.status_code

@app.route("/telegram_bot_api", methods=["GET", "POST"])
def bot_api():
    text = request.json["message"]["text"]
    chat_id = request.json["message"]["chat"]["id"]
    if text == "/start":
        send_message(chat_id, "绑定成功")
    else:
        message = "您设置的交易阈值即将被触发\n交易对:USD/CNY\n最高价:6.45\n最低价:6.31\n交易量:2334\n交易额:98765.43\n请及时关注交易信息,以免造成损失。"
        send_message(chat_id, message)
    return ""

if __name__ == "__main__":
    app.run(port=1234, threaded=True)

加入变量

https://t.me/cooolr_bot?start=helloworld