推送任意消息至QQ——借助OpenClaw的QQ机器人实现使用Python编辑任意消息向手机端的推送(完整教程)
import requestsimport jsonimport timefrom datetime import datetimetry:import websocketsimport asyncioWEBSOCKETS_AVAILABLE = Trueexcept ImportError:WEBSOCKETS_AVAILABLE = Falseprint("提示: websockets 库未安装,将使用简化模式")class QQBotListener:def __init__(self, app_id, app_secret, sandbox=False):self.app_id = app_idself.app_secret = app_secretself.sandbox = sandboxself.token_url = "https://bots.qq.com/app/getAppAccessToken"self.api_url = "https://api.sgroup.qq.com"self.sandbox_api_url = "https://sandbox.api.sgroup.qq.com"self.access_token = Noneself.token_expire_time = 0self.last_s = 0self.session_id = Noneself.heartbeat_interval = Noneself.running = False
C:\Users\Administrator\Desktop\Python\source_code\push_wechat>python qq_bot_listener.py============================================================QQ机器人 OpenID 获取工具============================================================AppID: 你的AppID沙箱模式: 否============================================================正在启动...获取到Gateway URL: wss://api.sgroup.qq.com/websocketWebSocket连接已建立,等待事件...[16:28:05] 收到Hello,心跳间隔: 41250ms[16:28:05] 发送心跳...[16:28:05] 已发送鉴权请求[16:28:05] [OK] 连接成功!机器人已就绪会话ID: e634b8da-b514-4a0e-a310-ead4ac80616d现在请在QQ中向机器人发送一条消息,我会为你显示用户的openid!
现在请在QQ中向机器人发送一条消息,我会为你显示用户的openid![16:28:46] 发送心跳...[16:28:46] [HEART] 心跳响应[16:29:27] 发送心跳...[16:29:27] [HEART] 心跳响应============================================================[16:29:49] [MSG] 收到单聊消息!用户OpenID: 你的OpenID消息内容: 你好消息ID:============================================================[OK] 已获取用户openid![已保存] openid记录已保存到 openid_record.json程序已停止
curl -X POST "https://bots.qq.com/app/getAppAccessToken" -H "Content-Type: application/json" -d "{\"appId\":\"你的AppID\",\"clientSecret\":\"你的AppSecret\"}"
curl -X POST "https://api.sgroup.qq.com/v2/users/你的UserID/messages" -H "Authorization: QQBot 你的token" -H "Content-Type: application/json" -d "{\"content\":\"你好,这是一条测试消息!\",\"msg_type\":0}"
import requestsappid = '你的AppID'secret = '你的AppSecret'userid = '你的UserID'message = '你好,这是一条测试消息'token = requests.post("https://bots.qq.com/app/getAppAccessToken",json={"appId":appid,"clientSecret":secret}).json()["access_token"]res = requests.post(f"https://api.sgroup.qq.com/v2/users/{userid}/messages", headers={"Authorization":f"QQBot {token}"}, json={"content":message,"msg_type":0})
夜雨聆风