Go-Wechaty 项目教程
1. 项目的目录结构及介绍
Go-Wechaty 项目的目录结构如下:
go-wechaty/
├── cmd/
│ └── main.go
├── configs/
│ └── config.yaml
├── internal/
│ ├── handlers/
│ └── services/
├── pkg/
│ ├── wechaty/
│ └── wechaty-puppet/
├── go.mod
├── go.sum
└── README.md
目录介绍
- cmd/: 包含项目的启动文件。
- configs/: 包含项目的配置文件。
- internal/: 包含项目的内部逻辑,如处理函数和业务逻辑。
- pkg/: 包含项目的外部包,如 wechaty 和 wechaty-puppet。
- go.mod 和 go.sum: Go 模块文件,用于管理依赖。
- README.md: 项目说明文档。
2. 项目的启动文件介绍
项目的启动文件位于 cmd/main.go
,主要负责初始化配置和启动 Wechaty 服务。
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() {
bot := wechaty.NewWechaty()
bot.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)
})
bot.OnLogin(func(context *wechaty.Context, user *user.ContactSelf) {
fmt.Printf("User %s logined\n", user)
})
bot.OnMessage(func(context *wechaty.Context, message *user.Message) {
fmt.Printf("Message: %s\n", message)
})
bot.DaemonStart()
}
启动文件功能
- 初始化 Wechaty 实例: 创建一个新的 Wechaty 实例。
- 事件监听: 监听登录、扫码和消息事件,并进行相应的处理。
- 启动服务: 启动 Wechaty 服务。
3. 项目的配置文件介绍
项目的配置文件位于 configs/config.yaml
,主要包含 Wechaty 的配置信息。
wechaty:
puppet_service_token: "your_token_at_here"
配置文件内容
- puppet_service_token: Wechaty 的 Puppet 服务令牌,用于连接 Wechaty 服务。
使用方法
在启动文件中读取配置文件并应用配置:
import (
"github.com/spf13/viper"
)
func init() {
viper.SetConfigName("config")
viper.AddConfigPath("./configs")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
func main() {
token := viper.GetString("wechaty.puppet_service_token")
// 使用 token 初始化 Wechaty
}
通过以上步骤,您可以成功配置和启动 Go-Wechaty 项目。