Compare commits

...

46 Commits

Author SHA1 Message Date
多吃点苹果
3e6fc41298
[fix]: 修改同步消息逻辑 (#236) 2023-02-05 11:23:05 +08:00
ford
3c7ac0cc75
【opt】优化好友公众号群组获取接口防止频繁发送网络请求 (#234)
Co-authored-by: wenyoufu <wenyoufu@jd.com>
2023-02-05 11:20:40 +08:00
多吃点苹果
99af4a2685
[refactor]: 添加 CookieGroup (#233) 2023-02-05 00:20:37 +08:00
多吃点苹果
0c57ab1ed5
更新 Group Display (#232) 2023-02-04 23:55:55 +08:00
多吃点苹果
a72c165c59
删除根据备注查找群组功能 (#231) 2023-02-04 12:04:36 +08:00
多吃点苹果
35a348f0af
[feat]: 添加最近联系人和公众号文章列表 (#230) 2023-02-04 11:59:17 +08:00
多吃点苹果
66c4bebd1f
提升上传文件性能 (#228) 2023-02-03 22:17:40 +08:00
多吃点苹果
fbfd691cb4
[style]: update User display (#227) 2023-02-03 17:57:58 +08:00
多吃点苹果
5194ad4965
[style]: 移除 DispatchMessage (#224) 2023-02-02 10:24:18 +08:00
多吃点苹果
eccc25e66e
[style]: Deprecated NewJsonFileHotReloadStorage (#223) 2023-02-02 10:06:17 +08:00
多吃点苹果
d77bb0a4cb
[feat]: 支持用户自定义热存储数据的序列化和反序列化 (#222) 2023-02-02 00:15:46 +08:00
多吃点苹果
e9c89f9ac8
[style]: 支持扫码登录自定义uuid (#221) 2023-02-02 00:05:26 +08:00
多吃点苹果
6629e77fd5
[feat]: 支持自定义添加 context 用于控制 bot 存活 (#220) 2023-02-01 23:54:11 +08:00
多吃点苹果
76bd0a5648
[fix]: 解决定时器同步数据到热存储中的数据竞争问题 https://github.com/eatmoreapple/openwech… (#219) 2023-02-01 23:43:10 +08:00
多吃点苹果
6be6359e34
[feat]: 添加邀请用户加入群聊功能 (#216) 2023-01-30 21:09:41 +08:00
李寻欢
7cbb2ae1bb
新增设置UUID接口,可使用该接口解耦登录逻辑 (#215)
* 🎨 优化是否有人加入了群聊判断逻辑

*  新增设置UUID接口,可使用该接口解耦登录逻辑
2023-01-30 20:30:32 +08:00
多吃点苹果
b9bbaed369
[doc]: update docs (#214) 2023-01-24 21:44:35 +08:00
多吃点苹果
2d11a7b95a
按照微信的排列顺序获取联系人列表 (#213) 2023-01-24 21:17:18 +08:00
eatmoreapple
e38b4258f0 wip 2023-01-22 09:21:34 +08:00
多吃点苹果
26fc0bb366
change readerToFile (#211) 2023-01-22 09:06:16 +08:00
多吃点苹果
71d8221cad
[bug]: 修复拍了拍我判断错误的问题 (#210) 2023-01-22 08:31:31 +08:00
多吃点苹果
1a13e73355
[feat]: 添加判断当前消息是否为拍了拍自己 (#209) 2023-01-21 09:32:46 +08:00
多吃点苹果
fc38bfb401
[fix]: 修复当用户主动退出后,block依然阻塞 (#206) 2023-01-13 20:53:52 +08:00
多吃点苹果
30da2df475
[fix]: 当用户自定义http client的时候 cookie 无法被反序列化的问题 (#205) 2023-01-13 20:40:55 +08:00
多吃点苹果
63143f9364
[refactor]: 增加 LoginCode 定义 (#204) 2023-01-13 19:56:52 +08:00
多吃点苹果
53478bad19
[perf]: 优化登录检查 (#203) 2023-01-13 19:44:15 +08:00
多吃点苹果
1eadbf8be6
[style]: 更新 Members 转换函数 (#202) 2023-01-13 12:55:22 +08:00
多吃点苹果
0f10aa4508
[feat]: 添加联系人去重和排序 (#201) 2023-01-13 12:34:20 +08:00
多吃点苹果
f8461401a7
[feat]: 添加联系人排序功能 (#200) 2023-01-13 12:23:15 +08:00
多吃点苹果
0af4b51d93
[feat]: 添加 User 转换函数 (#199) 2023-01-12 18:24:14 +08:00
多吃点苹果
26abfd6e49
[feat]: 添加 Members 去重 (#198) 2023-01-12 18:17:03 +08:00
多吃点苹果
dc3669dcad
[refactor] pushLogin 设置二维码回调和扫码回调默认不触发 (#197) 2023-01-12 12:47:42 +08:00
多吃点苹果
cc4d650796
[style]: 更新 BotLoginOption (#196) 2023-01-12 12:20:34 +08:00
多吃点苹果
71fe8b87ec
设置默认5分钟同步一次热存储数据 (#192) 2023-01-10 19:28:14 +08:00
eatmoreapple
fb20b70ebf 更新热存储功能 2023-01-10 19:08:33 +08:00
多吃点苹果
87036e2c94
添加定时同步数据到热存储容器功能 (#191) 2023-01-10 15:41:04 +08:00
eatmoreapple
102af677ff wip 2023-01-10 14:27:28 +08:00
多吃点苹果
200c5be4ff
修改同步消息错误默认行为 (#190) 2023-01-10 10:57:20 +08:00
多吃点苹果
2681b51702
format errors (#189) 2023-01-10 09:54:01 +08:00
多吃点苹果
f49c0367ad
update docs (#188) 2023-01-09 23:28:54 +08:00
eatmoreapple
93c73833e0 删除好友检测字符串 2023-01-08 23:21:03 +08:00
qiaojiewei
88b6a34307
fix: receiver里fileHelper为空的情况 (#186)
Co-authored-by: tgNotHouse <gqwj007@gmail.com>
2023-01-08 18:36:48 +08:00
多吃点苹果
9b5590f708
修复 pushlogin 重试失败的问题 🐛 (#183) 2023-01-06 15:10:05 +08:00
多吃点苹果
da3b267965
发送文件直接支持 io.Reader (#182) 2023-01-06 14:55:08 +08:00
多吃点苹果
721f56314e
添加 LoginChecker (#181) 2023-01-06 01:48:33 +08:00
多吃点苹果
953c1ce0be
添加 Ret code (#180) 2023-01-06 01:25:02 +08:00
24 changed files with 1188 additions and 575 deletions

View File

@ -4,16 +4,16 @@
[![Go Doc](https://pkg.go.dev/badge/github.com/eatMoreApple/openwechat)](https://godoc.org/github.com/eatMoreApple/openwechat)[![Release](https://img.shields.io/github/v/release/eatmoreapple/openwechat.svg?style=flat-square)](https://github.com/eatmoreapple/openwechat/releases)[![Go Report Card](https://goreportcard.com/badge/github.com/eatmoreapple/openwechat)](https://goreportcard.com/badge/github.com/eatmoreapple/openwechat)[![Stars](https://img.shields.io/github/stars/eatmoreapple/openwechat.svg?style=flat-square)](https://img.shields.io/github/stars/eatmoreapple/openwechat.svg?style=flat-square)[![Forks](https://img.shields.io/github/forks/eatmoreapple/openwechat.svg?style=flat-square)](https://img.shields.io/github/forks/eatmoreapple/openwechat.svg?style=flat-square)
> golang版个人微信号API, 突破网页版限制,类似开发公众号一样,开发个人微信号
> golang版个人微信号API, 突破登录限制,类似开发公众号一样,开发个人微信号
微信机器人:smiling_imp:,利用微信号完成一些功能的定制化开发⭐
* 模块简单易用,易于扩展
* 支持定制化开发,如日志记录,自动回复
* 突破网页版登录限制&#x1F4E3;
* 突破登录限制&#x1F4E3;
* 无需重复扫码登录
* 支持多个微信号同时登陆
@ -115,7 +115,7 @@ func main() {
### 添加微信(EatMoreApple):apple:(备注: openwechat进群交流:smiling_imp:
**如果二维码图片没显示出来,请添加微信号 EatMoreApple**
**如果二维码图片没显示出来,请添加微信号 eatmoreapple**
<img width="210px" src="https://raw.githubusercontent.com/eatmoreapple/eatMoreApple/main/img/wechat.jpg" align="left">

View File

@ -4,6 +4,8 @@ type Ret int
const (
ticketError Ret = -14 // ticket error
logicError Ret = -2 // logic error
sysError Ret = -1 // sys error
paramError Ret = 1 // param error
failedLoginWarn Ret = 1100 // failed login warn
failedLoginCheck Ret = 1101 // failed login check

192
bot.go
View File

@ -2,33 +2,36 @@ package openwechat
import (
"context"
"encoding/json"
"errors"
"io"
"log"
"net/url"
"os/exec"
"runtime"
"sync"
)
type Bot struct {
ScanCallBack func(body []byte) // 扫码回调,可获取扫码用户的头像
LoginCallBack func(body []byte) // 登陆回调
LogoutCallBack func(bot *Bot) // 退出回调
UUIDCallback func(uuid string) // 获取UUID的回调函数
SyncCheckCallback func(resp SyncCheckResponse) // 心跳回调
MessageHandler MessageHandler // 获取消息成功的handle
MessageErrorHandler func(err error) bool // 获取消息发生错误的handle, 返回true则尝试继续监听
ScanCallBack func(body CheckLoginResponse) // 扫码回调,可获取扫码用户的头像
LoginCallBack func(body CheckLoginResponse) // 登陆回调
LogoutCallBack func(bot *Bot) // 退出回调
UUIDCallback func(uuid string) // 获取UUID的回调函数
SyncCheckCallback func(resp SyncCheckResponse) // 心跳回调
MessageHandler MessageHandler // 获取消息成功的handle
MessageErrorHandler func(err error) bool // 获取消息发生错误的handle, 返回true则尝试继续监听
Serializer Serializer // 序列化器, 默认为json
Storage *Storage
Caller *Caller
once sync.Once
err error
context context.Context
cancel context.CancelFunc
Caller *Caller
self *Self
Storage *Storage
hotReloadStorage HotReloadStorage
uuid string
loginUUID *string
deviceId string // 设备Id
loginOptionGroup BotOptionGroup
}
// Alive 判断当前用户是否正常在线
@ -48,6 +51,7 @@ func (b *Bot) Alive() bool {
// @description: 设置设备Id
// @receiver b
// @param deviceId
// TODO ADD INTO LOGIN OPTION
func (b *Bot) SetDeviceId(deviceId string) {
b.deviceId = deviceId
}
@ -66,22 +70,31 @@ func (b *Bot) GetCurrentUser() (*Self, error) {
return b.self, nil
}
func (b *Bot) login(login BotLogin) error {
return login.Login(b)
// login 这里对进行一些对登录前后的hook
func (b *Bot) login(login BotLogin) (err error) {
opt := b.loginOptionGroup
opt.Prepare(b)
if err = login.Login(b); err != nil {
err = opt.OnError(b, err)
}
if err != nil {
return err
}
return opt.OnSuccess(b)
}
// Login 用户登录
func (b *Bot) Login() error {
scanLogin := &SacnLogin{}
scanLogin := &SacnLogin{UUID: b.loginUUID}
return b.login(scanLogin)
}
// HotLogin 热登录,可实现在单位时间内免重复扫码登录
func (b *Bot) HotLogin(storage HotReloadStorage, opts ...HotLoginOptionFunc) error {
func (b *Bot) HotLogin(storage HotReloadStorage, opts ...BotLoginOption) error {
hotLogin := &HotLogin{storage: storage}
for _, opt := range opts {
opt(&hotLogin.opt)
}
// 进行相关设置。
// 如果相对默认的行为进行修改在opts里面进行追加即可。
b.loginOptionGroup = append(hotLoginDefaultOptions[:], opts...)
return b.login(hotLogin)
}
@ -89,14 +102,11 @@ func (b *Bot) HotLogin(storage HotReloadStorage, opts ...HotLoginOptionFunc) err
// 免扫码登录需要先扫码登录一次才可以进行扫码登录
// 扫码登录成功后需要利用微信号发送一条消息,然后在手机上进行主动退出。
// 这时候在进行一次 PushLogin 即可。
func (b *Bot) PushLogin(storage HotReloadStorage, opts ...PushLoginOptionFunc) error {
func (b *Bot) PushLogin(storage HotReloadStorage, opts ...BotLoginOption) error {
pushLogin := &PushLogin{storage: storage}
// 进行相关设置。
// 如果相对默认的行为进行修改在opts里面进行追加即可。
opts = append(defaultPushLoginOpts[:], opts...)
for _, opt := range opts {
opt(&pushLogin.opt)
}
b.loginOptionGroup = append(pushLoginDefaultOptions[:], opts...)
return b.login(pushLogin)
}
@ -107,16 +117,16 @@ func (b *Bot) Logout() error {
if err := b.Caller.Logout(info); err != nil {
return err
}
b.stopSyncCheck(errors.New("logout"))
b.Exit()
return nil
}
return errors.New("user not login")
}
// HandleLogin 登录逻辑
func (b *Bot) HandleLogin(data []byte) error {
func (b *Bot) HandleLogin(path *url.URL) error {
// 获取登录的一些基本的信息
info, err := b.Caller.GetLoginInfo(data)
info, err := b.Caller.GetLoginInfo(path)
if err != nil {
return err
}
@ -159,9 +169,10 @@ func (b *Bot) WebInit() error {
return err
}
// 设置当前的用户
b.self = &Self{bot: b, User: &resp.User}
b.self = &Self{bot: b, User: resp.User}
b.self.formatEmoji()
b.self.self = b.self
resp.ContactList.init(b.self)
b.Storage.Response = resp
// 通知手机客户端已经登录
@ -173,7 +184,7 @@ func (b *Bot) WebInit() error {
// FIX: 当bot在线的情况下执行热登录,会开启多次事件监听
go b.once.Do(func() {
if b.MessageErrorHandler == nil {
b.MessageErrorHandler = b.stopSyncCheck
b.MessageErrorHandler = defaultSyncCheckErrHandler(b)
}
for {
err := b.syncCheck()
@ -182,6 +193,8 @@ func (b *Bot) WebInit() error {
}
// 判断是否继续, 如果不继续则退出
if goon := b.MessageErrorHandler(err); !goon {
b.err = err
b.Exit()
break
}
}
@ -210,8 +223,8 @@ func (b *Bot) syncCheck() error {
if !resp.Success() {
return resp.Err()
}
// 如果Selector不为0则获取消息
if !resp.NorMal() {
switch resp.Selector {
case SelectorNewMsg:
messages, err := b.syncMessage()
if err != nil {
return err
@ -224,20 +237,17 @@ func (b *Bot) syncCheck() error {
// 默认同步调用
// 如果异步调用则需自行处理
// 如配合 openwechat.MessageMatchDispatcher 使用
// NOTE: 请确保 MessageHandler 不会阻塞,否则会导致收不到后续的消息
b.MessageHandler(message)
}
case SelectorModContact:
case SelectorAddOrDelContact:
case SelectorModChatRoom:
}
}
return err
}
// 当获取消息发生错误时, 默认的错误处理行为
func (b *Bot) stopSyncCheck(err error) bool {
b.err = err
b.Exit()
return false
}
// 获取新的消息
func (b *Bot) syncMessage() ([]*Message, error) {
resp, err := b.Caller.WebWxSync(b.Storage.Request, b.Storage.Response, b.Storage.LoginInfo)
@ -254,7 +264,7 @@ func (b *Bot) Block() error {
if b.self == nil {
return errors.New("`Block` must be called after user login")
}
<-b.context.Done()
<-b.Context().Done()
return nil
}
@ -283,15 +293,55 @@ func (b *Bot) DumpHotReloadStorage() error {
// DumpTo 将热登录需要的数据写入到指定的 io.Writer 中
// 注: 写之前最好先清空之前的数据
func (b *Bot) DumpTo(writer io.Writer) error {
cookies := b.Caller.Client.GetCookieJar()
jar := b.Caller.Client.Jar()
item := HotReloadStorageItem{
BaseRequest: b.Storage.Request,
Jar: cookies,
Jar: fromCookieJar(jar),
LoginInfo: b.Storage.LoginInfo,
WechatDomain: b.Caller.Client.Domain,
UUID: b.uuid,
}
return json.NewEncoder(writer).Encode(item)
return b.Serializer.Encode(writer, item)
}
// IsHot returns true if is hot login otherwise false
func (b *Bot) IsHot() bool {
return b.hotReloadStorage != nil
}
// UUID returns current UUID of bot
func (b *Bot) UUID() string {
return b.uuid
}
// SetUUID
// @description: 设置UUID可以用来手动登录用
// @receiver b
// @param UUID
// TODO ADD INTO LOGIN OPTION
func (b *Bot) SetUUID(uuid string) {
b.loginUUID = &uuid
}
// Context returns current context of bot
func (b *Bot) Context() context.Context {
return b.context
}
func (b *Bot) reload() error {
if b.hotReloadStorage == nil {
return errors.New("hotReloadStorage is nil")
}
var item HotReloadStorageItem
if err := b.Serializer.Decode(b.hotReloadStorage, &item); err != nil {
return err
}
b.Caller.Client.SetCookieJar(item.Jar)
b.Storage.LoginInfo = item.LoginInfo
b.Storage.Request = item.BaseRequest
b.Caller.Client.Domain = item.WechatDomain
b.uuid = item.UUID
return nil
}
// NewBot Bot的构造方法
@ -301,23 +351,29 @@ func NewBot(c context.Context) *Bot {
// 默认行为为网页版微信模式
caller.Client.SetMode(normal)
ctx, cancel := context.WithCancel(c)
return &Bot{Caller: caller, Storage: &Storage{}, context: ctx, cancel: cancel}
return &Bot{
Caller: caller,
Storage: &Storage{},
Serializer: &JsonSerializer{},
context: ctx,
cancel: cancel,
}
}
// DefaultBot 默认的Bot的构造方法,
// mode不传入默认为 openwechat.Desktop,详情见mode
// mode不传入默认为 openwechat.Normal,详情见mode
//
// bot := openwechat.DefaultBot(openwechat.Desktop)
func DefaultBot(opts ...BotOptionFunc) *Bot {
func DefaultBot(prepares ...BotPreparer) *Bot {
bot := NewBot(context.Background())
// 获取二维码回调
bot.UUIDCallback = PrintlnQrcodeUrl
// 扫码回调
bot.ScanCallBack = func(body []byte) {
bot.ScanCallBack = func(_ CheckLoginResponse) {
log.Println("扫码成功,请在手机上确认登录")
}
// 登录回调
bot.LoginCallBack = func(body []byte) {
bot.LoginCallBack = func(_ CheckLoginResponse) {
log.Println("登录成功")
}
// 心跳回调函数
@ -325,12 +381,27 @@ func DefaultBot(opts ...BotOptionFunc) *Bot {
bot.SyncCheckCallback = func(resp SyncCheckResponse) {
log.Printf("RetCode:%s Selector:%s", resp.RetCode, resp.Selector)
}
for _, opt := range opts {
opt(bot)
for _, prepare := range prepares {
prepare.Prepare(bot)
}
return bot
}
// defaultSyncCheckErrHandler 默认的SyncCheck错误处理函数
func defaultSyncCheckErrHandler(bot *Bot) func(error) bool {
return func(err error) bool {
var ret Ret
if errors.As(err, &ret) {
switch ret {
case failedLoginCheck, cookieInvalid, failedLoginWarn:
_ = bot.Logout()
return false
}
}
return true
}
}
// GetQrcodeUrl 通过uuid获取登录二维码的url
func GetQrcodeUrl(uuid string) string {
return qrcode + uuid
@ -365,30 +436,3 @@ func open(url string) error {
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
// IsHot returns true if is hot login otherwise false
func (b *Bot) IsHot() bool {
return b.hotReloadStorage != nil
}
// UUID returns current uuid of bot
func (b *Bot) UUID() string {
return b.uuid
}
func (b *Bot) reload() error {
if b.hotReloadStorage == nil {
return errors.New("hotReloadStorage is nil")
}
var item HotReloadStorageItem
err := json.NewDecoder(b.hotReloadStorage).Decode(&item)
if err != nil {
return err
}
b.Caller.Client.Jar = item.Jar.AsCookieJar()
b.Storage.LoginInfo = item.LoginInfo
b.Storage.Request = item.BaseRequest
b.Caller.Client.Domain = item.WechatDomain
b.uuid = item.UUID
return nil
}

View File

@ -1,18 +1,197 @@
package openwechat
import (
"context"
"time"
)
// LoginCode 定义登录状态码
type LoginCode string
const (
// LoginCodeSuccess 登录成功
LoginCodeSuccess LoginCode = "200"
// LoginCodeScanned 已扫码
LoginCodeScanned LoginCode = "201"
// LoginCodeTimeout 登录超时
LoginCodeTimeout LoginCode = "400"
// LoginCodeWait 等待扫码
LoginCodeWait LoginCode = "408"
)
func (l LoginCode) String() string {
switch l {
case LoginCodeSuccess:
return "登录成功"
case LoginCodeScanned:
return "已扫码"
case LoginCodeTimeout:
return "登录超时"
case LoginCodeWait:
return "等待扫码"
default:
return "未知状态"
}
}
type BotPreparer interface {
Prepare(*Bot)
}
type BotLoginOption interface {
BotPreparer
OnError(*Bot, error) error
OnSuccess(*Bot) error
}
// BotOptionGroup 是一个 BotLoginOption 的集合
// 用于将多个 BotLoginOption 组合成一个 BotLoginOption
type BotOptionGroup []BotLoginOption
// Prepare 实现了 BotLoginOption 接口
func (g BotOptionGroup) Prepare(bot *Bot) {
for _, option := range g {
option.Prepare(bot)
}
}
// OnError 实现了 BotLoginOption 接口
func (g BotOptionGroup) OnError(b *Bot, err error) error {
// 当有一个 BotLoginOption 的 OnError 返回的 error 等于 nil 时,就会停止执行后续的 BotLoginOption
for _, option := range g {
currentErr := option.OnError(b, err)
if currentErr == nil {
return nil
}
if currentErr != err {
return currentErr
}
}
return err
}
// OnSuccess 实现了 BotLoginOption 接口
func (g BotOptionGroup) OnSuccess(b *Bot) error {
for _, option := range g {
if err := option.OnSuccess(b); err != nil {
return err
}
}
return nil
}
type BaseBotLoginOption struct{}
func (BaseBotLoginOption) Prepare(_ *Bot) {}
func (BaseBotLoginOption) OnError(_ *Bot, err error) error { return err }
func (BaseBotLoginOption) OnSuccess(_ *Bot) error { return nil }
// DoNothingBotLoginOption 是一个空的 BotLoginOption表示不做任何操作
var DoNothingBotLoginOption = &BaseBotLoginOption{}
// RetryLoginOption 在登录失败后进行扫码登录
type RetryLoginOption struct {
BaseBotLoginOption
MaxRetryCount int
currentRetryTime int
}
// OnError 实现了 BotLoginOption 接口
// 当登录失败后,会调用此方法进行扫码登录
func (r *RetryLoginOption) OnError(bot *Bot, err error) error {
if r.currentRetryTime >= r.MaxRetryCount {
return err
}
r.currentRetryTime++
return bot.Login()
}
func NewRetryLoginOption() BotLoginOption {
return &RetryLoginOption{MaxRetryCount: 1}
}
// SyncReloadDataLoginOption 在登录成功后进行数据定时同步到指定的storage中
type SyncReloadDataLoginOption struct {
BaseBotLoginOption
SyncLoopDuration time.Duration
}
// OnSuccess 实现了 BotLoginOption 接口
// 当登录成功后会调用此方法进行数据定时同步到指定的storage中
func (s SyncReloadDataLoginOption) OnSuccess(bot *Bot) error {
if s.SyncLoopDuration <= 0 {
return nil
}
syncer := NewHotReloadStorageSyncer(bot, s.SyncLoopDuration)
go func() { _ = syncer.Sync() }()
return nil
}
func NewSyncReloadDataLoginOption(duration time.Duration) BotLoginOption {
return &SyncReloadDataLoginOption{SyncLoopDuration: duration}
}
// withModeOption 指定使用哪种客户端模式
type withModeOption struct {
mode Mode
}
// Prepare 实现了 BotLoginOption 接口
func (w withModeOption) Prepare(b *Bot) { b.Caller.Client.SetMode(w.mode) }
func withMode(mode Mode) BotPreparer {
return withModeOption{mode: mode}
}
// btw, 这两个变量已经变了4回了, 但是为了兼容以前的代码, 还是得想着法儿让用户无感知的更新
var (
// Normal 网页版微信模式
Normal = withMode(normal)
// Desktop 桌面微信模式
Desktop = withMode(desktop)
)
// WithContextOption 指定一个 context.Context 用于Bot的生命周期
type WithContextOption struct {
Ctx context.Context
}
// Prepare 实现了 BotLoginOption 接口
func (w WithContextOption) Prepare(b *Bot) {
if w.Ctx == nil {
panic("context is nil")
}
b.context, b.cancel = context.WithCancel(w.Ctx)
}
const (
defaultHotStorageSyncDuration = time.Minute * 5
)
// BotLogin 定义了一个Login的接口
type BotLogin interface {
Login(bot *Bot) error
}
// SacnLogin 扫码登录
type SacnLogin struct{}
type SacnLogin struct {
UUID *string
}
// Login 实现了 BotLogin 接口
func (s *SacnLogin) Login(bot *Bot) error {
uuid, err := bot.Caller.GetLoginUUID()
if err != nil {
return err
var uuid string
if s.UUID == nil {
var err error
uuid, err = bot.Caller.GetLoginUUID()
if err != nil {
return err
}
} else {
uuid = *s.UUID
}
return s.checkLogin(bot, uuid)
}
@ -20,69 +199,30 @@ func (s *SacnLogin) Login(bot *Bot) error {
// checkLogin 该方法会一直阻塞,直到用户扫码登录,或者二维码过期
func (s *SacnLogin) checkLogin(bot *Bot, uuid string) error {
bot.uuid = uuid
// 二维码获取回调
if bot.UUIDCallback != nil {
bot.UUIDCallback(uuid)
}
for {
// 长轮询检查是否扫码登录
resp, err := bot.Caller.CheckLogin(uuid, "0")
if err != nil {
return err
}
switch resp.Code {
case StatusSuccess:
// 判断是否有登录回调,如果有执行它
if err = bot.HandleLogin(resp.Raw); err != nil {
return err
}
if bot.LoginCallBack != nil {
bot.LoginCallBack(resp.Raw)
}
return nil
case StatusScanned:
// 执行扫码回调
if bot.ScanCallBack != nil {
bot.ScanCallBack(resp.Raw)
}
case StatusTimeout:
return ErrLoginTimeout
case StatusWait:
continue
}
loginChecker := &LoginChecker{
Bot: bot,
Tip: "0",
UUIDCallback: bot.UUIDCallback,
LoginCallBack: bot.LoginCallBack,
ScanCallBack: bot.ScanCallBack,
}
return loginChecker.CheckLogin()
}
type hotLoginOption struct {
withRetry bool
_ struct{}
}
type HotLoginOptionFunc func(o *hotLoginOption)
func HotLoginWithRetry(flag bool) HotLoginOptionFunc {
return func(o *hotLoginOption) {
o.withRetry = flag
var (
hotLoginDefaultOptions = [...]BotLoginOption{
NewSyncReloadDataLoginOption(defaultHotStorageSyncDuration),
}
}
pushLoginDefaultOptions = hotLoginDefaultOptions
)
// HotLogin 热登录模式
type HotLogin struct {
storage HotReloadStorage
opt hotLoginOption
}
// Login 实现了 BotLogin 接口
func (h *HotLogin) Login(bot *Bot) error {
err := h.login(bot)
if err != nil && h.opt.withRetry {
scanLogin := SacnLogin{}
return scanLogin.Login(bot)
}
return err
}
func (h *HotLogin) login(bot *Bot) error {
if err := h.hotLoginInit(bot); err != nil {
return err
}
@ -94,57 +234,13 @@ func (h *HotLogin) hotLoginInit(bot *Bot) error {
return bot.reload()
}
type pushLoginOption struct {
withoutUUIDCallback bool
withoutScanCallback bool
withoutLoginCallback bool
withRetry bool
}
type PushLoginOptionFunc func(o *pushLoginOption)
// PushLoginWithoutUUIDCallback 设置 PushLogin 不执行二维码回调
func PushLoginWithoutUUIDCallback(flag bool) PushLoginOptionFunc {
return func(o *pushLoginOption) {
o.withoutUUIDCallback = flag
}
}
// PushLoginWithoutScanCallback 设置 PushLogin 不执行扫码回调
func PushLoginWithoutScanCallback(flag bool) PushLoginOptionFunc {
return func(o *pushLoginOption) {
o.withoutScanCallback = flag
}
}
// PushLoginWithoutLoginCallback 设置 PushLogin 不执行登录回调
func PushLoginWithoutLoginCallback(flag bool) PushLoginOptionFunc {
return func(o *pushLoginOption) {
o.withoutLoginCallback = flag
}
}
// PushLoginWithRetry 设置 PushLogin 失败后执行扫码登录
func PushLoginWithRetry(flag bool) PushLoginOptionFunc {
return func(o *pushLoginOption) {
o.withRetry = flag
}
}
// defaultPushLoginOpts 默认的 PushLogin
var defaultPushLoginOpts = [...]PushLoginOptionFunc{
PushLoginWithoutUUIDCallback(true),
PushLoginWithoutScanCallback(true),
}
// PushLogin 免扫码登录模式
type PushLogin struct {
storage HotReloadStorage
opt pushLoginOption
}
// Login 实现了 BotLogin 接口
func (p PushLogin) Login(bot *Bot) error {
func (p *PushLogin) Login(bot *Bot) error {
if err := p.pushLoginInit(bot); err != nil {
return err
}
@ -155,55 +251,113 @@ func (p PushLogin) Login(bot *Bot) error {
if err = resp.Err(); err != nil {
return err
}
err = p.checkLogin(bot, resp.UUID, "1")
if err != nil && p.opt.withRetry {
scanLogin := SacnLogin{}
return scanLogin.Login(bot)
}
return err
return p.checkLogin(bot, resp.UUID)
}
func (p PushLogin) pushLoginInit(bot *Bot) error {
func (p *PushLogin) pushLoginInit(bot *Bot) error {
bot.hotReloadStorage = p.storage
return bot.reload()
}
// checkLogin 登录检查
func (p PushLogin) checkLogin(bot *Bot, uuid, tip string) error {
// todo 将checkLogin剥离出来
func (p *PushLogin) checkLogin(bot *Bot, uuid string) error {
bot.uuid = uuid
// 二维码获取回调
if bot.UUIDCallback != nil && !p.opt.withoutUUIDCallback {
bot.UUIDCallback(uuid)
// 为什么把 UUIDCallback 和 ScanCallBack 置为nil呢?
// 因为这两个对用户是无感知的。
loginChecker := &LoginChecker{
Bot: bot,
Tip: "1",
LoginCallBack: bot.LoginCallBack,
}
return loginChecker.CheckLogin()
}
type LoginChecker struct {
Bot *Bot
Tip string
UUIDCallback func(uuid string)
LoginCallBack func(body CheckLoginResponse)
ScanCallBack func(body CheckLoginResponse)
}
func (l *LoginChecker) CheckLogin() error {
uuid := l.Bot.UUID()
// 二维码获取回调
if cb := l.UUIDCallback; cb != nil {
cb(uuid)
}
var tip = l.Tip
for {
// 长轮询检查是否扫码登录
resp, err := bot.Caller.CheckLogin(uuid, tip)
resp, err := l.Bot.Caller.CheckLogin(uuid, tip)
if err != nil {
return err
}
code, err := resp.Code()
if err != nil {
return err
}
if tip == "1" {
tip = "0"
}
switch resp.Code {
case StatusSuccess:
switch code {
case LoginCodeSuccess:
// 判断是否有登录回调,如果有执行它
if err = bot.HandleLogin(resp.Raw); err != nil {
redirectURL, err := resp.RedirectURL()
if err != nil {
return err
}
if bot.LoginCallBack != nil && !p.opt.withoutLoginCallback {
bot.LoginCallBack(resp.Raw)
if err = l.Bot.HandleLogin(redirectURL); err != nil {
return err
}
if cb := l.LoginCallBack; cb != nil {
cb(resp)
}
return nil
case StatusScanned:
case LoginCodeScanned:
// 执行扫码回调
if bot.ScanCallBack != nil && !p.opt.withoutScanCallback {
bot.ScanCallBack(resp.Raw)
if cb := l.ScanCallBack; cb != nil {
cb(resp)
}
case StatusTimeout:
case LoginCodeTimeout:
return ErrLoginTimeout
case StatusWait:
case LoginCodeWait:
continue
}
}
}
// # 下面都是即将废弃的函数。
// # 为了兼容老版本暂时留了下来, 但是它的函数签名已经发生了改变。
// # 如果你是使用的是openwechat提供的api来调用这些函数那么你是感知不到变动的。
// # openwechat内部对这些函数的调用做了兼容处理, 如果你的代码中调用了这些函数, 请尽快修改。
// Deprecated: 请使用 NewRetryLoginOption 代替
// HotLoginWithRetry 热登录模式,如果登录失败会重试
func HotLoginWithRetry(flag bool) BotLoginOption {
if flag {
return NewRetryLoginOption()
}
return DoNothingBotLoginOption
}
// Deprecated: 请使用 NewRetryLoginOption 代替
// HotLoginWithSyncReloadData 定时同步热登录数据
func HotLoginWithSyncReloadData(duration time.Duration) BotLoginOption {
return NewSyncReloadDataLoginOption(duration)
}
// Deprecated: 请使用 NewRetryLoginOption 代替
// PushLoginWithRetry 免扫码登录模式,如果登录失败会重试
func PushLoginWithRetry(flag bool) BotLoginOption {
if !flag {
return DoNothingBotLoginOption
}
return NewRetryLoginOption()
}
// Deprecated: 请使用 NewSyncReloadDataLoginOption 代替
// PushLoginWithSyncReloadData 定时同步热登录数据
func PushLoginWithSyncReloadData(duration time.Duration) BotLoginOption {
return NewSyncReloadDataLoginOption(duration)
}

View File

@ -1,30 +0,0 @@
package openwechat
import (
"context"
)
// BotOptionFunc 用于设置Bot的选项
type BotOptionFunc func(*Bot)
// Normal 网页版微信
func Normal(b *Bot) {
b.Caller.Client.SetMode(normal)
}
// Desktop 模式
func Desktop(b *Bot) {
b.Caller.Client.SetMode(desktop)
}
func WithContext(ctx context.Context) BotOptionFunc {
return func(b *Bot) {
b.context = ctx
}
}
func WithDeviceID(deviceID string) BotOptionFunc {
return func(b *Bot) {
b.SetDeviceId(deviceID)
}
}

View File

@ -128,4 +128,30 @@ func TestSender(t *testing.T) {
bot.Block()
}
// TestGetUUID
// @description: 获取登录二维码(UUID)
// @param t
func TestGetUUID(t *testing.T) {
bot := DefaultBot(Desktop)
uuid, err := bot.Caller.GetLoginUUID()
if err != nil {
t.Error(err)
return
}
t.Log(uuid)
}
// TestLoginWithUUID
// @description: 使用UUID登录
// @param t
func TestLoginWithUUID(t *testing.T) {
uuid := "oZZsO0Qv8Q=="
bot := DefaultBot(Desktop)
bot.SetUUID(uuid)
err := bot.Login()
if err != nil {
t.Errorf("登录失败: %v", err.Error())
return
}
}

View File

@ -50,7 +50,7 @@ func (c *Caller) GetLoginUUID() (string, error) {
}
// CheckLogin 检查是否登录成功
func (c *Caller) CheckLogin(uuid, tip string) (*CheckLoginResponse, error) {
func (c *Caller) CheckLogin(uuid, tip string) (CheckLoginResponse, error) {
resp, err := c.Client.CheckLogin(uuid, tip)
if err != nil {
return nil, err
@ -61,29 +61,13 @@ func (c *Caller) CheckLogin(uuid, tip string) (*CheckLoginResponse, error) {
if _, err := buffer.ReadFrom(resp.Body); err != nil {
return nil, err
}
// 正则匹配检测的code
// 具体code参考global.go
results := statusCodeRegexp.FindSubmatch(buffer.Bytes())
if len(results) != 2 {
return nil, errors.New("error status code match")
}
code := string(results[1])
return &CheckLoginResponse{Code: code, Raw: buffer.Bytes()}, nil
return buffer.Bytes(), nil
}
// GetLoginInfo 获取登录信息
func (c *Caller) GetLoginInfo(body []byte) (*LoginInfo, error) {
func (c *Caller) GetLoginInfo(path *url.URL) (*LoginInfo, error) {
// 从响应体里面获取需要跳转的url
results := redirectUriRegexp.FindSubmatch(body)
if len(results) != 2 {
return nil, errors.New("redirect url does not match")
}
path, err := url.Parse(string(results[1]))
if err != nil {
return nil, err
}
c.Client.Domain = WechatDomain(path.Host)
resp, err := c.Client.GetLoginInfo(path.String())
resp, err := c.Client.GetLoginInfo(path)
if err != nil {
return nil, err
}
@ -147,7 +131,7 @@ func (c *Caller) SyncCheck(request *BaseRequest, info *LoginInfo, response *WebI
if len(results) != 3 {
return nil, errors.New("parse sync key failed")
}
retCode, selector := string(results[1]), string(results[2])
retCode, selector := string(results[1]), Selector(results[2])
syncCheckResponse := &SyncCheckResponse{RetCode: retCode, Selector: selector}
return syncCheckResponse, nil
}
@ -260,7 +244,12 @@ func (c *Caller) UploadMedia(file *os.File, request *BaseRequest, info *LoginInf
}
// WebWxSendImageMsg 发送图片消息接口
func (c *Caller) WebWxSendImageMsg(file *os.File, request *BaseRequest, info *LoginInfo, fromUserName, toUserName string) (*SentMessage, error) {
func (c *Caller) WebWxSendImageMsg(reader io.Reader, request *BaseRequest, info *LoginInfo, fromUserName, toUserName string) (*SentMessage, error) {
file, cb, err := readerToFile(reader)
if err != nil {
return nil, err
}
defer cb()
// 首先尝试上传图片
var mediaId string
{
@ -282,7 +271,12 @@ func (c *Caller) WebWxSendImageMsg(file *os.File, request *BaseRequest, info *Lo
return parser.SentMessage(msg)
}
func (c *Caller) WebWxSendFile(file *os.File, req *BaseRequest, info *LoginInfo, fromUserName, toUserName string) (*SentMessage, error) {
func (c *Caller) WebWxSendFile(reader io.Reader, req *BaseRequest, info *LoginInfo, fromUserName, toUserName string) (*SentMessage, error) {
file, cb, err := readerToFile(reader)
if err != nil {
return nil, err
}
defer cb()
resp, err := c.UploadMedia(file, req, info, fromUserName, toUserName)
if err != nil {
return nil, err
@ -298,7 +292,12 @@ func (c *Caller) WebWxSendFile(file *os.File, req *BaseRequest, info *LoginInfo,
return c.WebWxSendAppMsg(msg, req)
}
func (c *Caller) WebWxSendVideoMsg(file *os.File, request *BaseRequest, info *LoginInfo, fromUserName, toUserName string) (*SentMessage, error) {
func (c *Caller) WebWxSendVideoMsg(reader io.Reader, request *BaseRequest, info *LoginInfo, fromUserName, toUserName string) (*SentMessage, error) {
file, cb, err := readerToFile(reader)
if err != nil {
return nil, err
}
defer cb()
var mediaId string
{
resp, err := c.UploadMedia(file, request, info, fromUserName, toUserName)
@ -500,3 +499,29 @@ func (p *MessageResponseParser) SentMessage(msg *SendMessage) (*SentMessage, err
}
return &SentMessage{MsgId: msgID, SendMessage: msg}, nil
}
func readerToFile(reader io.Reader) (file *os.File, cb func(), err error) {
var ok bool
if file, ok = reader.(*os.File); ok {
return file, func() {}, nil
}
file, err = os.CreateTemp("", "*")
if err != nil {
return nil, nil, err
}
cb = func() {
_ = file.Close()
_ = os.Remove(file.Name())
}
_, err = io.Copy(file, reader)
if err != nil {
cb()
return nil, nil, err
}
_, err = file.Seek(0, io.SeekStart)
if err != nil {
cb()
return nil, nil, err
}
return file, cb, nil
}

153
client.go
View File

@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
@ -11,9 +12,9 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
@ -31,30 +32,44 @@ func (u UserAgentHook) BeforeRequest(req *http.Request) {
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36")
}
func (u UserAgentHook) AfterRequest(response *http.Response, err error) {}
func (u UserAgentHook) AfterRequest(_ *http.Response, _ error) {}
// Client http请求客户端
// 客户端需要维持Session会话
// 并且客户端不允许跳转
type Client struct {
// 设置一些client的请求行为
// see normalMode desktopMode
mode Mode
// client http客户端
client *http.Client
// Domain 微信服务器请求域名
// 这个参数会在登录成功后被赋值
// 之后所有的请求都会使用这个域名
// 在登录热登录和扫码登录时会被重新赋值
Domain WechatDomain
// HttpHooks 请求上下文钩子
HttpHooks HttpHooks
*http.Client
Domain WechatDomain
mode Mode
mu sync.Mutex
// MaxRetryTimes 最大重试次数
MaxRetryTimes int
}
func NewClient() *Client {
timeout := 30 * time.Second
return &Client{
Client: &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Jar: newCookieJar(),
Timeout: timeout,
}}
httpClient := &http.Client{
// 设置客户端不自动跳转
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
// 设置30秒超时
// 因为微信同步消息时是一个时间长达25秒的长轮训
Timeout: 30 * time.Second,
}
client := &Client{client: httpClient}
client.SetCookieJar(NewJar())
return client
}
// DefaultClient 自动存储cookie
@ -79,7 +94,7 @@ func (c *Client) do(req *http.Request) (*http.Response, error) {
err error
)
for i := 0; i < c.MaxRetryTimes; i++ {
resp, err = c.Client.Do(req)
resp, err = c.client.Do(req)
if err == nil {
break
}
@ -99,9 +114,17 @@ func (c *Client) Do(req *http.Request) (*http.Response, error) {
return c.do(req)
}
// GetCookieJar 获取当前client的所有的有效的client
func (c *Client) GetCookieJar() *Jar {
return fromCookieJar(c.Client.Jar)
// Jar 返回当前client的 http.CookieJar
// this http.CookieJar must be *Jar type
func (c *Client) Jar() http.CookieJar {
return c.client.Jar
}
// SetCookieJar 设置cookieJar
// 这里限制了cookieJar必须是Jar类型
// 否则进行cookie序列化的时候因为字段的私有性无法进行所有字段的导出
func (c *Client) SetCookieJar(jar *Jar) {
c.client.Jar = jar.AsCookieJar()
}
// GetLoginUUID 获取登录的uuid
@ -112,7 +135,7 @@ func (c *Client) GetLoginUUID() (*http.Response, error) {
// GetLoginQrcode 获取登录的二维吗
func (c *Client) GetLoginQrcode(uuid string) (*http.Response, error) {
path := qrcode + uuid
return c.Get(path)
return c.client.Get(path)
}
// CheckLogin 检查是否登录
@ -131,8 +154,9 @@ func (c *Client) CheckLogin(uuid, tip string) (*http.Response, error) {
}
// GetLoginInfo 请求获取LoginInfo
func (c *Client) GetLoginInfo(path string) (*http.Response, error) {
return c.mode.GetLoginInfo(c, path)
func (c *Client) GetLoginInfo(path *url.URL) (*http.Response, error) {
c.Domain = WechatDomain(path.Host)
return c.mode.GetLoginInfo(c, path.String())
}
// WebInit 请求获取初始化信息
@ -290,6 +314,8 @@ func (c *Client) WebWxGetHeadImg(user *User) (*http.Response, error) {
return c.Do(req)
}
// WebWxUploadMediaByChunk 分块上传文件
// TODO 优化掉这个函数
func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, info *LoginInfo, forUserName, toUserName string) (*http.Response, error) {
// 获取文件上传的类型
contentType, err := GetFileContentType(file)
@ -310,15 +336,22 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
return nil, err
}
fileMd5 := fmt.Sprintf("%x", h.Sum(nil))
fileMd5 := hex.EncodeToString(h.Sum(nil))
sate, err := file.Stat()
if err != nil {
return nil, err
}
filename := sate.Name()
if ext := filepath.Ext(filename); ext == "" {
names := strings.Split(contentType, "/")
filename = filename + "." + names[len(names)-1]
}
// 获取文件的类型
mediaType := getMessageType(sate.Name())
mediaType := getMessageType(filename)
path, _ := url.Parse(c.Domain.FileHost() + webwxuploadmedia)
params := url.Values{}
@ -326,8 +359,12 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
path.RawQuery = params.Encode()
cookies := c.Jar.Cookies(path)
webWxDataTicket := getWebWxDataTicket(cookies)
cookies := c.Jar().Cookies(path)
webWxDataTicket, err := getWebWxDataTicket(cookies)
if err != nil {
return nil, err
}
uploadMediaRequest := map[string]interface{}{
"UploadType": 2,
@ -362,7 +399,7 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
content := map[string]string{
"id": "WU_FILE_0",
"name": file.Name(),
"name": filename,
"type": contentType,
"lastModifiedDate": sate.ModTime().Format(TimeFormat),
"size": strconv.FormatInt(sate.Size(), 10),
@ -379,16 +416,17 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
return nil, err
}
var chunkBuff = make([]byte, chunkSize)
var formBuffer = bytes.NewBuffer(nil)
// 分块上传
for chunk := 0; int64(chunk) < chunks; chunk++ {
isLastTime := int64(chunk)+1 == chunks
if chunks > 1 {
content["chunk"] = strconv.Itoa(chunk)
}
var formBuffer = bytes.NewBuffer(nil)
formBuffer.Reset()
writer := multipart.NewWriter(formBuffer)
@ -403,34 +441,33 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
}
w, err := writer.CreateFormFile("filename", file.Name())
if err != nil {
return nil, err
}
chunkData := make([]byte, chunkSize)
n, err := file.Read(chunkData)
n, err := file.Read(chunkBuff)
if err != nil && err != io.EOF {
return nil, err
}
if _, err = w.Write(chunkData[:n]); err != nil {
if _, err = w.Write(chunkBuff[:n]); err != nil {
return nil, err
}
ct := writer.FormDataContentType()
if err = writer.Close(); err != nil {
return nil, err
}
req, _ := http.NewRequest(http.MethodPost, path.String(), formBuffer)
req.Header.Set("Content-Type", ct)
// 发送数据
resp, err = c.Do(req)
if err != nil {
return nil, err
}
isLastTime := int64(chunk)+1 == chunks
// 如果不是最后一次, 解析有没有错误
if !isLastTime {
parser := MessageResponseParser{Reader: resp.Body}
@ -560,13 +597,18 @@ func (c *Client) WebWxGetVideo(msg *Message, info *LoginInfo) (*http.Response, e
// WebWxGetMedia 获取文件消息的文件响应
func (c *Client) WebWxGetMedia(msg *Message, info *LoginInfo) (*http.Response, error) {
path, _ := url.Parse(c.Domain.FileHost() + webwxgetmedia)
cookies := c.Jar().Cookies(path)
webWxDataTicket, err := getWebWxDataTicket(cookies)
if err != nil {
return nil, err
}
params := url.Values{}
params.Add("sender", msg.FromUserName)
params.Add("mediaid", msg.MediaId)
params.Add("encryfilename", msg.EncryFileName)
params.Add("fromuser", strconv.FormatInt(info.WxUin, 10))
params.Add("pass_ticket", info.PassTicket)
params.Add("webwx_data_ticket", getWebWxDataTicket(c.Jar.Cookies(path)))
params.Add("webwx_data_ticket", webWxDataTicket)
path.RawQuery = params.Encode()
req, _ := http.NewRequest(http.MethodGet, path.String(), nil)
req.Header.Add("Referer", c.Domain.BaseHost()+"/")
@ -587,6 +629,14 @@ func (c *Client) Logout(info *LoginInfo) (*http.Response, error) {
// AddMemberIntoChatRoom 添加用户进群聊
func (c *Client) AddMemberIntoChatRoom(req *BaseRequest, info *LoginInfo, group *Group, friends ...*Friend) (*http.Response, error) {
if len(group.MemberList) >= 40 {
return c.InviteMemberIntoChatRoom(req, info, group, friends...)
}
return c.addMemberIntoChatRoom(req, info, group, friends...)
}
// addMemberIntoChatRoom 添加用户进群聊
func (c *Client) addMemberIntoChatRoom(req *BaseRequest, info *LoginInfo, group *Group, friends ...*Friend) (*http.Response, error) {
path, _ := url.Parse(c.Domain.BaseHost() + webwxupdatechatroom)
params := url.Values{}
params.Add("fun", "addmember")
@ -608,6 +658,29 @@ func (c *Client) AddMemberIntoChatRoom(req *BaseRequest, info *LoginInfo, group
return c.Do(requ)
}
// InviteMemberIntoChatRoom 邀请用户进群聊
func (c *Client) InviteMemberIntoChatRoom(req *BaseRequest, info *LoginInfo, group *Group, friends ...*Friend) (*http.Response, error) {
path, _ := url.Parse(c.Domain.BaseHost() + webwxupdatechatroom)
params := url.Values{}
params.Add("fun", "invitemember")
params.Add("pass_ticket", info.PassTicket)
params.Add("lang", "zh_CN")
path.RawQuery = params.Encode()
addMemberList := make([]string, len(friends))
for index, friend := range friends {
addMemberList[index] = friend.UserName
}
content := map[string]interface{}{
"ChatRoomName": group.UserName,
"BaseRequest": req,
"InviteMemberList": strings.Join(addMemberList, ","),
}
buffer, _ := ToBuffer(content)
requ, _ := http.NewRequest(http.MethodPost, path.String(), buffer)
requ.Header.Set("Content-Type", jsonContentType)
return c.Do(requ)
}
// RemoveMemberFromChatRoom 从群聊中移除用户
func (c *Client) RemoveMemberFromChatRoom(req *BaseRequest, info *LoginInfo, group *Group, friends ...*User) (*http.Response, error) {
path, _ := url.Parse(c.Domain.BaseHost() + webwxupdatechatroom)

View File

@ -9,6 +9,7 @@ import (
)
// Jar is a struct which as same as cookiejar.Jar
// cookiejar.Jar's fields are private, so we can't use it directly
type Jar struct {
PsList cookiejar.PublicSuffixList
@ -16,7 +17,7 @@ type Jar struct {
mu sync.Mutex
// Entries is a set of entries, keyed by their eTLD+1 and subkeyed by
// their name/domain/path.
// their name/Domain/path.
Entries map[string]map[string]entry
// nextSeqNum is the next sequence number assigned to a new cookie
@ -29,15 +30,15 @@ func (j *Jar) AsCookieJar() http.CookieJar {
return (*cookiejar.Jar)(unsafe.Pointer(j))
}
func newCookieJar() http.CookieJar {
jar, _ := cookiejar.New(nil)
return jar
}
func fromCookieJar(jar http.CookieJar) *Jar {
return (*Jar)(unsafe.Pointer(jar.(*cookiejar.Jar)))
}
func NewJar() *Jar {
jar, _ := cookiejar.New(nil)
return fromCookieJar(jar)
}
type entry struct {
Name string
Value string
@ -57,3 +58,24 @@ type entry struct {
// equal Creation time. This simplifies testing.
seqNum uint64
}
// CookieGroup is a group of cookies
type CookieGroup []*http.Cookie
func (c CookieGroup) GetByName(cookieName string) (cookie *http.Cookie, exist bool) {
for _, cookie := range c {
if cookie.Name == cookieName {
return cookie, true
}
}
return nil, false
}
func getWebWxDataTicket(cookies []*http.Cookie) (string, error) {
cookieGroup := CookieGroup(cookies)
cookie, exist := cookieGroup.GetByName("webwx_data_ticket")
if !exist {
return "", ErrWebWxDataTicketNotFound
}
return cookie.Value, nil
}

View File

@ -2,7 +2,8 @@ package openwechat
import (
"errors"
"strconv"
"fmt"
"net/url"
)
/*
@ -56,9 +57,9 @@ type WebInitResponse struct {
SKey string
BaseResponse BaseResponse
SyncKey SyncKey
User User
MPSubscribeMsgList []MPSubscribeMsg
ContactList []User
User *User
MPSubscribeMsgList []*MPSubscribeMsg
ContactList Members
}
// MPSubscribeMsg 公众号的订阅信息
@ -67,12 +68,14 @@ type MPSubscribeMsg struct {
Time int64
UserName string
NickName string
MPArticleList []struct {
Title string
Cover string
Digest string
Url string
}
MPArticleList []*MPArticle
}
type MPArticle struct {
Title string
Cover string
Digest string
Url string
}
type UserDetailItem struct {
@ -91,30 +94,6 @@ func NewUserDetailItemList(members Members) UserDetailItemList {
return list
}
type SyncCheckResponse struct {
RetCode string
Selector string
}
func (s SyncCheckResponse) Success() bool {
return s.RetCode == "0"
}
func (s SyncCheckResponse) NorMal() bool {
return s.Success() && s.Selector == "0"
}
func (s SyncCheckResponse) Err() error {
if s.Success() {
return nil
}
i, err := strconv.ParseInt(s.RetCode, 16, 10)
if err != nil {
return errors.New("sync check unknown error")
}
return errors.New(Ret(i).String())
}
type WebWxSyncResponse struct {
AddMsgCount int
ContinueFlag int
@ -142,9 +121,49 @@ type WebWxBatchContactResponse struct {
ContactList []*User
}
type CheckLoginResponse struct {
Code string
Raw []byte
// CheckLoginResponse 检查登录状态的响应body
type CheckLoginResponse []byte
// RedirectURL 重定向的URL
func (c CheckLoginResponse) RedirectURL() (*url.URL, error) {
code, err := c.Code()
if err != nil {
return nil, err
}
if code != LoginCodeSuccess {
return nil, fmt.Errorf("expect status code %s, but got %s", LoginCodeSuccess, code)
}
results := redirectUriRegexp.FindSubmatch(c)
if len(results) != 2 {
return nil, errors.New("redirect url does not match")
}
return url.Parse(string(results[1]))
}
// Code 获取当前的登录检查状态的代码
func (c CheckLoginResponse) Code() (LoginCode, error) {
results := statusCodeRegexp.FindSubmatch(c)
if len(results) != 2 {
return "", errors.New("error status code match")
}
code := string(results[1])
return LoginCode(code), nil
}
// Avatar 获取扫码后的用户头像, base64编码
func (c CheckLoginResponse) Avatar() (string, error) {
code, err := c.Code()
if err != nil {
return "", err
}
if code != LoginCodeScanned {
return "", nil
}
results := avatarRegexp.FindSubmatch(c)
if len(results) != 2 {
return "", errors.New("avatar does not match")
}
return string(results[1]), nil
}
type MessageResponse struct {

View File

@ -26,6 +26,15 @@ var (
// NetworkErr define wechat network error
NetworkErr = errors.New("wechat network error")
// ErrNoSuchUserFoundError define no such user found error
ErrNoSuchUserFoundError = errors.New("no such user found")
// ErrLoginTimeout define login timeout error
ErrLoginTimeout = errors.New("login timeout")
// ErrWebWxDataTicketNotFound define webwx_data_ticket not found error
ErrWebWxDataTicketNotFound = errors.New("webwx_data_ticket not found")
)
// Error impl error interface

View File

@ -1,13 +1,13 @@
package openwechat
import (
"errors"
"regexp"
)
var (
uuidRegexp = regexp.MustCompile(`uuid = "(.*?)";`)
statusCodeRegexp = regexp.MustCompile(`window.code=(\d+);`)
avatarRegexp = regexp.MustCompile(`window.userAvatar = '(.*)';`)
syncCheckRegexp = regexp.MustCompile(`window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}`)
redirectUriRegexp = regexp.MustCompile(`window.redirect_uri="(.*?)"`)
)
@ -98,20 +98,6 @@ const (
AppMsgTypeReaderType AppMessageType = 100001 //自定义的消息
)
// 登录状态
const (
StatusSuccess = "200"
StatusScanned = "201"
StatusTimeout = "400"
StatusWait = "408"
)
// errors
var (
ErrNoSuchUserFoundError = errors.New("no such user found")
ErrLoginTimeout = errors.New("login timeout")
)
// ALL 跟search函数搭配
//
// friends.Search(openwechat.ALL, )
@ -143,8 +129,7 @@ var imageType = map[string]struct{}{
"jpg": {},
}
var videoType = "mp4"
const videoType = "mp4"
// ZombieText 检测僵尸好友字符串
// 发送该字符给好友,能正常发送不报错的为正常好友,否则为僵尸好友
const ZombieText = "وُحfخe ̷̴̐nخg ̷̴̐cخh ̷̴̐aخo امارتيخ ̷̴̐خ\n"
// FileHelper 文件传输助手
const FileHelper = "filehelper"

View File

@ -114,9 +114,10 @@ func (m *Message) Receiver() (*User, error) {
return m.bot.self.User, nil
}
// https://github.com/eatmoreapple/openwechat/issues/113
if m.ToUserName == m.bot.self.fileHelper.UserName {
return m.bot.self.fileHelper.User, nil
if m.ToUserName == FileHelper {
return m.bot.self.FileHelper().User, nil
}
if m.IsSendByGroup() {
groups, err := m.bot.self.Groups()
if err != nil {
@ -165,7 +166,7 @@ func (m *Message) ReplyText(content string) (*SentMessage, error) {
}
// ReplyImage 回复图片消息
func (m *Message) ReplyImage(file *os.File) (*SentMessage, error) {
func (m *Message) ReplyImage(file io.Reader) (*SentMessage, error) {
info := m.bot.Storage.LoginInfo
request := m.bot.Storage.Request
sentMessage, err := m.bot.Caller.WebWxSendImageMsg(file, request, info, m.bot.self.UserName, m.FromUserName)
@ -173,7 +174,7 @@ func (m *Message) ReplyImage(file *os.File) (*SentMessage, error) {
}
// ReplyVideo 回复视频消息
func (m *Message) ReplyVideo(file *os.File) (*SentMessage, error) {
func (m *Message) ReplyVideo(file io.Reader) (*SentMessage, error) {
info := m.bot.Storage.LoginInfo
request := m.bot.Storage.Request
sentMessage, err := m.bot.Caller.WebWxSendVideoMsg(file, request, info, m.bot.self.UserName, m.FromUserName)
@ -181,7 +182,7 @@ func (m *Message) ReplyVideo(file *os.File) (*SentMessage, error) {
}
// ReplyFile 回复文件消息
func (m *Message) ReplyFile(file *os.File) (*SentMessage, error) {
func (m *Message) ReplyFile(file io.Reader) (*SentMessage, error) {
info := m.bot.Storage.LoginInfo
request := m.bot.Storage.Request
sentMessage, err := m.bot.Caller.WebWxSendFile(file, request, info, m.bot.self.UserName, m.FromUserName)
@ -790,7 +791,7 @@ func (m *Message) IsAt() bool {
// IsPaiYiPai 判断消息是否为拍一拍
// 不要问我为什么取名为PaiYiPai因为我也不知道取啥名字好
func (m *Message) IsPaiYiPai() bool {
return m.IsSystem() && strings.Contains(m.Content, "拍了拍")
return m.IsTickled()
}
// IsJoinGroup 判断是否有人加入了群聊
@ -800,7 +801,12 @@ func (m *Message) IsJoinGroup() bool {
// IsTickled 判断消息是否为拍一拍
func (m *Message) IsTickled() bool {
return m.IsPaiYiPai()
return m.IsSystem() && strings.Contains(m.Content, "拍了拍")
}
// IsTickledMe 判断消息是否拍了拍自己
func (m *Message) IsTickledMe() bool {
return m.IsSystem() && strings.Count(m.Content, "拍了拍我") == 1
}
// IsVoipInvite 判断消息是否为语音或视频通话邀请

View File

@ -11,14 +11,6 @@ type MessageDispatcher interface {
Dispatch(msg *Message)
}
// DispatchMessage 跟 MessageDispatcher 结合封装成 MessageHandler
// Deprecated: use MessageMatchDispatcher.AsMessageHandler instead
func DispatchMessage(dispatcher MessageDispatcher) func(msg *Message) {
return func(msg *Message) { dispatcher.Dispatch(msg) }
}
// MessageDispatcher impl
// MessageContextHandler 消息处理函数
type MessageContextHandler func(ctx *MessageContext)

View File

@ -38,15 +38,6 @@ func GetRandomDeviceId() string {
return builder.String()
}
func getWebWxDataTicket(cookies []*http.Cookie) string {
for _, cookie := range cookies {
if cookie.Name == "webwx_data_ticket" {
return cookie.Value
}
}
return ""
}
// GetFileContentType 获取文件上传的类型
func GetFileContentType(file multipart.File) (string, error) {
data := make([]byte, 512)

View File

@ -2,15 +2,19 @@ package openwechat
import (
"fmt"
"os"
"io"
"time"
)
type Friend struct{ *User }
// implement fmt.Stringer
func (f Friend) String() string {
return fmt.Sprintf("<Friend:%s>", f.NickName)
func (f *Friend) String() string {
display := f.NickName
if f.RemarkName != "" {
display = f.RemarkName
}
return fmt.Sprintf("<Friend:%s>", display)
}
// SetRemarkName 重命名当前好友
@ -24,17 +28,17 @@ func (f *Friend) SendText(content string) (*SentMessage, error) {
}
// SendImage 发送图片消息
func (f *Friend) SendImage(file *os.File) (*SentMessage, error) {
func (f *Friend) SendImage(file io.Reader) (*SentMessage, error) {
return f.self.SendImageToFriend(f, file)
}
// SendVideo 发送视频消息
func (f *Friend) SendVideo(file *os.File) (*SentMessage, error) {
func (f *Friend) SendVideo(file io.Reader) (*SentMessage, error) {
return f.self.SendVideoToFriend(f, file)
}
// SendFile 发送文件消息
func (f *Friend) SendFile(file *os.File) (*SentMessage, error) {
func (f *Friend) SendFile(file io.Reader) (*SentMessage, error) {
return f.self.SendFileToFriend(f, file)
}
@ -53,7 +57,7 @@ func (f Friends) Count() int {
// First 获取第一个好友
func (f Friends) First() *Friend {
if f.Count() > 0 {
return f[0]
return f.Sort()[0]
}
return nil
}
@ -61,7 +65,7 @@ func (f Friends) First() *Friend {
// Last 获取最后一个好友
func (f Friends) Last() *Friend {
if f.Count() > 0 {
return f[f.Count()-1]
return f.Sort()[f.Count()-1]
}
return nil
}
@ -103,6 +107,16 @@ func (f Friends) AsMembers() Members {
return members
}
// Sort 对好友进行排序
func (f Friends) Sort() Friends {
return f.AsMembers().Sort().Friends()
}
// Uniq 对好友进行去重
func (f Friends) Uniq() Friends {
return f.AsMembers().Uniq().Friends()
}
// SendText 向slice的好友依次发送文本消息
func (f Friends) SendText(text string, delays ...time.Duration) error {
if f.Count() == 0 {
@ -117,7 +131,7 @@ func (f Friends) SendText(text string, delays ...time.Duration) error {
}
// SendImage 向slice的好友依次发送图片消息
func (f Friends) SendImage(file *os.File, delays ...time.Duration) error {
func (f Friends) SendImage(file io.Reader, delays ...time.Duration) error {
if f.Count() == 0 {
return nil
}
@ -130,7 +144,7 @@ func (f Friends) SendImage(file *os.File, delays ...time.Duration) error {
}
// SendFile 群发文件
func (f Friends) SendFile(file *os.File, delay ...time.Duration) error {
func (f Friends) SendFile(file io.Reader, delay ...time.Duration) error {
if f.Count() == 0 {
return nil
}
@ -145,7 +159,7 @@ func (f Friends) SendFile(file *os.File, delay ...time.Duration) error {
type Group struct{ *User }
// implement fmt.Stringer
func (g Group) String() string {
func (g *Group) String() string {
return fmt.Sprintf("<Group:%s>", g.NickName)
}
@ -155,17 +169,17 @@ func (g *Group) SendText(content string) (*SentMessage, error) {
}
// SendImage 发行图片消息给当前的群组
func (g *Group) SendImage(file *os.File) (*SentMessage, error) {
func (g *Group) SendImage(file io.Reader) (*SentMessage, error) {
return g.self.SendImageToGroup(g, file)
}
// SendVideo 发行视频消息给当前的群组
func (g *Group) SendVideo(file *os.File) (*SentMessage, error) {
func (g *Group) SendVideo(file io.Reader) (*SentMessage, error) {
return g.self.SendVideoToGroup(g, file)
}
// SendFile 发送文件给当前的群组
func (g *Group) SendFile(file *os.File) (*SentMessage, error) {
func (g *Group) SendFile(file io.Reader) (*SentMessage, error) {
return g.self.SendFileToGroup(g, file)
}
@ -180,6 +194,7 @@ func (g *Group) Members() (Members, error) {
// AddFriendsIn 拉好友入群
func (g *Group) AddFriendsIn(friends ...*Friend) error {
friends = Friends(friends).Uniq()
return g.self.AddFriendsIntoGroup(g, friends...)
}
@ -227,7 +242,7 @@ func (g Groups) Count() int {
// First 获取第一个群组
func (g Groups) First() *Group {
if g.Count() > 0 {
return g[0]
return g.Sort()[0]
}
return nil
}
@ -235,7 +250,7 @@ func (g Groups) First() *Group {
// Last 获取最后一个群组
func (g Groups) Last() *Group {
if g.Count() > 0 {
return g[g.Count()-1]
return g.Sort()[g.Count()-1]
}
return nil
}
@ -254,7 +269,7 @@ func (g Groups) SendText(text string, delay ...time.Duration) error {
}
// SendImage 向群组依次发送图片消息, 支持发送延迟
func (g Groups) SendImage(file *os.File, delay ...time.Duration) error {
func (g Groups) SendImage(file io.Reader, delay ...time.Duration) error {
if g.Count() == 0 {
return nil
}
@ -267,7 +282,7 @@ func (g Groups) SendImage(file *os.File, delay ...time.Duration) error {
}
// SendFile 向群组依次发送文件消息, 支持发送延迟
func (g Groups) SendFile(file *os.File, delay ...time.Duration) error {
func (g Groups) SendFile(file io.Reader, delay ...time.Duration) error {
if g.Count() == 0 {
return nil
}
@ -289,11 +304,6 @@ func (g Groups) SearchByNickName(limit int, nickName string) (results Groups) {
return g.Search(limit, func(group *Group) bool { return group.NickName == nickName })
}
// SearchByRemarkName 根据备注查找群组
func (g Groups) SearchByRemarkName(limit int, remarkName string) (results Groups) {
return g.Search(limit, func(group *Group) bool { return group.RemarkName == remarkName })
}
// Search 根据自定义条件查找群组
func (g Groups) Search(limit int, searchFuncList ...func(group *Group) bool) (results Groups) {
return g.AsMembers().Search(limit, func(user *User) bool {
@ -316,10 +326,20 @@ func (g Groups) AsMembers() Members {
return members
}
// Sort 对群组进行排序
func (g Groups) Sort() Groups {
return g.AsMembers().Sort().Groups()
}
// Uniq 对群组进行去重
func (g Groups) Uniq() Groups {
return g.AsMembers().Uniq().Groups()
}
// Mp 公众号对象
type Mp struct{ *User }
func (m Mp) String() string {
func (m *Mp) String() string {
return fmt.Sprintf("<Mp:%s>", m.NickName)
}
@ -334,7 +354,7 @@ func (m Mps) Count() int {
// First 获取第一个
func (m Mps) First() *Mp {
if m.Count() > 0 {
return m[0]
return m.Sort()[0]
}
return nil
}
@ -342,7 +362,7 @@ func (m Mps) First() *Mp {
// Last 获取最后一个
func (m Mps) Last() *Mp {
if m.Count() > 0 {
return m[m.Count()-1]
return m.Sort()[m.Count()-1]
}
return nil
}
@ -369,6 +389,16 @@ func (m Mps) AsMembers() Members {
return members
}
// Sort 对公众号进行排序
func (m Mps) Sort() Mps {
return m.AsMembers().Sort().MPs()
}
// Uniq 对公众号进行去重
func (m Mps) Uniq() Mps {
return m.AsMembers().Uniq().MPs()
}
// SearchByUserName 根据用户名查找
func (m Mps) SearchByUserName(limit int, userName string) (results Mps) {
return m.Search(limit, func(group *Mp) bool { return group.UserName == userName })
@ -385,12 +415,12 @@ func (m *Mp) SendText(content string) (*SentMessage, error) {
}
// SendImage 发送图片消息给公众号
func (m *Mp) SendImage(file *os.File) (*SentMessage, error) {
func (m *Mp) SendImage(file io.Reader) (*SentMessage, error) {
return m.self.SendImageToMp(m, file)
}
// SendFile 发送文件消息给公众号
func (m *Mp) SendFile(file *os.File) (*SentMessage, error) {
func (m *Mp) SendFile(file io.Reader) (*SentMessage, error) {
return m.self.SendFileToMp(m, file)
}
@ -414,11 +444,6 @@ func (g Groups) GetByUsername(username string) *Group {
return g.SearchByUserName(1, username).First()
}
// GetByRemarkName 根据remarkName查询一个Group
func (g Groups) GetByRemarkName(remarkName string) *Group {
return g.SearchByRemarkName(1, remarkName).First()
}
// GetByNickName 根据nickname查询一个Group
func (g Groups) GetByNickName(nickname string) *Group {
return g.SearchByNickName(1, nickname).First()

25
serializer.go Normal file
View File

@ -0,0 +1,25 @@
package openwechat
import (
"encoding/json"
"io"
)
// Serializer is an interface for encoding and decoding data.
type Serializer interface {
Encode(writer io.Writer, v interface{}) error
Decode(reader io.Reader, v interface{}) error
}
// JsonSerializer is a serializer for json.
type JsonSerializer struct{}
// Encode encodes v to writer.
func (j JsonSerializer) Encode(writer io.Writer, v interface{}) error {
return json.NewEncoder(writer).Encode(v)
}
// Decode decodes data from reader to v.
func (j JsonSerializer) Decode(reader io.Reader, v interface{}) error {
return json.NewDecoder(reader).Decode(v)
}

View File

@ -60,7 +60,7 @@ func main() {
#### 普通登录
#### 扫码登录
上面的准备工作做完了,下面就可以登录,直接调用`Bot.Login`即可。
@ -68,6 +68,8 @@ func main() {
bot.Login()
```
`Login`方法会阻塞当前 goroutine直到登录成功或者失败。
登录会返回一个`error`,即登录失败的原因。
@ -82,12 +84,25 @@ bot.Login()
// 创建热存储容器对象
reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
defer reloadStorage.Close()
// 执行热登录
bot.HotLogin(reloadStorage)
```
`HotLogin`需要接受一个`热存储容器对象`来调用。`热存储容器`用来保存登录的会话信息,本质是一个接口类型
我们第一次进行热登录的时候,因为我们的`热存储容器`是空的,所以这时候会发生错误。
我们只需要在`HotLogin`增加一个参数,让它在失败后执行扫码登录即可
```go
bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption())
```
当扫码登录成功后,会将会话信息写入到`热存储容器`中,下次再执行热登录的时候就会从`热存储容器`中读取会话信息,直接登录成功。
```go
// 热登陆存储接口
type HotReloadStorage io.ReadWriter
@ -97,6 +112,46 @@ type HotReloadStorage io.ReadWriter
实现这个接口,实现你自己的存储方式。
#### 免扫码登录
目前热登录有一点缺点就是它的有效期很短(具体多久我也不知道)。
我们平常在pc上登录微信的时候通常只需要登录一次第二次就会在微信上有一个确认登录的按钮点击确认就会往手机上发送一个确认登录的请求这样就可以免扫码登录了。
openwechat也提供了这样的功能。
```go
bot.PushLogin(storage HotReloadStorage, opts ...openwechat.BotLoginOption) error
```
`PushLogin`需要传入一个`热存储容器`,和一些可选参数。
`HotReloadStorage` 跟上面一样,用来保存会话信息,必要参数。
`openwechat.BotLoginOption`是一个可选参数,用来设置一些额外的行为。
目前有下面几个可选参数:
```go
// NewSyncReloadDataLoginOption 登录成功后定时同步热存储容器数据
func NewSyncReloadDataLoginOption(duration time.Duration) BotLoginOption
// NewRetryLoginOption 登录失败后进行扫码登录
func NewRetryLoginOption() BotLoginOption
```
注意:如果是第一次登录,``PushLogin`` 一定会失败的,因为我们的`HotReloadStorage`里面没有会话信息,你需要设置失败会进行扫码登录。
```go
bot := openwechat.DefaultBot()
reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
defer reloadStorage.Close()
err = bot.PushLogin(reloadStorage, openwechat.NewRetryLoginOption())
```
这样当第一次登录失败的时候,会自动执行扫码登录。
扫码登录成功后,会自动保存会话信息到`HotReloadStorage`,下次登录就可以直接使用`PushLogin`了,就会往手机上发送确认登录的请求。
### 扫码回调
@ -106,13 +161,21 @@ type HotReloadStorage io.ReadWriter
通过对`bot`对象绑定扫码回调即可实现对应的功能。
```go
bot.ScanCallBack = func(body []byte) { fmt.Println(string(body)) }
bot.ScanCallBack = func(body openwechat.CheckLoginResponse) { fmt.Println(string(body)) }
```
用户扫码后body里面会携带用户的头像信息。
**注**:绑定扫码回调须在登录前执行。
`CheckLoginResponse` 是一个`[]byte`包装类型, 扫码成功后可以通过该类型获取用户的头像信息。
```go
type CheckLoginResponse []byte
func (c CheckLoginResponse) Avatar() (string, error)
```
### 登录回调
@ -120,13 +183,13 @@ bot.ScanCallBack = func(body []byte) { fmt.Println(string(body)) }
`bot`对象绑定登录
```go
bot.LoginCallBack = func(body []byte) {
bot.LoginCallBack = func(body openwechat.CheckLoginResponse) {
fmt.Println(string(body))
// to do your business
}
```
登录回调的参数就是当前客户端需要跳转的链接,可以不用关心它。
登录回调的参数就是当前客户端需要跳转的链接,用户可以不用关心它。(其实可以拿来做一些骚操作😈)
登录回调函数可以当做一个信号处理,表示当前扫码登录的用户已经确认登录。
@ -178,7 +241,7 @@ dispatcher.OnText(func(ctx *openwechat.MessageContext){
})
// 注册消息回调函数
bot.MessageHandler = openwechat.DispatchMessage(dispatcher)
bot.MessageHandler = dispatcher.AsMessageHandler()
```
`openwechat.DispatchMessage`会将消息转发给`dispatcher`对象处理
@ -262,5 +325,29 @@ self, err := bot.GetCurrentUser()
bot.Block()
```
该方法会一直阻塞,直到用户主动退出或者网络请求发生错误
该方法会一直阻塞,直到用户主动退出或者网络请求发生错误。
### 控制Bot存活
判断当前的`Bot`是否存活。
```go
func (b *Bot) Alive() bool
```
当返回为`true`则表示`Bot`存活。
如何控制`Bot`存活呢?
```go
ctx, cancel := context.WithCancel(context.Background())
bot := openwechat.DefaultBot(openwechat.WithContext(ctx))
```
`WithContext`接受一个`context.Context`对象,当`context`对象被取消时,`Bot`也会被取消。
当前我们也可以调用`bot.Logout`来主动退出当前的`Bot`,当`Bot`退出后,`bot.Alive()`会返回`false`

View File

@ -1,7 +1,5 @@
# 消息
### 接受消息
被动接受的消息对象,由微信服务器发出
@ -9,29 +7,25 @@
消息对象通过绑定在`bot`上的消息回调函数获取
```go
bot.MessageHandler = func(msg *openwechat.Message) {
if msg.IsText() && msg.Content == "ping" {
msg.ReplyText("pong")
}
bot.MessageHandler = func (msg *openwechat.Message) {
if msg.IsText() && msg.Content == "ping" {
msg.ReplyText("pong")
}
}
```
以下简写为`msg`
#### 消息内容
```go
msg.Content // 获取消息内容
msg.Content // 获取消息内容
```
通过访问`Content`属性可直接获取消息内容
由于消息分为很多种类型,它们都共用`Content`属性。一般当消息类型为文本类型的时候,我们才会去访问`Content`属性。
#### 消息类型判断
下面的判断消息类型的方法均返回`bool`
@ -117,13 +111,17 @@ msg.IsIsPaiYiPai() // 拍一拍消息
msg.IsTickled()
```
##### 判断是否拍了拍自己
```go
msg.IsTickledMe()
```
##### 判断是否有新人加入群聊
```go
msg.IsJoinGroup()
```
#### 获取消息的发送者
```go
@ -132,16 +130,12 @@ sender, err := msg.Sender()
如果是群聊消息,该方法返回的是群聊对象(需要自己将`User`转换为`Group`对象)
#### 获取消息的接受者
```go
receiver, err := msg.Receiver()
```
#### 获取消息在群里面的发送者
```go
@ -150,15 +144,17 @@ sender, err := msg.SenderInGroup()
获取群聊中具体发消息的用户,前提该消息必须来自群聊。
#### 是否由自己发送
```go
msg.IsSendBySelf()
```
#### 是否为拍一拍
```go
msg.IsTickled()
```
#### 消息是否由好友发出
@ -166,24 +162,18 @@ msg.IsSendBySelf()
msg.IsSendByFriend()
```
#### 消息是否由群聊发出
```go
msg.IsSendByGroup()
```
#### 回复文本消息
```go
msg.ReplyText("hello")
```
#### 回复图片消息
```go
@ -192,8 +182,6 @@ defer img.Close()
msg.ReplyImage(img)
```
#### 回复文件消息
```go
@ -202,14 +190,12 @@ defer file.Close()
msg.ReplyFile(file)
```
#### 获取消息里的其他信息
##### 名片消息
```go
card, err := msg. Card()
card, err := msg.Card()
```
该方法调用的前提为`msg.IsCard()`返回为`true`
@ -225,31 +211,29 @@ alias := card.Alias
```go
// 名片消息内容
type Card struct {
XMLName xml.Name `xml:"msg"`
ImageStatus int `xml:"imagestatus,attr"`
Scene int `xml:"scene,attr"`
Sex int `xml:"sex,attr"`
Certflag int `xml:"certflag,attr"`
BigHeadImgUrl string `xml:"bigheadimgurl,attr"`
SmallHeadImgUrl string `xml:"smallheadimgurl,attr"`
UserName string `xml:"username,attr"`
NickName string `xml:"nickname,attr"`
ShortPy string `xml:"shortpy,attr"`
Alias string `xml:"alias,attr"` // Note: 这个是名片用户的微信号
Province string `xml:"province,attr"`
City string `xml:"city,attr"`
Sign string `xml:"sign,attr"`
Certinfo string `xml:"certinfo,attr"`
BrandIconUrl string `xml:"brandIconUrl,attr"`
BrandHomeUr string `xml:"brandHomeUr,attr"`
BrandSubscriptConfigUrl string `xml:"brandSubscriptConfigUrl,attr"`
BrandFlags string `xml:"brandFlags,attr"`
RegionCode string `xml:"regionCode,attr"`
XMLName xml.Name `xml:"msg"`
ImageStatus int `xml:"imagestatus,attr"`
Scene int `xml:"scene,attr"`
Sex int `xml:"sex,attr"`
Certflag int `xml:"certflag,attr"`
BigHeadImgUrl string `xml:"bigheadimgurl,attr"`
SmallHeadImgUrl string `xml:"smallheadimgurl,attr"`
UserName string `xml:"username,attr"`
NickName string `xml:"nickname,attr"`
ShortPy string `xml:"shortpy,attr"`
Alias string `xml:"alias,attr"` // Note: 这个是名片用户的微信号
Province string `xml:"province,attr"`
City string `xml:"city,attr"`
Sign string `xml:"sign,attr"`
Certinfo string `xml:"certinfo,attr"`
BrandIconUrl string `xml:"brandIconUrl,attr"`
BrandHomeUr string `xml:"brandHomeUr,attr"`
BrandSubscriptConfigUrl string `xml:"brandSubscriptConfigUrl,attr"`
BrandFlags string `xml:"brandFlags,attr"`
RegionCode string `xml:"regionCode,attr"`
}
```
##### 获取已撤回的消息
```go
@ -262,19 +246,17 @@ revokeMsg, err := msg.RevokeMsg()
```go
type RevokeMsg struct {
SysMsg xml.Name `xml:"sysmsg"`
Type string `xml:"type,attr"`
RevokeMsg struct {
OldMsgId int64 `xml:"oldmsgid"`
MsgId int64 `xml:"msgid"`
Session string `xml:"session"`
ReplaceMsg string `xml:"replacemsg"`
} `xml:"revokemsg"`
SysMsg xml.Name `xml:"sysmsg"`
Type string `xml:"type,attr"`
RevokeMsg struct {
OldMsgId int64 `xml:"oldmsgid"`
MsgId int64 `xml:"msgid"`
Session string `xml:"session"`
ReplaceMsg string `xml:"replacemsg"`
} `xml:"revokemsg"`
}
```
#### 同意好友请求
```go
@ -286,8 +268,6 @@ friend, err := msg.Agree()
该方法调用成功的前提是`msg.IsFriendAdd()`返回为`true`
#### 设置为已读
```go
@ -296,10 +276,6 @@ msg.AsRead()
该当前消息设置为已读
#### 设置消息的上下文
用于多个消息处理函数之间的通信,并且是协程安全的。
@ -316,10 +292,6 @@ msg.Set("hello", "world")
value, exist := msg.Get("hello")
```
### 已发送消息
已发送消息指当前用户发送出去的消息
@ -334,8 +306,6 @@ sentMsg, err := msg.ReplyText("hello") // 通过回复消息获取
// and so on
```
#### 撤回消息
撤回刚刚发送的消息撤回消息的有效时间为2分钟超过了这个时间则无法撤回
@ -344,16 +314,12 @@ sentMsg, err := msg.ReplyText("hello") // 通过回复消息获取
sentMsg.Revoke()
```
#### 判断是否可以撤回
```go
sentMsg.CanRevoke()
```
#### 转发给好友
```go
@ -362,8 +328,6 @@ sentMsg.ForwardToFriends(friend1, friend2)
将刚发送的消息转发给好友
#### 转发给群聊
```go
@ -372,10 +336,6 @@ sentMsg.ForwardToGroups(group1, group2)
将刚发送的消息转发给群聊
### Emoji表情
openwechat提供了微信全套`emoji`表情的支持
@ -387,7 +347,7 @@ emoji表情可以通过发送`Text`类型的函数发送
```go
firend.SendText(openwechat.Emoji.Doge) // 发送狗头表情
firend.SendText(openwechat.Emoji.Doge) // 发送狗头表情
msg.ReplyText(openwechat.Emoji.Awesome) // 发送666的表情
```

View File

@ -400,10 +400,10 @@ func (f Friends) SendText(text string, delay ...time.Duration) error
#### 群发图片
```go
func (f Friends) SendImage(file *os.File, delay ...time.Duration) error
func (f Friends) SendImage(file io.Reader, delay ...time.Duration) error
```
* `file``os.file`类型,即发送图片的文件指针
* `file``io.Reader`类型。
* `delay`每次发送消息的间隔发送消息过快可能会被wx检测到最好加上间隔时间
@ -411,10 +411,10 @@ func (f Friends) SendImage(file *os.File, delay ...time.Duration) error
#### 群发文件
```go
func (f Friends) SendFile(file *os.File, delay ...time.Duration) error
func (f Friends) SendFile(file io.Reader, delay ...time.Duration) error
```
* `file``os.file`类型,即发送文件的文件指针
* `file``io.Reader`类型。
* `delay`每次发送消息的间隔发送消息过快可能会被wx检测到最好加上间隔时间
@ -545,10 +545,10 @@ func (g Groups) SendText(text string, delay ...time.Duration) error
#### 群发图片
```go
func (g Groups) SendImage(file *os.File, delay ...time.Duration) error
func (g Groups) SendImage(file io.Reader, delay ...time.Duration) error
```
* `file``os.file`类型,即发送文件的文件指针
* `file``io.Reader`类型。
* `delay`每次发送消息的间隔发送消息过快可能会被wx检测到最好加上间隔时间
@ -556,10 +556,10 @@ func (g Groups) SendImage(file *os.File, delay ...time.Duration) error
#### 群发文件
```go
func (g Groups) SendFile(file *os.File, delay ...time.Duration) error
func (g Groups) SendFile(file io.Reader, delay ...time.Duration) error
```
* `file``os.file`类型,即发送文件的文件指针
* `file``io.Reader`类型。
* `delay`每次发送消息的间隔发送消息过快可能会被wx检测到最好加上间隔时间

View File

@ -58,6 +58,8 @@ func _() {
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[ticketError - -14]
_ = x[logicError - -2]
_ = x[sysError - -1]
_ = x[paramError-1]
_ = x[failedLoginWarn-1100]
_ = x[failedLoginCheck-1101]
@ -68,31 +70,36 @@ func _() {
const (
_Ret_name_0 = "ticket error"
_Ret_name_1 = "param error"
_Ret_name_2 = "failed login warnfailed login Checkcookie invalid"
_Ret_name_3 = "login environmental abnormality"
_Ret_name_4 = "operate too often"
_Ret_name_1 = "logic errorsys error"
_Ret_name_2 = "param error"
_Ret_name_3 = "failed login warnfailed login checkcookie invalid"
_Ret_name_4 = "login environmental abnormality"
_Ret_name_5 = "operate too often"
)
var (
_Ret_index_2 = [...]uint8{0, 17, 35, 49}
_Ret_index_1 = [...]uint8{0, 11, 20}
_Ret_index_3 = [...]uint8{0, 17, 35, 49}
)
func (r Ret) String() string {
func (i Ret) String() string {
switch {
case r == -14:
case i == -14:
return _Ret_name_0
case r == 1:
return _Ret_name_1
case 1100 <= r && r <= 1102:
r -= 1100
return _Ret_name_2[_Ret_index_2[r]:_Ret_index_2[r+1]]
case r == 1203:
return _Ret_name_3
case r == 1205:
case -2 <= i && i <= -1:
i -= -2
return _Ret_name_1[_Ret_index_1[i]:_Ret_index_1[i+1]]
case i == 1:
return _Ret_name_2
case 1100 <= i && i <= 1102:
i -= 1100
return _Ret_name_3[_Ret_index_3[i]:_Ret_index_3[i+1]]
case i == 1203:
return _Ret_name_4
case i == 1205:
return _Ret_name_5
default:
return "Ret(" + strconv.FormatInt(int64(r), 10) + ")"
return "Ret(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
func _() {

View File

@ -3,6 +3,8 @@ package openwechat
import (
"io"
"os"
"sync"
"time"
)
// Storage 身份信息, 维持整个登陆的Session会话
@ -23,14 +25,17 @@ type HotReloadStorageItem struct {
// HotReloadStorage 热登陆存储接口
type HotReloadStorage io.ReadWriter
// jsonFileHotReloadStorage 实现HotReloadStorage接口
// 默认json文件的形式存储
type jsonFileHotReloadStorage struct {
// fileHotReloadStorage 实现HotReloadStorage接口
// 以文件的形式存储
type fileHotReloadStorage struct {
filename string
file *os.File
lock sync.Mutex
}
func (j *jsonFileHotReloadStorage) Read(p []byte) (n int, err error) {
func (j *fileHotReloadStorage) Read(p []byte) (n int, err error) {
j.lock.Lock()
defer j.lock.Unlock()
if j.file == nil {
j.file, err = os.OpenFile(j.filename, os.O_RDWR, 0600)
if os.IsNotExist(err) {
@ -43,35 +48,74 @@ func (j *jsonFileHotReloadStorage) Read(p []byte) (n int, err error) {
return j.file.Read(p)
}
func (j *jsonFileHotReloadStorage) Write(p []byte) (n int, err error) {
func (j *fileHotReloadStorage) Write(p []byte) (n int, err error) {
j.lock.Lock()
defer j.lock.Unlock()
if j.file == nil {
j.file, err = os.Create(j.filename)
if err != nil {
return 0, err
}
}
// 为什么这里要对文件进行Truncate操作呢?
// 这是为了方便每次Dump的时候对文件进行重新写入, 而不是追加
// json序列化写入只会调用一次Write方法, 所以不要把这个方法当成io.Writer的Write方法
// reset offset and truncate file
if _, err = j.file.Seek(0, io.SeekStart); err != nil {
return
}
if err = j.file.Truncate(0); err != nil {
return
}
// json decode only write once
return j.file.Write(p)
}
func (j *jsonFileHotReloadStorage) Close() error {
func (j *fileHotReloadStorage) Close() error {
j.lock.Lock()
defer j.lock.Unlock()
if j.file == nil {
return nil
}
return j.file.Close()
}
// NewJsonFileHotReloadStorage 创建JsonFileHotReloadStorage
// Deprecated: use NewFileHotReloadStorage instead
// 不再单纯以json的格式存储支持了用户自定义序列化方式
func NewJsonFileHotReloadStorage(filename string) io.ReadWriteCloser {
return &jsonFileHotReloadStorage{filename: filename}
return NewFileHotReloadStorage(filename)
}
var _ HotReloadStorage = (*jsonFileHotReloadStorage)(nil)
// NewFileHotReloadStorage implements HotReloadStorage
func NewFileHotReloadStorage(filename string) io.ReadWriteCloser {
return &fileHotReloadStorage{filename: filename}
}
var _ HotReloadStorage = (*fileHotReloadStorage)(nil)
type HotReloadStorageSyncer struct {
duration time.Duration
bot *Bot
}
// Sync 定时同步数据到登陆存储中
func (h *HotReloadStorageSyncer) Sync() error {
if h.duration <= 0 {
return nil
}
// 定时器
ticker := time.NewTicker(h.duration)
for {
select {
case <-ticker.C:
// 每隔一段时间, 将数据同步到storage中
if err := h.bot.DumpHotReloadStorage(); err != nil {
return err
}
case <-h.bot.Context().Done():
// 当Bot关闭的时候, 退出循环
return nil
}
}
}
func NewHotReloadStorageSyncer(bot *Bot, duration time.Duration) *HotReloadStorageSyncer {
return &HotReloadStorageSyncer{duration: duration, bot: bot}
}

44
sync_check.go Normal file
View File

@ -0,0 +1,44 @@
package openwechat
import (
"errors"
"strconv"
)
type Selector string
const (
SelectorNormal Selector = "0" // 正常
SelectorNewMsg Selector = "2" // 有新消息
SelectorModContact Selector = "4" // 联系人信息变更
SelectorAddOrDelContact Selector = "6" // 添加或删除联系人
SelectorModChatRoom Selector = "7" // 进入或退出聊天室
)
type SyncCheckResponse struct {
RetCode string
Selector Selector
}
func (s SyncCheckResponse) Success() bool {
return s.RetCode == "0"
}
func (s SyncCheckResponse) NorMal() bool {
return s.Success() && s.Selector == SelectorNormal
}
func (s SyncCheckResponse) HasNewMessage() bool {
return s.Success() && s.Selector == SelectorNewMsg
}
func (s SyncCheckResponse) Err() error {
if s.Success() {
return nil
}
i, err := strconv.Atoi(s.RetCode)
if err != nil {
return errors.New("sync check unknown error")
}
return Ret(i)
}

171
user.go
View File

@ -3,10 +3,13 @@ package openwechat
import (
"errors"
"fmt"
"html"
"io"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
@ -55,14 +58,14 @@ type User struct {
// implement fmt.Stringer
func (u *User) String() string {
format := "User"
if u.IsFriend() {
if u.IsSelf() {
format = "Self"
} else if u.IsFriend() {
format = "Friend"
} else if u.IsGroup() {
format = "Group"
} else if u.IsMP() {
format = "MP"
} else if u.IsSelf() {
format = "Self"
}
return fmt.Sprintf("<%s:%s>", format, u.NickName)
}
@ -130,16 +133,40 @@ func (u *User) IsFriend() bool {
return !u.IsGroup() && strings.HasPrefix(u.UserName, "@") && u.VerifyFlag == 0
}
// AsFriend 将当前用户转换为好友类型
func (u *User) AsFriend() (*Friend, bool) {
if u.IsFriend() {
return &Friend{User: u}, true
}
return nil, false
}
// IsGroup 判断是否为群组
func (u *User) IsGroup() bool {
return strings.HasPrefix(u.UserName, "@@") && u.VerifyFlag == 0
}
// AsGroup 将当前用户转换为群组类型
func (u *User) AsGroup() (*Group, bool) {
if u.IsGroup() {
return &Group{User: u}, true
}
return nil, false
}
// IsMP 判断是否为公众号
func (u *User) IsMP() bool {
return u.VerifyFlag == 8 || u.VerifyFlag == 24 || u.VerifyFlag == 136
}
// AsMP 将当前用户转换为公众号类型
func (u *User) AsMP() (*Mp, bool) {
if u.IsMP() {
return &Mp{User: u}, true
}
return nil, false
}
// Pin 将联系人置顶
func (u *User) Pin() error {
req := u.self.bot.Storage.Request
@ -190,6 +217,25 @@ func (u *User) IsSelf() bool {
return u.UserName == u.Self().UserName
}
// OrderSymbol 获取用户的排序标识
func (u *User) OrderSymbol() string {
var symbol string
if u.RemarkPYQuanPin != "" {
symbol = u.RemarkPYQuanPin
} else if u.PYQuanPin != "" {
symbol = u.PYQuanPin
} else {
symbol = u.NickName
}
symbol = html.UnescapeString(symbol)
symbol = strings.ToUpper(symbol)
symbol = regexp.MustCompile("/\\W/ig").ReplaceAllString(symbol, "")
if len(symbol) > 0 && symbol[0] < 'A' {
return "~"
}
return symbol
}
// 格式化emoji表情
func (u *User) formatEmoji() {
u.NickName = FormatEmoji(u.NickName)
@ -217,6 +263,7 @@ func (s *Self) Members(update ...bool) (Members, error) {
return nil, err
}
}
s.members.Sort()
return s.members, nil
}
@ -241,13 +288,18 @@ func (s *Self) FileHelper() *Friend {
}
return s.fileHelper
}
func (s *Self) ChkFrdGrpMpNil() bool {
return s.friends == nil && s.groups == nil && s.mps == nil
}
// Friends 获取所有的好友
func (s *Self) Friends(update ...bool) (Friends, error) {
if s.friends == nil || (len(update) > 0 && update[0]) {
if (len(update) > 0 && update[0]) || s.ChkFrdGrpMpNil() {
if _, err := s.Members(true); err != nil {
return nil, err
}
}
if s.friends == nil || (len(update) > 0 && update[0]) {
s.friends = s.members.Friends()
}
return s.friends, nil
@ -255,10 +307,14 @@ func (s *Self) Friends(update ...bool) (Friends, error) {
// Groups 获取所有的群组
func (s *Self) Groups(update ...bool) (Groups, error) {
if s.groups == nil || (len(update) > 0 && update[0]) {
if (len(update) > 0 && update[0]) || s.ChkFrdGrpMpNil() {
if _, err := s.Members(true); err != nil {
return nil, err
}
}
if s.groups == nil || (len(update) > 0 && update[0]) {
s.groups = s.members.Groups()
}
return s.groups, nil
@ -266,10 +322,12 @@ func (s *Self) Groups(update ...bool) (Groups, error) {
// Mps 获取所有的公众号
func (s *Self) Mps(update ...bool) (Mps, error) {
if s.mps == nil || (len(update) > 0 && update[0]) {
if (len(update) > 0 && update[0]) || s.ChkFrdGrpMpNil() {
if _, err := s.Members(true); err != nil {
return nil, err
}
}
if s.mps == nil || (len(update) > 0 && update[0]) {
s.mps = s.members.MPs()
}
return s.mps, nil
@ -295,21 +353,21 @@ func (s *Self) sendTextToUser(user *User, text string) (*SentMessage, error) {
return s.sendMessageWrapper(sentMessage, err)
}
func (s *Self) sendImageToUser(user *User, file *os.File) (*SentMessage, error) {
func (s *Self) sendImageToUser(user *User, file io.Reader) (*SentMessage, error) {
req := s.bot.Storage.Request
info := s.bot.Storage.LoginInfo
sentMessage, err := s.bot.Caller.WebWxSendImageMsg(file, req, info, s.UserName, user.UserName)
return s.sendMessageWrapper(sentMessage, err)
}
func (s *Self) sendVideoToUser(user *User, file *os.File) (*SentMessage, error) {
func (s *Self) sendVideoToUser(user *User, file io.Reader) (*SentMessage, error) {
req := s.bot.Storage.Request
info := s.bot.Storage.LoginInfo
sentMessage, err := s.bot.Caller.WebWxSendVideoMsg(file, req, info, s.UserName, user.UserName)
return s.sendMessageWrapper(sentMessage, err)
}
func (s *Self) sendFileToUser(user *User, file *os.File) (*SentMessage, error) {
func (s *Self) sendFileToUser(user *User, file io.Reader) (*SentMessage, error) {
req := s.bot.Storage.Request
info := s.bot.Storage.LoginInfo
sentMessage, err := s.bot.Caller.WebWxSendFile(file, req, info, s.UserName, user.UserName)
@ -322,17 +380,17 @@ func (s *Self) SendTextToFriend(friend *Friend, text string) (*SentMessage, erro
}
// SendImageToFriend 发送图片消息给好友
func (s *Self) SendImageToFriend(friend *Friend, file *os.File) (*SentMessage, error) {
func (s *Self) SendImageToFriend(friend *Friend, file io.Reader) (*SentMessage, error) {
return s.sendImageToUser(friend.User, file)
}
// SendVideoToFriend 发送视频给好友
func (s *Self) SendVideoToFriend(friend *Friend, file *os.File) (*SentMessage, error) {
func (s *Self) SendVideoToFriend(friend *Friend, file io.Reader) (*SentMessage, error) {
return s.sendVideoToUser(friend.User, file)
}
// SendFileToFriend 发送文件给好友
func (s *Self) SendFileToFriend(friend *Friend, file *os.File) (*SentMessage, error) {
func (s *Self) SendFileToFriend(friend *Friend, file io.Reader) (*SentMessage, error) {
return s.sendFileToUser(friend.User, file)
}
@ -348,6 +406,7 @@ func (s *Self) SetRemarkNameToFriend(friend *Friend, remarkName string) error {
// topic 群昵称,可以传递字符串
// friends 群员,最少为2个加上自己3个,三人才能成群
func (s *Self) CreateGroup(topic string, friends ...*Friend) (*Group, error) {
friends = Friends(friends).Uniq()
if len(friends) < 2 {
return nil, errors.New("a group must be at least 2 members")
}
@ -368,6 +427,7 @@ func (s *Self) AddFriendsIntoGroup(group *Group, friends ...*Friend) error {
if len(friends) == 0 {
return nil
}
friends = Friends(friends).Uniq()
// 获取群的所有的群员
groupMembers, err := group.Members()
if err != nil {
@ -420,6 +480,7 @@ func (s *Self) RemoveMemberFromGroup(group *Group, members Members) error {
// AddFriendIntoManyGroups 拉好友进多个群聊
// AddFriendIntoGroups, 名字和上面的有点像
func (s *Self) AddFriendIntoManyGroups(friend *Friend, groups ...*Group) error {
groups = Groups(groups).Uniq()
for _, group := range groups {
if err := s.AddFriendsIntoGroup(group, friend); err != nil {
return err
@ -441,17 +502,17 @@ func (s *Self) SendTextToGroup(group *Group, text string) (*SentMessage, error)
}
// SendImageToGroup 发送图片消息给群组
func (s *Self) SendImageToGroup(group *Group, file *os.File) (*SentMessage, error) {
func (s *Self) SendImageToGroup(group *Group, file io.Reader) (*SentMessage, error) {
return s.sendImageToUser(group.User, file)
}
// SendVideoToGroup 发送视频给群组
func (s *Self) SendVideoToGroup(group *Group, file *os.File) (*SentMessage, error) {
func (s *Self) SendVideoToGroup(group *Group, file io.Reader) (*SentMessage, error) {
return s.sendVideoToUser(group.User, file)
}
// SendFileToGroup 发送文件给群组
func (s *Self) SendFileToGroup(group *Group, file *os.File) (*SentMessage, error) {
func (s *Self) SendFileToGroup(group *Group, file io.Reader) (*SentMessage, error) {
return s.sendFileToUser(group.User, file)
}
@ -530,7 +591,7 @@ func (s *Self) sendTextToMembers(text string, delay time.Duration, members ...*U
}
// sendImageToMembers 发送图片消息给群组或者好友
func (s *Self) sendImageToMembers(img *os.File, delay time.Duration, members ...*User) error {
func (s *Self) sendImageToMembers(img io.Reader, delay time.Duration, members ...*User) error {
if len(members) == 0 {
return nil
}
@ -544,7 +605,7 @@ func (s *Self) sendImageToMembers(img *os.File, delay time.Duration, members ...
}
// sendVideoToMembers 发送视频消息给群组或者好友
func (s *Self) sendVideoToMembers(video *os.File, delay time.Duration, members ...*User) error {
func (s *Self) sendVideoToMembers(video io.Reader, delay time.Duration, members ...*User) error {
if len(members) == 0 {
return nil
}
@ -557,7 +618,7 @@ func (s *Self) sendVideoToMembers(video *os.File, delay time.Duration, members .
return s.forwardMessage(msg, delay, members[1:]...)
}
func (s *Self) sendFileToMembers(file *os.File, delay time.Duration, members ...*User) error {
func (s *Self) sendFileToMembers(file io.Reader, delay time.Duration, members ...*User) error {
if len(members) == 0 {
return nil
}
@ -577,19 +638,19 @@ func (s *Self) SendTextToFriends(text string, delay time.Duration, friends ...*F
}
// SendImageToFriends 发送图片消息给好友
func (s *Self) SendImageToFriends(img *os.File, delay time.Duration, friends ...*Friend) error {
func (s *Self) SendImageToFriends(img io.Reader, delay time.Duration, friends ...*Friend) error {
members := Friends(friends).AsMembers()
return s.sendImageToMembers(img, delay, members...)
}
// SendFileToFriends 发送文件给好友
func (s *Self) SendFileToFriends(file *os.File, delay time.Duration, friends ...*Friend) error {
func (s *Self) SendFileToFriends(file io.Reader, delay time.Duration, friends ...*Friend) error {
members := Friends(friends).AsMembers()
return s.sendFileToMembers(file, delay, members...)
}
// SendVideoToFriends 发送视频给好友
func (s *Self) SendVideoToFriends(video *os.File, delay time.Duration, friends ...*Friend) error {
func (s *Self) SendVideoToFriends(video io.Reader, delay time.Duration, friends ...*Friend) error {
members := Friends(friends).AsMembers()
return s.sendVideoToMembers(video, delay, members...)
}
@ -601,26 +662,68 @@ func (s *Self) SendTextToGroups(text string, delay time.Duration, groups ...*Gro
}
// SendImageToGroups 发送图片消息给群组
func (s *Self) SendImageToGroups(img *os.File, delay time.Duration, groups ...*Group) error {
func (s *Self) SendImageToGroups(img io.Reader, delay time.Duration, groups ...*Group) error {
members := Groups(groups).AsMembers()
return s.sendImageToMembers(img, delay, members...)
}
// SendFileToGroups 发送文件给群组
func (s *Self) SendFileToGroups(file *os.File, delay time.Duration, groups ...*Group) error {
func (s *Self) SendFileToGroups(file io.Reader, delay time.Duration, groups ...*Group) error {
members := Groups(groups).AsMembers()
return s.sendFileToMembers(file, delay, members...)
}
// SendVideoToGroups 发送视频给群组
func (s *Self) SendVideoToGroups(video *os.File, delay time.Duration, groups ...*Group) error {
func (s *Self) SendVideoToGroups(video io.Reader, delay time.Duration, groups ...*Group) error {
members := Groups(groups).AsMembers()
return s.sendVideoToMembers(video, delay, members...)
}
// ContactList 获取最近的联系人列表
func (s *Self) ContactList() Members {
return s.Bot().Storage.Response.ContactList
}
// MPSubscribeList 获取部分公众号文章列表
func (s *Self) MPSubscribeList() []*MPSubscribeMsg {
return s.Bot().Storage.Response.MPSubscribeMsgList
}
// Members 抽象的用户组
type Members []*User
func (m Members) Len() int {
return len(m)
}
// Less 按照微信的规则排序
func (m Members) Less(i, j int) bool {
return m[i].OrderSymbol() < m[j].OrderSymbol()
}
func (m Members) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
// Uniq Members 去重
func (m Members) Uniq() Members {
var uniqMembers = make(map[string]*User)
for _, member := range m {
uniqMembers[member.UserName] = member
}
var members Members
for _, member := range uniqMembers {
members = append(members, member)
}
return members
}
// Sort 对联系人进行排序
func (m Members) Sort() Members {
sort.Sort(m)
return m
}
// Count 统计数量
func (m Members) Count() int {
return len(m)
@ -695,8 +798,8 @@ func (m Members) GetByNickName(nickname string) (*User, bool) {
func (m Members) Friends() Friends {
friends := make(Friends, 0)
for _, mb := range m {
if mb.IsFriend() {
friend := &Friend{mb}
friend, ok := mb.AsFriend()
if ok {
friends = append(friends, friend)
}
}
@ -706,8 +809,8 @@ func (m Members) Friends() Friends {
func (m Members) Groups() Groups {
groups := make(Groups, 0)
for _, mb := range m {
if mb.IsGroup() {
group := &Group{mb}
group, ok := mb.AsGroup()
if ok {
groups = append(groups, group)
}
}
@ -717,8 +820,8 @@ func (m Members) Groups() Groups {
func (m Members) MPs() Mps {
mps := make(Mps, 0)
for _, mb := range m {
if mb.IsMP() {
mp := &Mp{mb}
mp, ok := mb.AsMP()
if ok {
mps = append(mps, mp)
}
}
@ -789,7 +892,7 @@ func newFriend(username string, self *Self) *Friend {
// NewFriendHelper 创建一个文件传输助手
// 文件传输助手的微信身份标识符永远是filehelper
func NewFriendHelper(self *Self) *Friend {
return newFriend("filehelper", self)
return newFriend(FileHelper, self)
}
// SendTextToMp 发送文本消息给公众号
@ -798,17 +901,17 @@ func (s *Self) SendTextToMp(mp *Mp, text string) (*SentMessage, error) {
}
// SendImageToMp 发送图片消息给公众号
func (s *Self) SendImageToMp(mp *Mp, file *os.File) (*SentMessage, error) {
func (s *Self) SendImageToMp(mp *Mp, file io.Reader) (*SentMessage, error) {
return s.sendImageToUser(mp.User, file)
}
// SendFileToMp 发送文件给公众号
func (s *Self) SendFileToMp(mp *Mp, file *os.File) (*SentMessage, error) {
func (s *Self) SendFileToMp(mp *Mp, file io.Reader) (*SentMessage, error) {
return s.sendFileToUser(mp.User, file)
}
// SendVideoToMp 发送视频消息给公众号
func (s *Self) SendVideoToMp(mp *Mp, file *os.File) (*SentMessage, error) {
func (s *Self) SendVideoToMp(mp *Mp, file io.Reader) (*SentMessage, error) {
return s.sendVideoToUser(mp.User, file)
}