openwechat

repository·master·Indexed 26 days ago

https://github.com/eatmoreapple/openwechat

A Go-based API for personal WeChat accounts that enables developers to build bots with automated replies, message handling, and contact management. It supports multiple login modes including standard QR scan, hot login (session reuse), and push login, as well as features for sending text, images, files, and emoticons, managing group memberships, and handling message synchronization.

Tokens
14.1K
Snippets
19
Records
104
Agent score
89%

What's inside openwechat

  1. Supported WeChat Bot Features

    master

    The openwechat library supports several core functionalities for automating a personal WeChat account:

    • Messaging: Reply to messages and send text, images, files, and emojis to specific targets (friends or groups).
    • Session Management: Supports hot login (avoiding repeated QR code scans).
    • Message Handling: Custom message processing and anti-recall (preventing message deletion from being hidden).
    • File Operations: File downloading.
    • Contact Management: Retrieve object information, set friend remarks, and add friends to groups.
  2. Quickstart: Create a WeChat Bot

    master

    To create a basic WeChat bot, use openwechat.DefaultBot with a specific mode (e.g., openwechat.Desktop). You can register a MessageHandler to handle incoming messages, a UUIDCallback to handle login QR codes, and call bot.Login() to start the session. Use bot.Block() to keep the main goroutine running.

    package main
    
    import (
    	"fmt"
    	"github.com/eatmoreapple/openwechat"
    )
    
    func main() {
    	bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式
    
    	// 注册消息处理函数
    	bot.MessageHandler = func(msg *openwechat.Message) {
    		if msg.IsText() && msg.Content == "ping" {
    			msg.ReplyText("pong")
    		}
    	}
    	// 注册登陆二维码回调
    	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
    	}
    
    	// 获取所有的好友
    	friends, err := self.Friends()
    	fmt.Println(friends, err)
    
    	// 获取所有的群组
    	groups, err := self.Groups()
    	fmt.Println(groups, err)
    
    	// 阻塞主goroutine, 直到发生异常或者用户主动退出
    	bot.Block()
    }
  3. Perform Login (Scan and Hot Reload)

    master

    There are three ways to handle authentication:

    1. Standard Login: bot.Login() blocks until login succeeds or fails. Requires scanning a QR code every time.
    2. Hot Login: Uses a HotReloadStorage to save session info, allowing you to skip scanning during restarts within a certain timeframe. Use openwechat.NewFileHotReloadStorage("filename.json") for file-based storage. To ensure the first run triggers a scan, use openwechat.NewRetryLoginOption().
    3. Push Login (Skip Scan): Attempts to trigger the 'Confirm Login' prompt on the user's mobile app (similar to PC WeChat). This requires a HotReloadStorage and openwechat.NewRetryLoginOption() to handle the initial scan.
  4. Handle incoming messages with MessageHandler

    master

    You can receive messages by assigning a callback function to the bot.MessageHandler field. The callback receives a *openwechat.Message object (referred to as msg).

    bot.MessageHandler = func (msg *openwechat.Message) {
    	if msg.IsText() && msg.Content == "ping" {
    		msg.ReplyText("pong")
    	}
    }
  5. Handle WeChat Login Flow

    master

    Use the Caller to manage the multi-step WeChat login process:

    1. Get Login UUID: Call GetLoginUUID to retrieve the UUID required for scanning.
    2. Check Login Status: Call CheckLogin with the UUID to monitor if the user has scanned the QR code.
    3. Get Login Info: Call GetLoginInfo to retrieve necessary session information (like SKey) after a successful login.
    4. Notify Status: Call WebWxStatusNotify to inform WeChat that the mobile device has successfully logged in.
  6. Initialize a Bot with NewBot or DefaultBot

    master

    To start using the library, you must first create a Bot instance.

    • NewBot(ctx context.Context): Creates a new bot instance using the default web WeChat mode. You must provide a context to control the bot's lifecycle.
    • DefaultBot(prepares ...BotPreparer): A convenience constructor that sets up default callbacks for QR code printing, scan success, login success, and heartbeat (sync check) logging. It uses context.Background().

    After initialization, you typically call Login() to begin the authentication process.

  7. Initialize the Client

    master
    You can create a new Client instance using NewClient by providing a custom *http.Client, or use DefaultClient() for a pre-configured client that handles cookie storage, sets a 30-second timeout, and includes a default User-Agent hook.
  8. Use Emoji constants

    master

    The project provides a full set of WeChat emojis via the openwechat.Emoji struct. These can be sent using SendText or ReplyText methods.

    // Example: Sending a Doge emoji to a friend
    friend.SendText(openwechat.Emoji.Doge)
    
    // Example: Replying to a message with an Awesome emoji
    msg.ReplyText(openwechat.Emoji.Awesome)
  9. Handle Scan and Login callbacks

    master

    You can intercept specific login stages by assigning callback functions to the Bot object. Note: These must be assigned before calling Login() or PushLogin().

    • ScanCallBack: Triggered when a user scans the QR code but hasn't confirmed yet. The CheckLoginResponse (a []byte wrapper) provides access to the user's avatar via .Avatar().
    • LoginCallBack: Triggered when the user confirms the login. The response contains a redirect link used as a signal that login is complete.