前面我们写的是对接企业微信客服、微信公众号、微信小程序
现在来对接一下个人微信机器人
效果如图:
基于唯一客服的机器人接口实现的
.env文件的配置就是机器人接口
API_BASE=https://{部署域名}/2/robotMessage
API_ENT_ID={商户ID}
REPLY_TYPE=GROUP
下面是微信个人机器人对接的Golang实现源码
package mainimport ("fmt""github.com/eatmoreapple/openwechat""github.com/joho/godotenv""github.com/tidwall/gjson""io/ioutil""log""net/http""net/url""os""regexp""strings"
)func main() {err := godotenv.Load(".env")myUID := ""myNicname := ""// 读取环境变量api := os.Getenv("API_BASE")entId := os.Getenv("API_ENT_ID")replyType := os.Getenv("REPLY_TYPE")bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式// 注册消息处理函数bot.MessageHandler = func(msg *openwechat.Message) {if msg.IsText() {log.Printf("收到消息:%s\n", msg.Content)isSend := false//群聊if msg.IsSendByGroup() {sender, err := msg.SenderInGroup()if err == nil {log.Println("消息发送者:" + sender.NickName)}if strings.Contains(msg.Content, "@"+myNicname) {msg.Content = strings.TrimSpace(strings.ReplaceAll(msg.Content, "@"+myNicname, ""))isSend = true} else {isSend = false}} else {//单聊sender, err := msg.Sender()if err == nil {log.Println("消息发送者:" + sender.NickName)}if replyType != "GROUP" {isSend = true}}if isSend {data := url.Values{}data.Set("ent_id", entId)data.Set("visitor_id", msg.MsgId)data.Set("content", msg.Content)res, err := PostForm(api, data)if err == nil {r := gjson.Get(res, "result.content").String()r = TrimHtml(r)msg.ReplyText(r)}}}}// 注册登陆二维码回调bot.UUIDCallback = openwechat.PrintlnQrcodeUrl// 登陆if err := bot.Login(); err != nil {fmt.Println(err)return}// 获取登陆的用户self, err := bot.GetCurrentUser()if err != nil {fmt.Println(err)return}myUID = self.ID()myNicname = self.NickNamelog.Printf("当前登录用户:%s,uid:%s \n", myNicname, myUID)// 获取所有的好友//friends, err := self.Friends()//fmt.Println(friends, err)// 获取所有的群组//groups, err := self.Groups()//fmt.Println(groups, err)// 阻塞主goroutine, 直到发生异常或者用户主动退出bot.Block()
}//发送http post请求数据为form
func PostForm(url string, data url.Values) (string, error) {resp, err := http.PostForm(url, data)if err != nil {return "", err}defer resp.Body.Close()content, err := ioutil.ReadAll(resp.Body)if err != nil {return "", err}return string(content), nil
}/**
去除html标签,过滤html标签
*/
func TrimHtml(src string) string {//将HTML标签全转换成小写re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")src = re.ReplaceAllStringFunc(src, strings.ToLower)//去除STYLEre, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")src = re.ReplaceAllString(src, "")//去除SCRIPTre, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")src = re.ReplaceAllString(src, "")//去除所有尖括号内的HTML代码,并换成换行符re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")src = re.ReplaceAllString(src, "\n")//去除连续的换行符re, _ = regexp.Compile("\\s{2,}")src = re.ReplaceAllString(src, "\n")return strings.TrimSpace(src)
}