Skip to content

MIoT 插件的 Webhook 使用说明

谢谢你

评论

评论 1 - hanxi

Webhook 使用说明

MIoT 插件的 Webhook 功能用于对话监听推送——当小爱音箱有新的对话消息时,插件会向你注册的 Webhook URL 发送 POST 请求。

1. 注册 Webhook

可以在插件的 Web UI(配置页 → 对话监听 → Webhook)里添加,也可以通过 API:

bash
curl -X POST 'http://<your-server>:58091/api/v1/jsplugin/miot/conversation/webhooks' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <token>' \
  -d '{"url": "https://example.com/my-webhook", "name": "我的推送"}'
  • url(必填):你的接收端地址,插件会向该地址 POST JSON 数据
  • name(可选):给这个 Webhook 起个名字,方便管理

2. 推送的数据格式

当小爱音箱检测到新对话时,插件会向你的 Webhook URL 发送如下格式的 POST 请求:

请求头: Content-Type: application/json

请求体示例:

json
{
  "account_id": "123456789",
  "device_id": "E8FAxxxxxxxxxx",
  "device_name": "小爱音箱 Pro",
  "messages": [
    {
      "account_id": "123456789",
      "device_id": "E8FAxxxxxxxxxx",
      "device_name": "小爱音箱 Pro",
      "message": {
        "timestamp_ms": 1749120000000,
        "response": {
          "answer": [
            {
              "question": "今天天气怎么样",
              "content": "今天多云,气温 25 到 32 度"
            }
          ]
        }
      }
    }
  ]
}

其中 messages 是本次轮询周期内检测到的所有新消息数组,每条消息包含:

  • question:用户对小爱说的话
  • content:小爱的回答

3. 接收端示例

你的 Webhook 接收端只需要是一个能处理 POST JSON 请求的 HTTP 服务。以下是几个简单示例:

Python (Flask):

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/my-webhook', methods=['POST'])
def webhook():
    data = request.json
    device = data.get('device_name', '')
    for msg in data.get('messages', []):
        answers = msg.get('message', {}).get('response', {}).get('answer', [])
        for a in answers:
            print(f"[{device}] Q: {a.get('question')}  A: {a.get('content')}")
    return 'ok'

app.run(host='0.0.0.0', port=8080)

Node.js:

javascript
const http = require('http');
http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      const data = JSON.parse(body);
      data.messages?.forEach(msg => {
        msg.message?.response?.answer?.forEach(a => {
          console.log(`[${data.device_name}] Q: ${a.question}  A: ${a.content}`);
        });
      });
      res.end('ok');
    });
  }
}).listen(8080);

4. 管理 Webhook

bash
# 查看已注册的 Webhook
curl 'http://<server>:58091/api/v1/jsplugin/miot/conversation/webhooks' \
  -H 'Authorization: Bearer <token>'

# 删除 Webhook(id 从列表接口获取)
curl -X DELETE 'http://<server>:58091/api/v1/jsplugin/miot/conversation/webhooks?id=wh_xxx' \
  -H 'Authorization: Bearer <token>'

注意事项

  • Webhook 推送不带签名或认证头,如果你的接收端暴露在公网,建议自行做来源校验
  • 推送失败不会重试,仅记录日志
  • 需要先开启对话监听功能并设置了受管设备,Webhook 才会有数据推送

链接到 GitHub Issue