github:https://github.com/zhumengyifang/ChattingRobot.git
github与blog展示代码稍有出入,请以github为准
让我自己做个聊天机器人怕是够呛了,所以研究了一下曲线救国的方法,使用免费的外接机器人api作为切入点实现自动聊天机器人的实现。
实现效果:
GitHub:https://github.com/zhumengyifang/ChattingRobot.git
如何创建项目:https://blog.csdn.net/weixin_40165163/article/details/89037098
好了新找一找免费的机器人接入点,我这里选择的是图灵机器人 http://www.turingapi.com/
注册之后创建一个属于自己的机器人:
之后进入设置拿到对应机器人的apikey:
之后打开api使用文档,根据文档首先使用postman进行一个测试:
userId这里对应的应该是apiKey机器人下的userId来确定是在跟那个用户进行聊天,我这里是随便输入的,到时候最好生成一个guid来作为唯一标记。
项目结构:
main.go
package main
import (
"fmt"
"main/Util"
"time"
)
const userId1 = "userId1"
const userId2 = "userId2"
func main() {
var chattingInfo = Util.BuildChatting("你好!", userId1)
var userId = userId1
for i := 0; i < 10; i++ {
var json = Util.ConvertJson(chattingInfo)
var resultText = chatting(userId, json)
time.Sleep(time.Second)
if i%2 != 0 {
userId = userId1
} else {
userId = userId2
}
chattingInfo = Util.UpdateChatting(userId, resultText, chattingInfo)
}
}
func chatting(userId string, json string) string {
var body, resultErrs = Util.HttpPost(json)
if resultErrs != nil {
fmt.Println(resultErrs.Error())
}
var resultText, errs = Util.GetText(body)
if errs != nil {
fmt.Println(errs.Error())
}
fmt.Println()
fmt.Println(userId + ":" + resultText)
return resultText
}
modelUtil.go
package Util
import (
"main/model"
)
const appKey = "6f884bbd0b9841bf846f13947a85b13c"
func UpdateChatting(userId string, text string, chattingInfo model.Chatting) model.Chatting {
chattingInfo.UserInfo.UserId = userId
chattingInfo.Perception.InputText.Text = text
return chattingInfo
}
func BuildChatting(text string, userId string) model.Chatting {
chatting := model.Chatting{ReqType: 0}
chatting.Perception = buildPerception(text)
chatting.UserInfo = buildUserInfo(userId)
return chatting
}
func buildPerception(text string) model.Perception {
perception := model.Perception{buildInputText(text)}
return perception
}
func buildInputText(text string) model.InputText {
inputText := model.InputText{text}
return inputText
}
func buildUserInfo(userId string) model.UserInfo {
return model.UserInfo{appKey, userId}
}
jsonUtil.go
解析json返回值也可以通过创建对象的方式去进行,我这里嫌麻烦 使用另一种方式:https://goframe.org/encoding/gjson/index
根据返回值进行选取我们需要的值:
package Util
import (
"encoding/json"
"errors"
"fmt"
"github.com/gogf/gf/g/encoding/gjson"
"main/model"
)
func GetText(data string) (string, error) {
if j, err := gjson.DecodeToJson([]byte(data)); err != nil {
return "", errors.New("Get Text Error")
} else {
var result = j.GetString("results.0.values.text")
return result, nil
}
}
func ConvertJson(chattingInfo model.Chatting) string {
jsons, errs := json.Marshal(chattingInfo)
if errs != nil {
fmt.Print(errs.Error())
}
return string(jsons)
}
httpUtil.go
package Util
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
const url = "http://openapi.tuling123.com/openapi/api/v2"
func HttpPost(json string) (string, error) {
jsonStr := []byte(json)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err.Error())
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if !(resp.StatusCode == 200) {
return "", errors.New("Get Text Error")
}
return string(body), nil
}
model实体:
实体根据格式进行创建:
package model
type Chatting struct {
ReqType int `json:"reqType"`
Perception Perception `json:"perception"`
UserInfo UserInfo `json:"userInfo"`
}
package model
type InputText struct {
Text string `json:"text"`
}
package model
type Perception struct {
InputText InputText `json:"inputText"`
}
package model
type UserInfo struct {
ApiKey string `json:"apiKey"`
UserId string `json:"userId"`
}
因为不是以单个文件为单位运行,所以我们这次要设置为package方式
显示效果:
收工 洗漱睡觉!