M1 Mac OS 安装微信机器人

  1. 安装 Homebrew
    打开终端,输入 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  2. 安装 go
    在终端中输入 brew install go

  3. 配置环境变量
    sudo vim ~/.zshrc
    在打开的文件结尾插入以下内容,#示例部分需要替换成自己的路径
    export GO111MODULE=on
    export GOPROXY=https://goproxy.cn
    export GOPATH="/Users/yours/go" # 示例
    export GOBIN="$GOPATH/bin"
    export PATH=$HOME/bin:/usr/local/bin:/usr/local/opt/mysql-client/bin:$GOBIN:$PATH

  4. 安装机器人
    go get github.com/eatmoreapple/openwechat

  5. 新建一个目录
    mkdir /Users/yours/go/wechatbot #路径需要自定义

  6. 在上面的目录中,新建一个main.go文件,将以下内容copy到main.go文件中
    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()

}

  1. 初始化gomod
    go mod init example.com/m #路径自定义随便写

  2. 执行 go mod tidy

  3. 执行 go run main.go

  4. 扫码登录微信

参考文档

https://github.com/eatmoreapple/openwechat
https://openwechat.readthedocs.io/zh/latest/
https://ysicing.me/posts/go-install

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注