### Start Go Wechaty Bot and Handle Events in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt Shows how to start a Go Wechaty bot instance and handle its lifecycle. It covers manual starting with error handling and the recommended `DaemonStart()` method for production, which blocks until an interrupt signal. ```go package main import ( "fmt" "log" "github.com/wechaty/go-wechaty/wechaty" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) // Option 1: Start with manual error handling err := bot.Start() if err != nil { log.Fatalf("Failed to start bot: %v", err) } fmt.Println("Bot started successfully") // Option 2: DaemonStart blocks until SIGINT (Ctrl+C) // This is the recommended approach for production bot.DaemonStart() // Panics on error, blocks until interrupted } ``` -------------------------------- ### Install Go Wechaty Package Source: https://github.com/wechaty/go-wechaty/blob/master/README.md Command to install the go-wechaty library using the Go module system. ```shell go get github.com/wechaty/go-wechaty ``` -------------------------------- ### Initialize and Start a Wechaty Bot Source: https://github.com/wechaty/go-wechaty/blob/master/README.md Demonstrates how to initialize a new Wechaty instance and register event handlers for QR code scanning, user login, and message reception before starting the bot in daemon mode. ```go package main import ( "fmt" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" ) func main() { wechaty.NewWechaty(). OnScan(func(context *wechaty.Context, qrCode string, status schemas.ScanStatus, data string) { fmt.Printf("Scan QR Code to login: %s\nhttps://wechaty.github.io/qrcode/%s\n", status, qrCode) }). OnLogin(func(context *wechaty.Context, user *user.ContactSelf) { fmt.Printf("User %s logined\n", user) }). OnMessage(func(context *wechaty.Context, message *user.Message) { fmt.Printf("Message: %s\n", message) }).DaemonStart() } ``` -------------------------------- ### Development Build Commands Source: https://github.com/wechaty/go-wechaty/blob/master/README.md Standard Makefile commands to install dependencies and run tests for the project. ```shell make install make test ``` -------------------------------- ### Implement a Full-Featured Ding-Dong Bot in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt This example demonstrates how to initialize a Go Wechaty bot, register event listeners for lifecycle events, and implement a message handler that responds to specific triggers with text, images, and URL links. ```go package main import ( "fmt" "log" "net/url" "os" "time" "github.com/mdp/qrterminal/v3" "github.com/wechaty/go-wechaty/wechaty" wp "github.com/wechaty/go-wechaty/wechaty-puppet" "github.com/wechaty/go-wechaty/wechaty-puppet/filebox" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: os.Getenv("WECHATY_TOKEN"), })) bot.OnScan(onScan) bot.OnLogin(onLogin) bot.OnLogout(onLogout) bot.OnMessage(onMessage) bot.OnError(onError) bot.OnReady(onReady) log.Println("Starting bot...") bot.DaemonStart() } func onScan(ctx *wechaty.Context, qrCode string, status schemas.ScanStatus, data string) { if status == schemas.ScanStatusWaiting || status == schemas.ScanStatusTimeout { qrterminal.GenerateHalfBlock(qrCode, qrterminal.L, os.Stdout) qrcodeUrl := fmt.Sprintf("https://wechaty.js.org/qrcode/%s", url.QueryEscape(qrCode)) fmt.Printf("Scan QR Code to login: %s\nStatus: %s\n", qrcodeUrl, status) return } fmt.Printf("Scan status: %s\n", status) } func onLogin(ctx *wechaty.Context, user *user.ContactSelf) { fmt.Printf("User %s logged in\n", user.Name()) } func onLogout(ctx *wechaty.Context, user *user.ContactSelf, reason string) { fmt.Printf("User %s logged out: %s\n", user.Name(), reason) } func onReady(ctx *wechaty.Context) { fmt.Println("Bot is ready to receive messages!") } func onError(ctx *wechaty.Context, err error) { log.Printf("Error: %v\n", err) } func onMessage(ctx *wechaty.Context, message *user.Message) { log.Printf("Received: %s\n", message) if message.Self() { log.Println("Skipping self message") return } if message.Age() > 2*time.Minute { log.Println("Skipping old message") return } if message.Type() != schemas.MessageTypeText || message.Text() != "#ding" { return } _, err := message.Say("dong") if err != nil { log.Printf("Error sending dong: %v\n", err) return } fileBox := filebox.FromUrl("https://wechaty.github.io/wechaty/images/bot-qr-code.png") _, err = message.Say(fileBox) urlLink := user.NewUrlLink(&schemas.UrlLinkPayload{ Description: "Go Wechaty is a Conversational SDK for Chatbot Makers", ThumbnailUrl: "https://wechaty.js.org/img/icon.png", Title: "wechaty/go-wechaty", Url: "https://github.com/wechaty/go-wechaty", }) _, err = message.Say(urlLink) } ``` -------------------------------- ### Go Wechaty: Controlling Plugin Execution with Context Source: https://context7.com/wechaty/go-wechaty/llms.txt Illustrates how to use the Context object in Go Wechaty plugins to manage execution flow and share data. This example shows an authentication plugin storing user data and aborting further processing for unauthorized users, a command handler retrieving context data, and a logger plugin conditionally logging messages based on context activation. ```go package main import ( "fmt" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) // First plugin - authentication authPlugin := wechaty.NewPlugin() authPlugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } talker := message.Talker() // Store user data in context ctx.SetData("user_id", talker.ID()) ctx.SetData("user_name", talker.Name()) // Check if user is authorized if talker.Name() == "unauthorized_user" { fmt.Println("Unauthorized user, aborting further processing") ctx.Abort() // Stop all subsequent plugins return } fmt.Println("User authorized, continuing...") }) // Second plugin - command handler commandPlugin := wechaty.NewPlugin() commandPlugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } // Retrieve data from context userName := ctx.GetData("user_name") fmt.Printf("Processing command from: %v\n", userName) if message.Type() == schemas.MessageTypeText && message.Text() == "!help" { message.Say("Available commands: !help, !info, !status") } }) // Third plugin - logger (can be disabled for specific events) loggerPlugin := wechaty.NewPlugin() loggerPlugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { // Check if logger is active for this context if ctx.IsActive(loggerPlugin) { fmt.Printf("LOG: Message from %s: %s\n", message.Talker().Name(), message.Text()) } }) bot.Use(authPlugin) bot.Use(commandPlugin) bot.Use(loggerPlugin) // You can disable a plugin temporarily for a specific context: // ctx.DisableOnce(loggerPlugin) bot.DaemonStart() } ``` -------------------------------- ### Working with Contacts API Source: https://context7.com/wechaty/go-wechaty/llms.txt This section demonstrates how to use the Contact factory to find, load, and interact with WeChat contacts. It includes examples of sending messages and retrieving contact profile information. ```APIDOC ## Working with Contacts The Contact factory provides methods to find, load, and interact with WeChat contacts. You can send messages to contacts and access their profile information. ### Find a Contact by Name This method searches for a contact by their name. **Method:** Implicit (via `bot.Contact().Find("Name")`) **Endpoint:** N/A (Client-side operation) ### Find All Contacts by Filter This method retrieves all contacts that match the provided query filter. **Method:** Implicit (via `bot.Contact().FindAll(filter)`) **Endpoint:** N/A (Client-side operation) **Parameters:** #### Request Body (for FindAll) - **ContactQueryFilter** (object) - Optional - Filter criteria for contacts. - **name** (string) - Optional - Filter by contact name. ### Get All Contact Tags Retrieves all tags associated with contacts. **Method:** Implicit (via `bot.Contact().Tags()`) **Endpoint:** N/A (Client-side operation) ### Get Logged-in User Retrieves the profile of the currently logged-in user. **Method:** Implicit (via `bot.UserSelf()`) **Endpoint:** N/A (Client-side operation) ### Send Message to Contact Sends a message to a specific contact. **Method:** Implicit (via `contact.Say("message")`) **Endpoint:** N/A (Client-side operation) ### Get Contact Avatar Retrieves the avatar URL of a contact. **Method:** Implicit (via `contact.Avatar()`) **Endpoint:** N/A (Client-side operation) ### Contact Profile Information Access various profile details of a contact. **Fields:** - **ID** (string) - The unique identifier of the contact. - **Name** (string) - The display name of the contact. - **Alias** (string) - The alias of the contact. - **Gender** (schemas.ContactGender) - The gender of the contact. - **City** (string) - The city the contact is located in. - **Province** (string) - The province the contact is located in. - **Friend** (bool) - Indicates if the contact is a friend. - **Star** (bool) - Indicates if the contact is starred. - **Type** (schemas.ContactType) - The type of the contact (e.g., personal, group). ### Request Example (Sending a message) ```go contact.Say("Hello from the bot!") ``` ### Response Example (Sending a message) ```json { "messageId": "some-message-id" } ``` ### Response Example (Contact details) ```go { "id": "contact-id", "name": "John Doe", "alias": "JD", "gender": 1, // Example value for male "city": "Shanghai", "province": "Shanghai", "isFriend": true, "isStar": false, "type": 1 // Example value for personal } ``` ``` -------------------------------- ### Plugin System Overview Source: https://context7.com/wechaty/go-wechaty/llms.txt Demonstrates how to create and use basic plugins for event handling, such as responding to messages or greeting users on login. ```APIDOC ## Using the Plugin System Go Wechaty supports a plugin system for modular bot development. Plugins can register their own event handlers and can be enabled/disabled dynamically. ```go package main import ( "fmt" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) // Create a ding-dong plugin func createDingDongPlugin() *wechaty.Plugin { plugin := wechaty.NewPlugin() plugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } if message.Type() == schemas.MessageTypeText && message.Text() == "ding" { message.Say("dong") fmt.Println("Ding-dong plugin replied!") } }) return plugin } // Create a greeting plugin func createGreetingPlugin() *wechaty.Plugin { plugin := wechaty.NewPlugin() plugin.OnLogin(func(ctx *wechaty.Context, user *user.ContactSelf) { fmt.Printf("Greeting plugin: Welcome, %s!\n", user.Name()) }) plugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } text := message.Text() if text == "hello" || text == "hi" { message.Say("Hello! Nice to meet you!") } }) return plugin } func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) // Create plugins dingDongPlugin := createDingDongPlugin() greetingPlugin := createGreetingPlugin() // Register plugins with the bot bot.Use(dingDongPlugin) bot.Use(greetingPlugin) // Plugins can be disabled dynamically // dingDongPlugin.SetEnable(false) // Check if a plugin is enabled if dingDongPlugin.IsEnable() { fmt.Println("Ding-dong plugin is active") } bot.DaemonStart() } ``` ``` -------------------------------- ### Go Wechaty: Implementing Basic Plugins Source: https://context7.com/wechaty/go-wechaty/llms.txt Demonstrates how to create and register simple plugins for Go Wechaty. Includes a 'ding-dong' plugin that responds to 'ding' messages and a 'greeting' plugin that responds to 'hello' or 'hi' and logs login events. Plugins are added to the bot using `bot.Use()` and can be checked for their enabled status. ```go package main import ( "fmt" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) // Create a ding-dong plugin func createDingDongPlugin() *wechaty.Plugin { plugin := wechaty.NewPlugin() plugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } if message.Type() == schemas.MessageTypeText && message.Text() == "ding" { message.Say("dong") fmt.Println("Ding-dong plugin replied!") } }) return plugin } // Create a greeting plugin func createGreetingPlugin() *wechaty.Plugin { plugin := wechaty.NewPlugin() plugin.OnLogin(func(ctx *wechaty.Context, user *user.ContactSelf) { fmt.Printf("Greeting plugin: Welcome, %s!\n", user.Name()) }) plugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } text := message.Text() if text == "hello" || text == "hi" { message.Say("Hello! Nice to meet you!") } }) return plugin } func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) // Create plugins dingDongPlugin := createDingDongPlugin() greetingPlugin := createGreetingPlugin() // Register plugins with the bot bot.Use(dingDongPlugin) bot.Use(greetingPlugin) // Plugins can be disabled dynamically // dingDongPlugin.SetEnable(false) // Check if a plugin is enabled if dingDongPlugin.IsEnable() { fmt.Println("Ding-dong plugin is active") } bot.DaemonStart() } ``` -------------------------------- ### Working with FileBox for File Abstraction in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt Illustrates the usage of the FileBox utility in Go Wechaty for creating file representations from various sources. It covers creating FileBoxes from URLs, local files, base64 encoded data, QR codes, and io.Reader streams. It also shows how to convert FileBoxes to bytes, base64, JSON, and save them to local files. ```go package main import ( "fmt" "log" "strings" "github.com/wechaty/go-wechaty/wechaty-puppet/filebox" ) func main() { // Create from URL fbUrl := filebox.FromUrl("https://example.com/image.png") fmt.Printf("FileBox: %s\n", fbUrl.String()) // Create from local file fbFile := filebox.FromFile("/path/to/local/file.pdf") fmt.Printf("FileBox: %s\n", fbFile.String()) // Create from base64 encoded data base64Data := "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" fbBase64 := filebox.FromBase64(base64Data, filebox.WithName("pixel.png")) fmt.Printf("FileBox: %s\n", fbBase64.String()) // Create from QR code content fbQR := filebox.FromQRCode("https://github.com/wechaty/go-wechaty") fmt.Printf("FileBox: %s\n", fbQR.String()) // Create from io.Reader stream reader := strings.NewReader("Hello, World!") fbStream := filebox.FromStream(reader, filebox.WithName("hello.txt")) fmt.Printf("FileBox: %s\n", fbStream.String()) // Convert FileBox to different formats bytes, err := fbUrl.ToBytes() if err != nil { log.Printf("ToBytes error: %v\n", err) } fmt.Printf("File size: %d bytes\n", len(bytes)) base64Str, err := fbUrl.ToBase64() if err != nil { log.Printf("ToBase64 error: %v\n", err) } fmt.Printf("Base64 length: %d\n", len(base64Str)) // Save to local file err = fbUrl.ToFile("downloaded.png", true) // overwrite=true if err != nil { log.Printf("ToFile error: %v\n", err) } // Convert to JSON for serialization jsonStr, err := fbUrl.ToJSON() if err != nil { log.Printf("ToJSON error: %v\n", err) } fmt.Printf("JSON: %s\n", jsonStr) // Restore from JSON restoredFb := filebox.FromJSON(jsonStr) fmt.Printf("Restored: %s\n", restoredFb.String()) } ``` -------------------------------- ### Create Wechaty Bot Instance in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt Demonstrates how to create a new Go Wechaty bot instance using functional options. This includes basic creation with a puppet service token, setting a custom bot name, and advanced configuration with puppet service options. ```go package main import ( "github.com/wechaty/go-wechaty/wechaty" wp "github.com/wechaty/go-wechaty/wechaty-puppet" puppetservice "github.com/wechaty/go-wechaty/wechaty-puppet-service" ) func main() { // Basic bot creation with puppet service token bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-puppet-service-token", })) // Bot with custom name bot = wechaty.NewWechaty( wechaty.WithName("my-awesome-bot"), wechaty.WithPuppetOption(wp.Option{ Token: "your-puppet-service-token", }), ) // Bot with puppet service options (advanced configuration) bot = wechaty.NewWechaty( wechaty.WithPuppetServiceOptions(puppetservice.Options{ Option: wp.Option{ Token: "your-puppet-service-token", Endpoint: "grpc://localhost:8788", }, GrpcReconnectInterval: 5000, }), ) } ``` -------------------------------- ### Register Login and Logout Event Callbacks Source: https://context7.com/wechaty/go-wechaty/llms.txt Demonstrates how to use OnLogin and OnLogout methods to listen for authentication state changes. These callbacks provide access to the user's contact information and the reason for logout. ```go package main import ( "fmt" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnLogin(func(ctx *wechaty.Context, self *user.ContactSelf) { fmt.Printf("Bot logged in as: %s\n", self.Name()) fmt.Printf("User ID: %s\n", self.ID()) fmt.Printf("Gender: %v\n", self.Gender()) fmt.Printf("City: %s\n", self.City()) }) bot.OnLogout(func(ctx *wechaty.Context, self *user.ContactSelf, reason string) { fmt.Printf("Bot logged out: %s\n", self.Name()) fmt.Printf("Reason: %s\n", reason) }) bot.DaemonStart() } ``` -------------------------------- ### Manage Room Operations and Events in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt This snippet demonstrates how to interact with rooms, including finding rooms, managing members, sending messages, setting announcements, and handling room lifecycle events such as joins and topic changes. ```go package main import ( "fmt" "log" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" _interface "github.com/wechaty/go-wechaty/wechaty/interface" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnReady(func(ctx *wechaty.Context) { room := bot.Room().Find("My Group Chat") if room != nil { fmt.Printf("Room Topic: %s\n", room.Topic()) owner := room.Owner() if owner != nil { fmt.Printf("Room Owner: %s\n", owner.Name()) } members, err := room.MemberAll(nil) if err == nil { for _, member := range members { alias, _ := room.Alias(member) fmt.Printf("Member: %s (Alias: %s)\n", member.Name(), alias) } } room.Say("Hello everyone!") } }) bot.OnRoomJoin(func(ctx *wechaty.Context, room *user.Room, inviteeList []_interface.IContact, inviter _interface.IContact, date time.Time) { fmt.Printf("Room join event in %s\n", room.Topic()) }) bot.DaemonStart() } ``` -------------------------------- ### Handle Room Invitations in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt This code demonstrates how to handle incoming room invitations using the OnRoomInvite event. It automatically accepts invitations to join group chats. Key dependencies include the go-wechaty library and its user and puppet modules. ```Go package main import ( "fmt" "log" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnRoomInvite(func(ctx *wechaty.Context, roomInvitation *user.RoomInvitation) { room, err := roomInvitation.Room() if err != nil { log.Printf("Error getting room: %v\n", err) return } fmt.Printf("Received room invitation to: %s\n", room.Topic()) // Accept the invitation err = roomInvitation.Accept() if err != nil { log.Printf("Error accepting invitation: %v\n", err) } else { fmt.Printf("Accepted room invitation to: %s\n", room.Topic()) } }) bot.DaemonStart() } ``` -------------------------------- ### Working with FileBox Source: https://context7.com/wechaty/go-wechaty/llms.txt This section explains how to create and manipulate FileBox objects, which serve as an abstraction for files in the Wechaty Go SDK. FileBox supports creation from URLs, local files, base64 data, QR codes, and streams. ```APIDOC ## Working with FileBox ### Description FileBox is a versatile file abstraction that supports creating files from various sources including URLs, local files, base64 data, and streams. It provides methods for conversion to different formats and saving to local files. ### Method This is a conceptual representation of the `FileBox` functionality within the Wechaty Go SDK. The actual implementation is within the `filebox` package. ### Endpoint N/A (This is a utility package for file handling, not a direct HTTP endpoint). ### Parameters FileBox creation methods accept various parameters depending on the source: #### Create from URL - **url** (string) - Required - The URL of the file. #### Create from Local File - **filePath** (string) - Required - The local path to the file. #### Create from Base64 - **base64Data** (string) - Required - The base64 encoded file content. - **options** (*FileBoxOptions) - Optional - Options like setting the filename. #### Create from QR Code - **content** (string) - Required - The content to be encoded as a QR code. #### Create from Stream - **reader** (io.Reader) - Required - An io.Reader stream for the file content. - **options** (*FileBoxOptions) - Optional - Options like setting the filename. ### Request Example ```go // Create from URL fbUrl := filebox.FromUrl("https://example.com/image.png") // Create from local file fbFile := filebox.FromFile("/path/to/local/file.pdf") // Create from base64 encoded data base64Data := "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" fbBase64 := filebox.FromBase64(base64Data, filebox.WithName("pixel.png")) // Create from QR code content fbQR := filebox.FromQRCode("https://github.com/wechaty/go-wechaty") // Create from io.Reader stream reader := strings.NewReader("Hello, World!") fbStream := filebox.FromStream(reader, filebox.WithName("hello.txt")) ``` ### Response FileBox methods typically return a `*FileBox` object or an error. Conversion methods return the converted data or an error. #### Success Response (200) - ***FileBox** (object) - The created FileBox object. - **[]byte** (bytes) - The file content as bytes. - **string** (base64 string) - The file content as a base64 string. - **string** (JSON string) - The FileBox object serialized to JSON. - **error** (error) - An error if the operation failed. #### Response Example ```json { "type": "url", "url": "https://example.com/image.png", "name": "image.png" } ``` ``` -------------------------------- ### Replying to Messages with Various Content Types in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt Demonstrates how to use the `Say` method on a Wechaty message object to reply with different content types. This includes text, images from URLs, local files, URL links, and mini-programs. It requires the go-wechaty SDK and handles potential errors during message sending. ```go package main import ( "log" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/filebox" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() || message.Type() != schemas.MessageTypeText { return } text := message.Text() // Reply with text if text == "hello" { _, err := message.Say("Hello! How can I help you?") if err != nil { log.Printf("Error sending text: %v\n", err) } } // Reply with an image from URL if text == "image" { fileBox := filebox.FromUrl("https://example.com/image.png") _, err := message.Say(fileBox) if err != nil { log.Printf("Error sending image: %v\n", err) } } // Reply with a local file if text == "file" { fileBox := filebox.FromFile("/path/to/document.pdf") _, err := message.Say(fileBox) if err != nil { log.Printf("Error sending file: %v\n", err) } } // Reply with URL link if text == "link" { urlLink := user.NewUrlLink(&schemas.UrlLinkPayload{ Title: "Go Wechaty", Description: "Conversational AI SDK for WeChat", Url: "https://github.com/wechaty/go-wechaty", ThumbnailUrl: "https://wechaty.js.org/img/icon.png", }) _, err := message.Say(urlLink) if err != nil { log.Printf("Error sending URL link: %v\n", err) } } // Reply with mini program if text == "miniprogram" { miniProgram := user.NewMiniProgram(&schemas.MiniProgramPayload{ Appid: "wx1234567890", Title: "My Mini Program", PagePath: "pages/index/index", Description: "A sample mini program", ThumbUrl: "https://example.com/thumb.png", }) _, err := message.Say(miniProgram) if err != nil { log.Printf("Error sending mini program: %v\n", err) } } }) bot.DaemonStart() } ``` -------------------------------- ### Handle QR Code Scan Login Events in Go Source: https://context7.com/wechaty/go-wechaty/llms.txt Illustrates how to register a callback for QR code scan events using `OnScan`. This is crucial for WeChat authentication, displaying the QR code in the terminal, and generating a web URL for scanning. ```go package main import ( "fmt" "net/url" "os" "github.com/mdp/qrterminal/v3" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnScan(func(ctx *wechaty.Context, qrCode string, status schemas.ScanStatus, data string) { if status == schemas.ScanStatusWaiting || status == schemas.ScanStatusTimeout { // Display QR code in terminal qrterminal.GenerateHalfBlock(qrCode, qrterminal.L, os.Stdout) // Generate web URL for QR code qrcodeUrl := fmt.Sprintf("https://wechaty.js.org/qrcode/%s", url.QueryEscape(qrCode)) fmt.Printf("Scan QR Code to login: %s\n", qrcodeUrl) fmt.Printf("Status: %s\n", status) } else if status == schemas.ScanStatusScanned { fmt.Println("QR Code scanned, waiting for confirmation...") } else if status == schemas.ScanStatusConfirmed { fmt.Println("Login confirmed!") } }) bot.DaemonStart() } ``` -------------------------------- ### Process Incoming Messages with Filters Source: https://context7.com/wechaty/go-wechaty/llms.txt Shows how to implement the OnMessage event handler to process incoming messages. It includes logic to filter out self-sent messages and stale messages, and demonstrates how to handle different message types. ```go package main import ( "fmt" "log" "time" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } if message.Age() > 2*time.Minute { log.Println("Skipping old message") return } fmt.Printf("Message Type: %s\n", message.Type()) fmt.Printf("Message Text: %s\n", message.Text()) talker := message.Talker() if talker != nil { fmt.Printf("From: %s (ID: %s)\n", talker.Name(), talker.ID()) } room := message.Room() if room != nil { fmt.Printf("Room: %s\n", room.Topic()) } switch message.Type() { case schemas.MessageTypeText: fmt.Printf("Text message: %s\n", message.Text()) case schemas.MessageTypeImage: fmt.Println("Received an image") } }) bot.DaemonStart() } ``` -------------------------------- ### Replying to Messages Source: https://context7.com/wechaty/go-wechaty/llms.txt This section demonstrates how to use the `Say` method on a Message object to reply with different types of content, including text, images from URLs, local files, URL links, and mini-programs. ```APIDOC ## Replying to Messages ### Description The `Say` method on Message allows replying with various content types including text, files, contacts, URL links, mini programs, and locations. ### Method This is a conceptual representation of the `Say` method within the Wechaty Go SDK. The actual implementation is within the `Message` struct. ### Endpoint N/A (This is a method call within the SDK, not a direct HTTP endpoint). ### Parameters - **content** (string | *FileBox | *UrlLink | *MiniProgram) - Required - The content to send as a reply. This can be a string for text, a FileBox object for files/images, a UrlLink object for URL shares, or a MiniProgram object. ### Request Example ```go // Reply with text _, err := message.Say("Hello! How can I help you?") // Reply with an image from URL fileBox := filebox.FromUrl("https://example.com/image.png") _, err := message.Say(fileBox) // Reply with URL link urlLink := user.NewUrlLink(&schemas.UrlLinkPayload{ Title: "Go Wechaty", Description: "Conversational AI SDK for WeChat", Url: "https://github.com/wechaty/go-wechaty", ThumbnailUrl: "https://wechaty.js.org/img/icon.png", }) _, err := message.Say(urlLink) ``` ### Response #### Success Response (200) - ***Message** (object) - The sent message object. - **error** (error) - An error if the message sending failed. #### Response Example ```json { "messageId": "someMessageId" } ``` ``` -------------------------------- ### Context for Plugin Control Source: https://context7.com/wechaty/go-wechaty/llms.txt Illustrates how to use the Context object to control plugin execution flow, share data between plugins, and abort further processing. ```APIDOC ## Using Context for Plugin Control The Context object allows controlling plugin execution flow and sharing data between plugins within the same event. ```go package main import ( "fmt" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) // First plugin - authentication authPlugin := wechaty.NewPlugin() authPlugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } talker := message.Talker() // Store user data in context ctx.SetData("user_id", talker.ID()) ctx.SetData("user_name", talker.Name()) // Check if user is authorized if talker.Name() == "unauthorized_user" { fmt.Println("Unauthorized user, aborting further processing") ctx.Abort() // Stop all subsequent plugins return } fmt.Println("User authorized, continuing...") }) // Second plugin - command handler commandPlugin := wechaty.NewPlugin() commandPlugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { if message.Self() { return } // Retrieve data from context userName := ctx.GetData("user_name") fmt.Printf("Processing command from: %v\n", userName) if message.Type() == schemas.MessageTypeText && message.Text() == "!help" { message.Say("Available commands: !help, !info, !status") } }) // Third plugin - logger (can be disabled for specific events) loggerPlugin := wechaty.NewPlugin() loggerPlugin.OnMessage(func(ctx *wechaty.Context, message *user.Message) { // Check if logger is active for this context if ctx.IsActive(loggerPlugin) { fmt.Printf("LOG: Message from %s: %s\n", message.Talker().Name(), message.Text()) } }) bot.Use(authPlugin) bot.Use(commandPlugin) bot.Use(loggerPlugin) // You can disable a plugin temporarily for a specific context: // ctx.DisableOnce(loggerPlugin) bot.DaemonStart() } ``` ``` -------------------------------- ### Manage and Interact with WeChat Contacts Source: https://context7.com/wechaty/go-wechaty/llms.txt Demonstrates how to initialize a bot, find contacts by name or filter, retrieve profile metadata, and send messages. It also shows how to access the current user's profile and contact tags. ```go package main import ( "fmt" "log" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty-puppet/schemas" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) bot.OnReady(func(ctx *wechaty.Context) { contact := bot.Contact().Find("John Doe") if contact != nil { fmt.Printf("Found contact: %s\n", contact.Name()) fmt.Printf("Contact ID: %s\n", contact.ID()) fmt.Printf("Alias: %s\n", contact.Alias()) fmt.Printf("Gender: %v\n", contact.Gender()) fmt.Printf("City: %s\n", contact.City()) fmt.Printf("Province: %s\n", contact.Province()) fmt.Printf("Is Friend: %v\n", contact.Friend()) fmt.Printf("Is Star: %v\n", contact.Star()) fmt.Printf("Contact Type: %v\n", contact.Type()) msg, err := contact.Say("Hello from the bot!") if err != nil { log.Printf("Error sending message: %v\n", err) } else if msg != nil { fmt.Printf("Message sent, ID: %s\n", msg.ID()) } avatar := contact.Avatar() fmt.Printf("Avatar: %s\n", avatar.String()) } contacts := bot.Contact().FindAll(&schemas.ContactQueryFilter{ Name: "test", }) for _, c := range contacts { fmt.Printf("Contact: %s (%s)\n", c.Name(), c.ID()) } tags := bot.Contact().Tags() for _, tag := range tags { fmt.Printf("Tag: %s\n", tag.ID()) } self := bot.UserSelf() fmt.Printf("Logged in as: %s\n", self.Name()) }) bot.DaemonStart() } ``` -------------------------------- ### Handle Bot Events and Errors in Go Wechaty Source: https://context7.com/wechaty/go-wechaty/llms.txt This Go code snippet illustrates how to implement error handling and subscribe to various bot lifecycle events using the Wechaty library. It covers OnError, OnHeartbeat, OnDong, OnReady, OnStart, and OnStop events, providing a foundation for robust bot operation and monitoring. The code requires the go-wechaty library and a valid bot token. ```go package main import ( "fmt" "log" "github.com/wechaty/go-wechaty/wechaty" "github.com/wechaty/go-wechaty/wechaty/user" wp "github.com/wechaty/go-wechaty/wechaty-puppet" ) func main() { bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{ Token: "your-token", })) // Handle errors bot.OnError(func(ctx *wechaty.Context, err error) { log.Printf("Bot error: %v\n", err) // Implement error reporting, alerting, etc. }) // Handle heartbeat events bot.OnHeartbeat(func(ctx *wechaty.Context, data string) { fmt.Printf("Heartbeat: %s\n", data) }) // Handle dong events (response to ping) bot.OnDong(func(ctx *wechaty.Context, data string) { fmt.Printf("Dong received: %s\n", data) }) // Handle ready event (bot is fully initialized) bot.OnReady(func(ctx *wechaty.Context) { fmt.Println("Bot is ready!") // Now safe to use bot.Contact(), bot.Room(), etc. self := bot.UserSelf() fmt.Printf("Logged in as: %s\n", self.Name()) }) // Handle start event bot.OnStart(func(ctx *wechaty.Context) { fmt.Println("Bot started!") }) // Handle stop event bot.OnStop(func(ctx *wechaty.Context) { fmt.Println("Bot stopped!") }) bot.DaemonStart() } ```