wechatbot
English

Go SDK 简洁、地道、协程安全。仅标准库,无 CGO,32 个测试。使用 sync.Map 实现并发 context_token 访问。已在 Linux、macOS、Windows 上测试通过。

安装

go get github.com/corespeed-io/wechatbot/golang

快速开始

package main import ( "context" "fmt" wechatbot "github.com/corespeed-io/wechatbot/golang" ) func main() { ctx := context.Background() bot := wechatbot.New() creds, _ := bot.Login(ctx, false) fmt.Printf("已登录: %s\n", creds.AccountID) bot.OnMessage(func(msg *wechatbot.IncomingMessage) { bot.SendTyping(ctx, msg.UserID) bot.Reply(ctx, msg, fmt.Sprintf("Echo: %s", msg.Text)) }) bot.Run(ctx) }

配置

bot := wechatbot.New(wechatbot.Options{ BaseURL: "", // 默认: ilinkai.weixin.qq.com CredPath: "", // 默认: ~/.wechatbot/credentials.json OnQRURL: func(url string) { ... }, // 自定义二维码渲染 OnScanned: func() { ... }, OnExpired: func() { ... }, OnError: func(err error) { ... }, })

消息处理

bot.OnMessage(func(msg *wechatbot.IncomingMessage) { fmt.Printf("[%s] %s: %s\n", msg.Type, msg.UserID, msg.Text) for _, img := range msg.Images { fmt.Printf(" 图片: %s\n", img.URL) } for _, voice := range msg.Voices { fmt.Printf(" 语音: %s (%dms)\n", voice.Text, voice.DurationMs) } for _, file := range msg.Files { fmt.Printf(" 文件: %s (%d 字节)\n", file.FileName, file.Size) } })

发送消息

bot.Reply(ctx, msg, "你好!") // 回复(自动 context_token) bot.Send(ctx, userID, "主动消息") // 发送(需先有 context) bot.SendTyping(ctx, userID) // 显示输入中 bot.StopTyping(ctx, userID) // 取消输入中

生命周期

err := bot.Run(ctx) // 阻塞直到 Stop 或 context 取消 bot.Stop() // 优雅停止

会话恢复是自动的 —— 收到 -14 错误时,清除状态、删除凭证、重新扫码登录。

关键类型

type IncomingMessage struct { UserID string Text string Type ContentType // "text", "image", "voice", "file", "video" Timestamp time.Time Images []ImageContent Voices []VoiceContent Files []FileContent Videos []VideoContent QuotedMessage *QuotedMessage }
Go SDK — wechatbot/golang