文章目录
引言
我的这篇文章中:
介绍了打造对话聊天机器人的详细步骤,但是对于微信调用我们API的方式(见方式2)没有介绍,这篇文章作为补充说明。
微信主动调用我们的API也有2种方式:
- 回调函数
- 服务接口调用
回调函数一般用作通知,服务接口可实现动态答案(答案中某些部分是实时变化的)的显示,比如天气、房价等等。
服务接口调用
场景
我们如果要实现二手房实时均价的查询(先输入房价,然后输入要查询的城市):
则可以使用服务接口调用的方式。
操作步骤
创建高级技能
-
点击高级技能。
-
输入名字后,点击保存。
-
点击返回,防止出现BUG。
增加意图(问答)
- 从高级技能里点击编辑。
- 点击新建意图,并输入一个问题“房价查询”后点击确定。
补充用户问法
增加2个问题“房价”和“房价查询”。
语义槽设置
用户输入“房价”以后,机器人会反问他“查询那里的房价”,这时,用户输入了“上海”,则“上海”会被保存到语义槽里面,供我们进一步处理。
语义槽实际上是一个集合,比如我们这里可以支持城市级别的房价查询,则可以使用微信内置的 城市 语义槽,这样用户输入“北京”、“深圳”、“杭州”等等都可以匹配上(即用户输入的问题得在这个集合内,才能正确匹配问题)。
- 新增语义槽,选择城市
- 添加追问语句
- 启用立即追问
服务接口配置
- 增加服务接口调用
2.点击自定义接口和创建自定义接口
- 配置接口(注意要能公网访问)
- 选择刚刚的接口
- 点击配置接口
- 绑定输入语义槽,输出的会自动生成,不用配置(这样,用户输入的城市会通过city字段传到我们的API,而我们输出的价格会绑定到房价语义槽上面)
- 测试接口(一定要放到data_list下面,并且是一个数组!!!这里很重要)后点击确定。
- 发现多一个输出语义槽
配置回答
最后,点击保存配置和机器人发布。
接口准备
我这边使用golang写了一段代码:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
const kListenPort = 8099
func main() {
// 服务接口方式测试
// 官网文档:https://developers.weixin.qq.com/doc/aispeech/platform/di-san-fang-api-diao-yong.html
// 输出格式:https://developers.weixin.qq.com/doc/aispeech/platform/3rdparty_api.html
// 房价:https://hangzhou.anjuke.com/market/
// GET 输入:city,输出:price
http.HandleFunc("/house/price2", func(writer http.ResponseWriter, request *http.Request) {
if request.Method != "GET" {
log.Println("not support http post")
return
}
city := request.URL.Query().Get("city")
if city == "" {
log.Println("invalid city")
return
}
log.Println(fmt.Sprintf("/house/price2 city:%s", city))
price := 52624
switch city {
case "北京":
price = 57192
case "深圳":
price = 56569
case "杭州":
price = 28148
}
res := map[string]interface{
}{
"data_list": []interface{
}{
map[string]interface{
}{
"price": price,
},
},
"err_code": 0,
"err_msg": "success",
}
data, err := json.Marshal(res)
if err != nil {
log.Println(err.Error())
return
}
log.Println(fmt.Sprintf("/house/price2 response:%s", string(data)))
_, err = writer.Write(data)
if err != nil {
log.Println(err.Error())
}
})
log.Print("server start on :", kListenPort)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", kListenPort), nil))
}
代码在:
https://github.com/xmcy0011/MyWeChatRobot
- 需要安装go 1.13以上
- 需要启用go mod
使用方法为(CentOS 7为例,mac/windows类似):
$ git clone https://github.com/xmcy0011/MyWeChatRobot
$ cd MyWeChatRobot
$ cd robot_srv
$ go mod tidy
$ go build
$ ./robot_srv
测试
点击机器人调试,输入房价和城市,查看效果。
回调函数
创建
配置接口
API代码
package main
import (
"fmt"
"github.com/bitly/go-simplejson"
"io/ioutil"
"log"
"net/http"
)
const kListenPort = 8099
func main() {
// 接口回调测试
http.HandleFunc("/house/price", func(writer http.ResponseWriter, request *http.Request) {
if request.Method != "POST" {
_, _ = fmt.Fprintf(writer, "not support http get")
return
}
if request.ContentLength > 10*1024*1024 {
log.Printf("content length to large,> 10MB")
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Println(err.Error())
return
}
root, err := simplejson.NewJson(body)
if err != nil {
log.Println(err.Error())
return
}
nulValue := root.Get("nlu")
answerValue, err := nulValue.Get("answer").String()
if err != nil {
log.Println(err.Error())
return
}
nulValue.Set("answer", fmt.Sprintf("%s 再加工----------", answerValue))
resData, err := nulValue.Encode()
if err != nil {
log.Println(err.Error())
return
}
log.Printf("/house/price method:%s,header:%v,body:%s \n", request.Method, request.Header, string(body))
_, err = writer.Write(resData)
if err != nil {
log.Println(err.Error())
}
//_, _ = fmt.Fprintf(writer, string(resData))
})
log.Print("server start on :", kListenPort)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", kListenPort), nil))
}
更多可以参考官方文档。
效果(有问题)
不知道为什么,啥都没有输出。
返回值json如下
输入:
{
"touser":"o9U-85owe0wsywkZibHBf8UBU5NQ",
"nlu":{
"ans_node_id":8405354,
"ans_node_name":"测试",
"answer":"{"callback":{"url":"http://106.14.172.35:8099/house/price"}}",
"answer_open":1,
"answer_type":"text",
"article":"",
"bid_stat":{
"curr_time":"20201116-15:28:23",
"err_msg":"",
"latest_time":"20201116-15:28:23",
"latest_valid":true,
"up_ret":0
},
"confidence":1,
"create_time":"1605512089886",
"dialog_session_status":"COMPLETE",
"dialog_status":"COMPLETE",
"event":"",
"from_user_name":"o9U-85owe0wsywkZibHBf8UBU5NQ",
"intent_confirm_status":"",
"list_options":false,
"msg":[
{
"ans_node_id":8405354,
"ans_node_name":"测试",
"article":"",
"confidence":1,
"content":"{"callback":{"url":"http://106.14.172.35:8099/house/price"}}",
"debug_info":"",
"event":"",
"list_options":false,
"msg_type":"text",
"opening":"",
"request_id":32599,
"resp_title":"房价回调",
"scene_status":"s_Not_Started@",
"session_id":"",
"status":"GENERAL_FAQ",
"take_options_only":false
}
],
"msg_id":"ac7bd7089003df1931c3de382371af4555c23e79",
"opening":"",
"request_id":32599,
"ret":0,
"scene_status":"s_Not_Started@",
"session_id":"",
"slot_info":[
],
"slots_info":[
],
"status":"GENERAL_FAQ",
"take_options_only":false,
"title":"房价回调",
"to_user_name":"37471"
},
"query":"房价回调",
"authtoken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b3VzZXIiOiJvOVUtODVvd2Uwd3N5d2taaWJIQmY4VUJVNU5RIiwiYXBwaWQiOiJGaTE2aG16QWdnUHFxSmYiLCJ0b2tlbiI6IkRERHlNakNYcVpiakRMS0ZQU1FuT29uOFdtVmtXSSIsImlhdCI6MTYwNTUxMjA5MH0._Vk7OWPYGWQQs8ywfmv_AEnLXIV8lPcEklCPy8dqTSg"
}
输出:
{
"ans_node_name": "小微闲聊",
"answer": "你好呀! 再加工----------",
"answer_type": "text",
"bid_stat": {
"curr_time": "20190515-18:07:37",
"err_msg": "微信通用意图.肯定[email protected]'s element.slot slot does not exist!",
"latest_time": "20190523-16:06:33",
"latest_valid": false,
"up_ret": -1
},
"from_user_name": "o9U-85tEZToQxIF8ht6o-KkagxO0",
"msg": [
{
"ans_node_id": 6666,
"ans_node_name": "小微闲聊",
"confidence": 1,
"content": "你好呀!",
"debug_info": "",
"msg_type": "text",
"resp_title": "小薇兄你好",
"status": "FAQ"
}
],
"status": "FAQ",
"title": "小薇兄你好",
"to_user_name": "xalsjfasf1ljasjdf1"
}
关于
推荐下自己的开源IM,纯Golang编写:
CoffeeChat:
https://github.com/xmcy0011/CoffeeChat
opensource im with server(go) and client(flutter+swift)
参考了TeamTalk、瓜子IM等知名项目,包含服务端(go)和客户端(flutter+swift),单聊和机器人(小微、图灵、思知)聊天功能已完成,目前正在研发群聊功能,欢迎对golang和跨平台开发flutter技术感兴趣的小伙伴Star加关注。
————————————————
版权声明:本文为CSDN博主「许非」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xmcy001122/article/details/109720877