### Get All Groups (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Retrieves a list of all groups the user is a part of. This method should be called after the user has successfully logged in. ```Go groups, err := self.Groups() ``` -------------------------------- ### Get User Details Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Fetches detailed information for a specific user and returns a new User object populated with this data. This method is useful for obtaining comprehensive user information. ```go func (u *User) Detail() (*User, error) ``` -------------------------------- ### Set and Get Message Context (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Allows for setting and retrieving arbitrary key-value pairs associated with a message. This mechanism facilitates communication and state management between different message handler functions in a concurrent environment. ```Go msg.Set("hello", "world") value, exist := msg.Get("hello") ``` -------------------------------- ### Get Group Members (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Retrieves a list of all members within a specific group. This function returns the members and an error if any occurs. ```Go members, err := group.Members() ``` -------------------------------- ### Get All Official Accounts of Current User Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Fetches a list of all official accounts (MP) that the current user follows. An optional boolean parameter can be used to ensure the retrieval of the most up-to-date list. ```go mps, err := self.Mps() // self.Mps(true) ``` -------------------------------- ### Get Message Content (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Retrieves the content of an incoming message. This property is common across all message types, but is typically accessed when the message is identified as text. ```Go msg.Content ``` -------------------------------- ### Get Message Sender and Receiver (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Retrieves information about the sender and receiver of a message. For group messages, Sender() returns the group object, while SenderInGroup() specifically returns the user within the group who sent the message. Receiver() gets the recipient of the message. ```Go sender, err := msg.Sender() receiver, err := msg.Receiver() senderInGroup, err := msg.SenderInGroup() ``` -------------------------------- ### Get Current Logged-in User Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Retrieves the User object representing the currently logged-in user, typically obtained after a successful QR code scan. This object has all the properties and methods of a standard User. ```go self, err := bot.GetCurrentUser() ``` -------------------------------- ### Get File Transfer Helper Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Retrieves the special User object representing the 'File Transfer Helper' (文件传输助手), a built-in WeChat feature for transferring files to oneself. ```go fh, err := self.FileHelper() ``` -------------------------------- ### Get All Friends of Current User Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Fetches a list of all friends associated with the current logged-in user. An optional boolean parameter can be used to ensure the retrieval of the most up-to-date friend list. ```go Friends, err := self.Friends() // self.Friends(true) ``` -------------------------------- ### Get All Groups of Current User Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Retrieves a list of all groups the current user is a member of. Note that this list primarily includes groups saved in the phone's contacts. To include other groups, one must receive a message from them or explicitly save them to contacts. ```go groups, err := self.Groups() // self.Groups(true) ``` -------------------------------- ### Get Current User's Friend List Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Retrieves the list of all friends belonging to the current logged-in user. The returned list is a 'Friends' group, which is a collection of all friends, not necessarily organized into subgroups. ```go Friends, err := self.Friends() ``` -------------------------------- ### Go: Manage Bot Lifecycle with Context and Signals Source: https://context7.com/eatmoreapple/openwechat/llms.txt Demonstrates how to manage the Bot's lifecycle in Go using context.Context for graceful shutdown and signal handling for interruption. It includes setting up callbacks for login, logout, sync checks, and message errors. The code initializes a bot, sets up a heartbeat check, and listens for OS signals to trigger a controlled exit. ```go package main import ( "context" "fmt" "os" "os/signal" syscall "syscall" "time" "github.com/eatmoreapple/openwechat" ) func main() { // 创建可取消的 context ctx, cancel := context.WithCancel(context.Background()) // 使用自定义 context 创建 Bot bot := openwechat.DefaultBot(openwechat.Desktop, openwechat.WithContextOption(ctx)) // 设置退出回调 bot.LogoutCallBack = func(bot *openwechat.Bot) { fmt.Println("机器人已退出") // 获取崩溃原因 reason := bot.CrashReason() if reason != nil { fmt.Printf("退出原因: %v\n", reason) } } // 设置心跳回调(监控连接状态) bot.SyncCheckCallback = func(resp openwechat.SyncCheckResponse) { fmt.Printf("心跳检查 - RetCode: %s, Selector: %s\n", resp.RetCode, resp.Selector) } // 设置消息错误处理 bot.MessageErrorHandler = func(err error) error { fmt.Printf("消息处理错误: %v\n", err) // 返回 nil 表示忽略错误继续运行 // 返回 error 表示终止运行 return nil } bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() // 启动定时任务 go func() { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: // 检查机器人是否存活 if bot.Alive() { fmt.Println("机器人运行正常") } else { fmt.Println("机器人已离线") return } case <-ctx.Done(): return } } }() // 监听系统信号,优雅退出 sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigChan fmt.Println("收到退出信号,正在退出...") // 方式1:通过 context 取消 cancel() // 方式2:调用 Logout 主动退出 // bot.Logout() // 方式3:带原因退出 // bot.ExitWith(errors.New("用户主动退出")) }() // 阻塞主程序 err := bot.Block() if err != nil { fmt.Printf("Bot 退出: %v\n", err) } } ``` -------------------------------- ### Receive and Reply to Messages (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md This snippet demonstrates how to set up a message handler to receive incoming messages and reply to them. It specifically shows how to respond to a 'ping' message with 'pong'. This is the core mechanism for interactive bots. ```Go bot.MessageHandler = func (msg *openwechat.Message) { if msg.IsText() && msg.Content == "ping" { msg.ReplyText("pong") } } ``` -------------------------------- ### Retrieve Current User and Contact Lists in Go Source: https://context7.com/eatmoreapple/openwechat/llms.txt Demonstrates how to initialize the bot, authenticate, and retrieve the current user's profile along with their friends, groups, and official account lists. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) 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 } fmt.Printf("用户ID: %d\n", self.ID()) friends, _ := self.Friends() groups, _ := self.Groups() mps, _ := self.Mps() fmt.Printf("好友数量: %d, 群组数量: %d, 公众号数量: %d\n", friends.Count(), groups.Count(), mps.Count()) self.FileHelper().SendText("机器人已上线") bot.Block() } ``` -------------------------------- ### Implement HotLogin for Session Persistence Source: https://context7.com/eatmoreapple/openwechat/llms.txt Demonstrates how to use HotLogin to save session data to a file, allowing the bot to reconnect without re-scanning the QR code. It automatically falls back to manual login if the session is invalid. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) reloadStorage := openwechat.NewFileHotReloadStorage("storage.json") defer reloadStorage.Close() err := bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption()) if err != nil { fmt.Println("登录失败:", err) return } fmt.Println("热登录成功") self, _ := bot.GetCurrentUser() fmt.Printf("当前用户: %s\n", self.NickName) bot.Block() } ``` -------------------------------- ### Perform Standard Login Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Initiates the login process. The Login method blocks the current goroutine until the authentication process succeeds or fails. ```go bot.Login() ``` -------------------------------- ### Custom Message Matching with MatchFunc (Go) Source: https://context7.com/eatmoreapple/openwechat/llms.txt Illustrates how to use MatchFunc and the MessageMatchDispatcher to create flexible message routing and handling logic. It covers matching based on sender type, nickname, content, and combining multiple conditions for precise message filtering and response. ```go package main import ( "fmt" "strings" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) dispatcher := openwechat.NewMessageMatchDispatcher() // 使用预定义的匹配函数 // 只匹配好友消息 dispatcher.RegisterHandler(openwechat.SenderFriendRequired(), func(ctx *openwechat.MessageContext) { fmt.Println("这是好友消息") }) // 只匹配群组消息 dispatcher.RegisterHandler(openwechat.SenderGroupRequired(), func(ctx *openwechat.MessageContext) { fmt.Println("这是群组消息") }) // 只匹配公众号消息 dispatcher.RegisterHandler(openwechat.SenderMpRequired(), func(ctx *openwechat.MessageContext) { fmt.Println("这是公众号消息") }) // 匹配特定昵称的发送者 dispatcher.RegisterHandler(openwechat.SenderNickNameEqualMatchFunc("张三"), func(ctx *openwechat.MessageContext) { ctx.ReplyText("你好张三!") }) // 匹配昵称包含特定字符的发送者 dispatcher.RegisterHandler(openwechat.SenderNickNameContainsMatchFunc("客服"), func(ctx *openwechat.MessageContext) { ctx.ReplyText("收到客服消息") }) // 组合多个匹配条件 combinedMatch := openwechat.MatchFuncList( openwechat.SenderFriendRequired(), openwechat.SenderNickNameContainsMatchFunc("VIP"), func(msg *openwechat.Message) bool { return msg.IsText() && strings.Contains(msg.Content, "订单") }, ) dispatcher.RegisterHandler(combinedMatch, func(ctx *openwechat.MessageContext) { ctx.ReplyText("VIP客户订单消息,优先处理") }) // 自定义复杂匹配函数 customMatch := func(msg *openwechat.Message) bool { // 只处理群消息中@我的文本消息 if !msg.IsSendByGroup() || !msg.IsText() { return false } return msg.IsAt() } dispatcher.RegisterHandler(customMatch, func(ctx *openwechat.MessageContext) { sender, _ := ctx.SenderInGroup() ctx.ReplyText(fmt.Sprintf("@%s 你好,有什么需要帮助的?", sender.NickName)) }) // 使用 SenderMatchFunc 自定义发送者匹配 vipMatch := openwechat.SenderMatchFunc( func(user *openwechat.User) bool { return user.IsFriend() }, func(user *openwechat.User) bool { return strings.HasPrefix(user.RemarkName, "VIP-") }, ) dispatcher.RegisterHandler(vipMatch, func(ctx *openwechat.MessageContext) { ctx.ReplyText("尊贵的VIP客户您好!") }) // 消息处理链(中间件模式) dispatcher.OnText( // 第一个处理器:记录日志 func(ctx *openwechat.MessageContext) { fmt.Printf("[LOG] 收到消息: %s\n", ctx.Content) ctx.Next() // 继续执行下一个处理器 }, // 第二个处理器:检查权限 func(ctx *openwechat.MessageContext) { sender, _ := ctx.Sender() if sender.RemarkName == "黑名单" { ctx.Abort() // 中断处理链 return } ctx.Next() }, // 第三个处理器:实际业务处理 func(ctx *openwechat.MessageContext) { ctx.ReplyText("消息处理完成") }, ) bot.MessageHandler = dispatcher.AsMessageHandler() bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() bot.Block() } ``` -------------------------------- ### Manage Friends and Send Messages in Go Source: https://context7.com/eatmoreapple/openwechat/llms.txt Shows how to search for friends using nicknames or remarks, send text, images, and files, and perform message revocation. It also demonstrates bulk messaging with delays to avoid rate limits. ```go package main import ( "fmt" "os" "time" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() self, _ := bot.GetCurrentUser() friends, _ := self.Friends() results := friends.SearchByNickName(1, "张三") if results.Count() > 0 { friend := results.First() sentMsg, _ := friend.SendText("你好!") if sentMsg.CanRevoke() { sentMsg.Revoke() } imgFile, _ := os.Open("image.jpg") friend.SendImage(imgFile) } friends.SendText("群发消息测试", time.Second) bot.Block() } ``` -------------------------------- ### Get Unique User Identifier Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Provides a method to retrieve the unique and persistent identifier for a user. Unlike UserName, this ID does not change with login sessions, ensuring a stable reference. ```go func (u *User) ID() string ``` -------------------------------- ### Implement PushLogin for One-Click Confirmation Source: https://context7.com/eatmoreapple/openwechat/llms.txt Utilizes PushLogin to enable PC-style login where the user confirms the login request on their mobile device instead of scanning a QR code. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) reloadStorage := openwechat.NewFileHotReloadStorage("push_storage.json") defer reloadStorage.Close() err := bot.PushLogin(reloadStorage, openwechat.NewRetryLoginOption()) if err != nil { fmt.Println("登录失败:", err) return } fmt.Println("免扫码登录成功") if bot.Alive() { fmt.Println("机器人运行中...") } bot.Block() } ``` -------------------------------- ### Create DefaultBot Instance Source: https://context7.com/eatmoreapple/openwechat/llms.txt Initializes a basic WeChat bot instance with desktop mode enabled to bypass login restrictions. It includes callbacks for QR code generation, scan events, and login success. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.ScanCallBack = func(body openwechat.CheckLoginResponse) { fmt.Println("扫码成功,请在手机上确认登录") } bot.LoginCallBack = func(body openwechat.CheckLoginResponse) { fmt.Println("登录成功") } if err := bot.Login(); err != nil { fmt.Println("登录失败:", err) return } self, err := bot.GetCurrentUser() if err != nil { fmt.Println("获取用户失败:", err) return } fmt.Printf("登录用户: %s\n", self.NickName) bot.Block() } ``` -------------------------------- ### Initialize Bot Object Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Creates a new Bot instance to manage WeChat interactions. The default constructor initializes the bot for standard web-based WeChat communication. ```go bot := openwechat.DefaultBot() ``` -------------------------------- ### Configure Scan and Login Callbacks Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Registers callbacks to monitor the status of the login process, such as retrieving user avatar info after a scan or executing logic upon successful login. ```go bot.ScanCallBack = func(body openwechat.CheckLoginResponse) { fmt.Println(string(body)) } bot.LoginCallBack = func(body openwechat.CheckLoginResponse) { fmt.Println(string(body)) } ``` -------------------------------- ### Self - Get Current Logged-in User Source: https://context7.com/eatmoreapple/openwechat/llms.txt The `Self` object represents the currently logged-in user and provides core functionalities such as retrieving friend lists, group lists, official account lists, and sending messages. ```APIDOC ## Self - Get Current Logged-in User ### Description The `Self` object represents the currently logged-in user and provides core functionalities such as retrieving friend lists, group lists, official account lists, and sending messages. ### Method GET ### Endpoint /self ### Parameters None ### Request Example ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) 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 } fmt.Printf("用户ID: %d\n", self.ID()) fmt.Printf("用户昵称: %s\n", self.NickName) fmt.Printf("用户签名: %s\n", self.Signature) // 获取所有好友 friends, err := self.Friends() if err != nil { fmt.Println("获取好友失败:", err) return } fmt.Printf("好友数量: %d\n", friends.Count()) // 获取所有群组 groups, err := self.Groups() if err != nil { fmt.Println("获取群组失败:", err) return } fmt.Printf("群组数量: %d\n", groups.Count()) // 获取所有公众号 mps, err := self.Mps() if err != nil { fmt.Println("获取公众号失败:", err) return } fmt.Printf("公众号数量: %d\n", mps.Count()) // 获取文件传输助手 fileHelper := self.FileHelper() fileHelper.SendText("机器人已上线") bot.Block() } ``` ### Response #### Success Response (200) - **ID** (int) - The unique identifier of the user. - **NickName** (string) - The nickname of the user. - **Signature** (string) - The signature of the user. #### Response Example ```json { "ID": 123456789, "NickName": "YourWechatName", "Signature": "Hello, world!" } ``` ``` -------------------------------- ### Implement Push Login Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Enables push-based login where the user confirms the login request on their mobile device. This is a more convenient alternative to scanning QR codes for subsequent logins. ```go bot := openwechat.DefaultBot() reloadStorage := openwechat.NewFileHotReloadStorage("storage.json") defer reloadStorage.Close() err = bot.PushLogin(reloadStorage, openwechat.NewRetryLoginOption()) ``` -------------------------------- ### Send Video Message (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Sends a video message to a group. The video file is provided as an io.Reader. Ensure the file path is correct. ```Go video, _ := os.Open("your video path") defer video.Close() group.SendVideo(img) ``` -------------------------------- ### Implement Hot Login Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Uses a file-based storage to persist session information, allowing for re-authentication without re-scanning the QR code. The retry option ensures that if the session is expired, the bot falls back to manual QR scanning. ```go reloadStorage := openwechat.NewFileHotReloadStorage("storage.json") defer reloadStorage.Close() bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption()) ``` -------------------------------- ### SentMessage Operations: Recall and Forward Messages (Go) Source: https://context7.com/eatmoreapple/openwechat/llms.txt Demonstrates how to send text messages, obtain the SentMessage object, check if a message can be recalled within a 2-minute window, and then revoke it. It also shows how to forward messages to friends and groups, including options for delayed forwarding. ```go package main import ( "fmt" "time" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() self, _ := bot.GetCurrentUser() friends, _ := self.Friends() groups, _ := self.Groups() friend := friends.First() if friend == nil { fmt.Println("没有好友") return } // 发送消息并获取已发送消息对象 sentMsg, err := friend.SendText("测试消息") if err != nil { fmt.Println("发送失败:", err) return } fmt.Printf("消息ID: %s\n", sentMsg.MsgId) // 检查是否可以撤回(2分钟内) if sentMsg.CanRevoke() { fmt.Println("消息可以撤回") // 等待5秒后撤回 time.Sleep(5 * time.Second) err := sentMsg.Revoke() if err != nil { fmt.Println("撤回失败:", err) } else { fmt.Println("消息已撤回") } } // 发送新消息用于转发测试 newMsg, _ := friend.SendText("这条消息将被转发") // 转发给其他好友 otherFriends := friends.Search(3, func(f *openwechat.Friend) bool { return f.UserName != friend.UserName }) if otherFriends.Count() > 0 { // 转发消息(带延迟) err := newMsg.ForwardToFriends(otherFriends...) if err != nil { fmt.Println("转发失败:", err) } // 自定义延迟转发 err = newMsg.ForwardToFriendsWithDelay(time.Second, otherFriends...) if err != nil { fmt.Println("延迟转发失败:", err) } } // 转发给群组 if groups.Count() > 0 { targetGroups := groups.Search(2, func(g *openwechat.Group) bool { return true }) newMsg.ForwardToGroups(targetGroups...) } bot.Block() } ``` -------------------------------- ### Configure QR Code Callback Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Registers a callback function to handle the login QR code. This allows the developer to define how the QR code URL is presented to the user for scanning. ```go bot.UUIDCallback = openwechat.PrintlnQrcodeUrl ``` -------------------------------- ### Handle WeChat Messages with openwechat Source: https://context7.com/eatmoreapple/openwechat/llms.txt Demonstrates how to process various message types including text, files, images, and friend requests. It covers identifying message sources, replying to messages, saving attachments, and managing message state. ```go package main import ( "fmt" "os" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.MessageHandler = func(msg *openwechat.Message) { sender, err := msg.Sender() if err != nil { fmt.Println("获取发送者失败:", err) return } fmt.Printf("发送者: %s\n", sender.NickName) if msg.IsSendByFriend() { fmt.Println("来自好友的消息") } else if msg.IsSendByGroup() { fmt.Println("来自群组的消息") groupSender, _ := msg.SenderInGroup() fmt.Printf("群内发送者: %s\n", groupSender.NickName) } if msg.IsAt() { fmt.Println("有人@我") msg.ReplyText("你@我了,有什么事?") } if msg.HasFile() { filename := fmt.Sprintf("downloads/%s", msg.FileName) msg.SaveFileToLocal(filename) } if msg.IsText() { msg.ReplyText("你发送了: " + msg.Content) } msg.AsRead() } bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() bot.Block() } ``` -------------------------------- ### Control Bot Liveness and Lifecycle - Go Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md This snippet demonstrates how to check if the bot is alive using the Alive() method and how to control its lifecycle. The bot's liveness can be managed by passing a context.Context to WithContext, which allows cancellation to stop the bot. Alternatively, bot.Logout() can be called to explicitly terminate the bot, after which Alive() will return false. ```Go func (b *Bot) Alive() bool ``` ```Go ctx, cancel := context.WithCancel(context.Background()) bot := openwechat.DefaultBot(openwechat.WithContext(ctx)) ``` -------------------------------- ### Handle Incoming Messages with MessageHandler Source: https://context7.com/eatmoreapple/openwechat/llms.txt Configures a central message handler to process various incoming message types such as text, images, voice, and friend requests. Includes logic for auto-replying and handling message recalls. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.MessageHandler = func(msg *openwechat.Message) { switch { case msg.IsText(): fmt.Printf("收到文本消息: %s\n", msg.Content) if msg.Content == "ping" { msg.ReplyText("pong") } case msg.IsPicture(): fmt.Println("收到图片消息") msg.ReplyText("已收到图片") case msg.IsVoice(): fmt.Println("收到语音消息") case msg.IsFriendAdd(): fmt.Println("收到好友添加请求") msg.Agree("你好,我是机器人") case msg.IsRecalled(): revokeMsg, _ := msg.RevokeMsg() fmt.Printf("消息被撤回: %s\n", revokeMsg.RevokeMsg.ReplaceMsg) } } bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() bot.Block() } ``` -------------------------------- ### Send File Message (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Sends a file message. The file is provided as an io.Reader. An optional delay can be specified between messages. This function can be used to send files to individual friends or groups. ```Go func (f Friends) SendFile(file io.Reader, delay ...time.Duration) error ``` ```Go func (g Groups) SendFile(file io.Reader, delay ...time.Duration) error ``` ```Go file, _ := os.Open("your file path") defer file.Close() friend.SendFile(file) ``` ```Go file, _ := os.Open("your file path") defer file.Close() group.SendFile(file) ``` -------------------------------- ### Reply to Messages with Different Content Types (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Allows the bot to reply to messages using various formats, including text, emoticons (via MD5 or file path), images, videos, and generic files. This enables rich communication responses. ```Go msg.ReplyText("hello") emoticon, _ := os.Open("your Emoticon path") defer emoticon.Close() msg.ReplyEmoticon("md5 string", nil) // or msg.ReplyEmoticon("", emoticon) img, _ := os.Open("your img path") defer img.Close() msg.ReplyImage(img) video, _ := os.Open("your video path") defer video.Close() msg.ReplyVideo(video) file, _ := os.Open("your file path") defer file.Close() msg.ReplyFile(file) ``` -------------------------------- ### Search Groups by Condition (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Searches for groups based on a list of custom condition functions. It allows limiting the number of results. All provided condition functions must return true for a group to be included in the results. ```Go func (g Groups) Search(limit int, condFuncList ...func(group *Group) bool) (results Groups) ``` -------------------------------- ### Manage Groups and Members in Go Source: https://context7.com/eatmoreapple/openwechat/llms.txt Covers group operations including searching, sending media messages, retrieving group members, creating new groups, and adding friends to existing groups. ```go package main import ( "fmt" "time" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() self, _ := bot.GetCurrentUser() groups, _ := self.Groups() results := groups.SearchByNickName(1, "测试群") if results.Count() > 0 { group := results.First() group.SendText("大家好!") members, _ := group.Members() fmt.Printf("群成员数量: %d\n", members.Count()) } groups.SendText("群发通知", time.Second) bot.Block() } ``` -------------------------------- ### Search Groups by Nickname (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Searches for groups by their nickname. It allows limiting the number of results returned. The function takes a limit and the nickname string as input. ```Go func (g Groups) SearchByNickName(limit int, nickName string) (results Groups) ``` -------------------------------- ### Handle Friend Requests and Set Message Read Status (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Enables the bot to automatically agree to incoming friend requests and to mark messages as read. Agreeing a friend request returns the newly added friend object, while AsRead() updates the message's read status. ```Go friend, err := msg.Agree() // Requires msg.IsFriendAdd() to be true msg.AsRead() ``` -------------------------------- ### Block Main Program Execution - Go Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md The bot.Block() method is used to indefinitely block the main program's execution. This ensures the bot continues to run until the user explicitly exits or a network error occurs. ```Go bot.Block() ``` -------------------------------- ### Handle Messages with Dispatcher Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Uses a MessageMatchDispatcher to route incoming messages based on their type or content. This provides a structured way to handle text, images, or voice messages. ```go dispatcher := openwechat.NewMessageMatchDispatcher() dispatcher.OnText(func(ctx *openwechat.MessageContext){ msg := ctx.Message msg.ReplyText("hello") }) bot.MessageHandler = dispatcher.AsMessageHandler() ``` -------------------------------- ### Send File to Friend Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Transmits a file to a specified friend. The file is passed as an `os.File` object. Similar to sending images, this can be done via the Self object or the Friend object. ```go file, _ := os.Open("your file path") deffer file.Close() self.SendFileToFriend(friend, file) // 或者 // friend.SendFile(img) ``` -------------------------------- ### Send Image Message to Friend Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Sends an image file to a specified friend. The image is provided as an `os.File` object. This operation can be initiated either through the Self object or the Friend object directly. ```go // 确保获取了有效的好友对象 img, _ := os.Open("your file path") deffer img.Close() self.SendImageToFriend(friend, img) // 或者 // friend.SendImage(img) ``` -------------------------------- ### Send File to Group Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Transmits a file to a specified group chat. The file is passed as an `os.File` object. This operation can be initiated via the Self object or directly on the group object. ```go file, _ := os.Open("your file path") deffer file.Close() self.SendFileToGroup(group, file) // group.SendFile(file) ``` -------------------------------- ### Send Image to Group Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Sends an image file to a specified group chat. The image is provided as an `os.File` object and can be sent using either the Self object or the group object. ```go img, _ := os.Open("your file path") deffer img.Close() self.SendImageToGroup(group, img) // group.SendImage(img) ``` -------------------------------- ### Search Friends by Remark Name (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Searches for friends based on their remark name. It allows limiting the number of results returned. The function takes a limit and the remark name as input and returns a list of matching friends. ```Go func (f Friends) SearchByRemarkName(limit int, remarkName string) (results Friends) ``` -------------------------------- ### Send Image Message (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Sends an image message. The image is provided as an io.Reader. An optional delay can be set between messages. This function is available for both individual friends and groups. ```Go func (f Friends) SendImage(file io.Reader, delay ...time.Duration) error ``` ```Go func (g Groups) SendImage(file io.Reader, delay ...time.Duration) error ``` ```Go friend.SendImage(img) ``` ```Go img, _ := os.Open("your image path") defer img.Close() friend.SendImage(img) ``` ```Go group.SendImage(img) ``` ```Go img, _ := os.Open("your image path") defer img.Close() group.SendImage(img) ``` -------------------------------- ### Define User Structure in Go Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Defines the abstract User structure used in Openwechat, encompassing properties for friends, groups, and official accounts. It includes fields for user identification, status, and personal information, along with nested structures for members and self-information. ```go type User struct { Uin int HideInputBarFlag int StarFriend int Sex int AppAccountFlag int VerifyFlag int ContactFlag int WebWxPluginSwitch int HeadImgFlag int SnsFlag int IsOwner int MemberCount int ChatRoomId int UniFriend int OwnerUin int Statues int AttrStatus int Province string City string Alias string DisplayName string KeyWord string EncryChatRoomId string UserName string NickName string HeadImgUrl string RemarkName string PYInitial string PYQuanPin string RemarkPYInitial string RemarkPYQuanPin string Signature string MemberList Members Self *Self } ``` -------------------------------- ### Dispatch Messages with MessageMatchDispatcher Source: https://context7.com/eatmoreapple/openwechat/llms.txt Uses a dispatcher to route messages to specific handler functions based on type, sender, or content. Supports asynchronous processing and chainable middleware logic. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) dispatcher := openwechat.NewMessageMatchDispatcher() dispatcher.SetAsync(true) dispatcher.OnText(func(ctx *openwechat.MessageContext) { fmt.Printf("文本消息: %s\n", ctx.Content) ctx.ReplyText("收到文本") }) dispatcher.OnImage(func(ctx *openwechat.MessageContext) { fmt.Println("收到图片") ctx.ReplyText("图片已收到") }) dispatcher.OnFriend(func(ctx *openwechat.MessageContext) { sender, _ := ctx.Sender() fmt.Printf("好友 %s 发来消息\n", sender.NickName) }) dispatcher.OnGroup(func(ctx *openwechat.MessageContext) { sender, _ := ctx.Sender() fmt.Printf("群 %s 收到消息\n", sender.NickName) }) dispatcher.OnFriendAdd(func(ctx *openwechat.MessageContext) { ctx.Agree("欢迎添加") }) dispatcher.OnRecalled(func(ctx *openwechat.MessageContext) { fmt.Println("检测到消息撤回") }) dispatcher.OnFriendByNickName("张三", func(ctx *openwechat.MessageContext) { fmt.Println("收到张三的消息") ctx.ReplyText("你好,张三!") }) bot.MessageHandler = dispatcher.AsMessageHandler() bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() bot.Block() } ``` -------------------------------- ### Count Groups (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Counts the total number of groups the user is a part of. This function returns an integer representing the group count. ```Go groups.Count() // => int ``` -------------------------------- ### Manage WeChat Contacts and Users Source: https://context7.com/eatmoreapple/openwechat/llms.txt Shows how to retrieve the current user's contact list, identify user types (friends, groups, official accounts), and perform operations like saving avatars, searching contacts, and pinning chats. ```go package main import ( "fmt" "github.com/eatmoreapple/openwechat" ) func main() { bot := openwechat.DefaultBot(openwechat.Desktop) bot.UUIDCallback = openwechat.PrintlnQrcodeUrl bot.Login() self, _ := bot.GetCurrentUser() members, _ := self.Members() for _, member := range members { if member.IsFriend() { friend, _ := member.AsFriend() fmt.Printf("好友: %s\n", friend.NickName) } member.SaveAvatar(fmt.Sprintf("avatars/%s.jpg", member.UserName)) if member.IsPin() { member.UnPin() } else { member.Pin() } } bot.Block() } ``` -------------------------------- ### Save Friend Avatar (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Saves the avatar of a specific friend to a local file. The filename for saving the avatar is provided as an argument. ```Go friend.SaveAvatar("avatar.png") ``` -------------------------------- ### Save Group Avatar (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Saves the avatar of a specific group to a local file. The filename for saving the avatar is provided as an argument. ```Go group.SaveAvatar("group.png") ``` -------------------------------- ### Search Friends by Custom Conditions Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Searches for friends within a Friends list based on a set of custom conditions. It allows limiting the number of results and applying multiple boolean functions that must all be true for a friend to be included. ```go func (f Friends) Search(limit int, condFuncList ...func(friend *Friend) bool) (results Friends) // 例:查询昵称为eatmoreapple的1个好友 sult := Friends.Search(1, func(friend *openwechat.Friend) bool {return friend.NickName == "eatmoreapple"}) ``` -------------------------------- ### Add Friend to Group (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Adds a specific friend into a group. This function requires both the friend object and the group object to be available. ```Go friend.AddIntoGroup(group) ``` -------------------------------- ### Add Friends to Group (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Adds one or more friends into a specific group. This function takes a friend object as an argument. ```Go group.AddFriendsIn(friend) ``` -------------------------------- ### Check Message Type (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Provides boolean methods to determine the type of an incoming message. These methods allow for conditional logic based on message content, such as identifying text, pictures, or friend requests. ```Go msg.IsText() msg.IsPicture() msg.IsLocation() msg.IsVoice() msg.IsFriendAdd() msg.IsCard() msg.IsVideo() msg.IsRecalled() msg.IsSystem() msg.IsTransferAccounts() msg.IsSendRedPacket() msg.IsReceiveRedPacket() msg.IsIsPaiYiPai() msg.IsTickled() msg.IsTickledMe() msg.IsJoinGroup() ``` -------------------------------- ### Set Friend Remark Name (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Sets or updates the remark name for a specific friend. The new remark name is provided as a string argument. ```Go friend.SetRemarkName("你的备注") ``` -------------------------------- ### Manage Sent Messages (Go) Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/message.md Handles actions related to messages that have already been sent by the user. This includes revoking messages within a 2-minute window, checking if a message can be revoked, and forwarding messages to other friends or groups. ```Go sentMsg.Revoke() // Within 2 minutes of sending sentMsg.CanRevoke() sentMsg.ForwardToFriends(friend1, friend2) sentMsg.ForwardToGroups(group1, group2) ``` -------------------------------- ### Forward Message to Multiple Friends Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Forwards a message to multiple friends simultaneously. This can be initiated using the Self object or the SentMessage object. ```go sentMesaage, _ := friend.SendText("hello") self.ForwardMessageToFriends(sentMesaage, friends1, friends2) // sentMesaage.ForwardToFriends(friends1, friends2) ``` -------------------------------- ### Search Friends by Nickname Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Searches for friends within a Friends list by their nickname. It allows specifying a limit for the number of results returned. ```go func (f Friends) SearchByNickName(limit int, nickName string) (results Friends) // * `limit`:为限制好友查找的个数 // * `nickname`:查询指定昵称的好友 // * `results`:返回满足条件的好友组 ``` -------------------------------- ### Friend List Structure Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Defines the Friends type as a slice of pointers to Friend objects, representing a collection of friends. ```go type Friends []*Friend ``` -------------------------------- ### Set Remark Name for Friend Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Allows setting or updating the remark name (nickname) for a specific friend. This operation can be performed using either the Self object or the Friend object. ```go self.SetRemarkNameToFriend(friend, "你的备注") // 或者 // friend.SetRemarkName("你的备注") ``` -------------------------------- ### Bot Lifecycle Control Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/bot.md Methods for blocking the main execution thread and checking the Bot's active status. ```APIDOC ## Block Execution ### Description Blocks the main program execution until the user logs out or a network error occurs. ### Method N/A (Method Call) ### Endpoint bot.Block() --- ## Check Bot Status ### Description Checks if the current Bot instance is still alive and connected. ### Method N/A (Method Call) ### Endpoint bot.Alive() ### Response - **result** (bool) - Returns true if the bot is active, false otherwise. --- ## Manage Bot Lifecycle with Context ### Description Configures the Bot lifecycle using context to allow for controlled shutdowns. ### Request Example ```go ctx, cancel := context.WithCancel(context.Background()) bot := openwechat.DefaultBot(openwechat.WithContext(ctx)) ``` ### Note When the context is cancelled, the Bot will stop. Alternatively, calling `bot.Logout()` will terminate the session and `bot.Alive()` will return false. ``` -------------------------------- ### Add Multiple Friends to Group Source: https://github.com/eatmoreapple/openwechat/blob/master/docs/user.md Adds multiple friends into a specified group chat. It is recommended that the initiator is the group owner for higher success rates. This operation can be performed using the Self object or the group object. ```go self.AddFriendsIntoGroup(group, friend1, friend2) // friend1, friend2 为不定长参数 // group.AddFriendsIn(friend1, friend2) ```