实现登录微信
思路
1、 web端通过websocket连接与服务器通信
2、发送信息告知服务器登录微信
3、服务端实例化一个登录微信的对象,触发登录事件,这里就会生成一个登录二维码,并将二维码的链接发送到web端,同时服务端监听登录状态
4、web端显示二维码,同时监听登录状态
代码
声明登录微信对象
type WxBot struct {
Bot openwechat.Bot
ws *websocket.Conn
cId string
}
func NewWxBot(ws *websocket.Conn, c string) *WxBot {
return &WxBot{ws: ws, cId: c}
}
服务端监听微信登录状态:
bot.ScanCallBack = func(body []byte) {
data_b, _ := json.Marshal(&data{
Status: 1,
Content: "扫码成功",
Type: "wxcodeqr",
User: w.cId,
})
w.ws.WriteMessage(websocket.TextMessage, data_b)
}
bot.LoginCallBack = func(body []byte) {
res := string(body)
if strings.Contains(res, "200") {
data_b, _ := json.Marshal(&data{
Status: 2,
Content: "登录成功",
Type: "wxcodeqr",
User: w.cId,
})
dao.UpdateAutoEnable(w.cId, true)
w.ws.WriteMessage(websocket.TextMessage, data_b)
} else {
data_b, _ := json.Marshal(&data{
Status: -1,
Content: "登录失败",
Type: "wxcodeqr",
User: w.cId,
})
w.ws.WriteMessage(websocket.TextMessage, data_b)
}
}
使用协程,让微信运行起来:
wx := wxbot.NewWxBot(c.ws, c.data.Content)
go func() {
wx.Login()
}()
实现多开
声明一个全局对象,保存着登录过的微信,当有信息需要自动回复时,就去这个对象里面找就可以了
代码
全局对象:
type WxBot struct {
Id string
Bot *openwechat.Bot
Auto *model.Auto
}
var BOTS = make(map[string]*WxBot)
记录登录微信:
if store.BOTS[w.cId] == nil {
store.BOTS[w.cId] = &store.WxBot{
Id: w.cId,
Bot: bot,
}
} else {
// fmt.Println("store.BOTS[w.cId]== 1111")
store.BOTS[w.cId].Bot = bot
}
回复机制:
bot.MessageHandler = func(msg *openwechat.Message) {
fmt.Println("接收信息===:", msg.Content, store.BOTS[w.cId].Auto)
if store.BOTS[w.cId].Auto == nil {
return
}
if msg.IsSendByFriend() && store.BOTS[w.cId].Auto.AutoReply == true {
replyText(msg, *store.BOTS[w.cId].Auto)
}
if msg.IsAt() && store.BOTS[w.cId].Auto.AutoReply == true && store.BOTS[w.cId].Auto.AutoReplyGroup == true {
replyText(msg, *store.BOTS[w.cId].Auto)
}
}