Compare commits

..

No commits in common. "master" and "v1.3.6" have entirely different histories.

19 changed files with 221 additions and 362 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:,利用微信号完成一些功能的定制化开发⭐
* 模块简单易用,易于扩展
* 支持定制化开发,如日志记录,自动回复
* 突破登录限制📣
* 突破网页版登录限制📣
* 无需重复扫码登录
* 支持多个微信号同时登陆
@ -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">

45
bot.go
View File

@ -2,6 +2,7 @@ package openwechat
import (
"context"
"encoding/json"
"errors"
"io"
"log"
@ -19,17 +20,15 @@ type Bot struct {
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
}
@ -51,7 +50,6 @@ 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
}
@ -85,7 +83,7 @@ func (b *Bot) login(login BotLogin) (err error) {
// Login 用户登录
func (b *Bot) Login() error {
scanLogin := &SacnLogin{UUID: b.loginUUID}
scanLogin := &SacnLogin{}
return b.login(scanLogin)
}
@ -169,10 +167,9 @@ 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
// 通知手机客户端已经登录
@ -223,8 +220,8 @@ func (b *Bot) syncCheck() error {
if !resp.Success() {
return resp.Err()
}
switch resp.Selector {
case SelectorNewMsg:
// 如果Selector不为0则获取消息
if !resp.NorMal() {
messages, err := b.syncMessage()
if err != nil {
return err
@ -237,12 +234,8 @@ func (b *Bot) syncCheck() error {
// 默认同步调用
// 如果异步调用则需自行处理
// 如配合 openwechat.MessageMatchDispatcher 使用
// NOTE: 请确保 MessageHandler 不会阻塞,否则会导致收不到后续的消息
b.MessageHandler(message)
}
case SelectorModContact:
case SelectorAddOrDelContact:
case SelectorModChatRoom:
}
}
return err
@ -301,7 +294,7 @@ func (b *Bot) DumpTo(writer io.Writer) error {
WechatDomain: b.Caller.Client.Domain,
UUID: b.uuid,
}
return b.Serializer.Encode(writer, item)
return json.NewEncoder(writer).Encode(item)
}
// IsHot returns true if is hot login otherwise false
@ -309,20 +302,11 @@ func (b *Bot) IsHot() bool {
return b.hotReloadStorage != nil
}
// UUID returns current UUID of bot
// 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
@ -333,7 +317,8 @@ func (b *Bot) reload() error {
return errors.New("hotReloadStorage is nil")
}
var item HotReloadStorageItem
if err := b.Serializer.Decode(b.hotReloadStorage, &item); err != nil {
err := json.NewDecoder(b.hotReloadStorage).Decode(&item)
if err != nil {
return err
}
b.Caller.Client.SetCookieJar(item.Jar)
@ -351,13 +336,7 @@ func NewBot(c context.Context) *Bot {
// 默认行为为网页版微信模式
caller.Client.SetMode(normal)
ctx, cancel := context.WithCancel(c)
return &Bot{
Caller: caller,
Storage: &Storage{},
Serializer: &JsonSerializer{},
context: ctx,
cancel: cancel,
}
return &Bot{Caller: caller, Storage: &Storage{}, context: ctx, cancel: cancel}
}
// DefaultBot 默认的Bot的构造方法,

View File

@ -1,7 +1,6 @@
package openwechat
import (
"context"
"time"
)
@ -133,16 +132,16 @@ func NewSyncReloadDataLoginOption(duration time.Duration) BotLoginOption {
return &SyncReloadDataLoginOption{SyncLoopDuration: duration}
}
// withModeOption 指定使用哪种客户端模式
type withModeOption struct {
// WithModeOption 指定使用哪种客户端模式
type WithModeOption struct {
mode Mode
}
// Prepare 实现了 BotLoginOption 接口
func (w withModeOption) Prepare(b *Bot) { b.Caller.Client.SetMode(w.mode) }
func (w WithModeOption) Prepare(b *Bot) { b.Caller.Client.SetMode(w.mode) }
func withMode(mode Mode) BotPreparer {
return withModeOption{mode: mode}
return WithModeOption{mode: mode}
}
// btw, 这两个变量已经变了4回了, 但是为了兼容以前的代码, 还是得想着法儿让用户无感知的更新
@ -154,19 +153,6 @@ var (
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
)
@ -177,22 +163,14 @@ type BotLogin interface {
}
// SacnLogin 扫码登录
type SacnLogin struct {
UUID *string
}
type SacnLogin struct{}
// Login 实现了 BotLogin 接口
func (s *SacnLogin) Login(bot *Bot) error {
var uuid string
if s.UUID == nil {
var err error
uuid, err = bot.Caller.GetLoginUUID()
uuid, err := bot.Caller.GetLoginUUID()
if err != nil {
return err
}
} else {
uuid = *s.UUID
}
return s.checkLogin(bot, uuid)
}

View File

@ -128,30 +128,4 @@ 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

@ -501,27 +501,30 @@ func (p *MessageResponseParser) SentMessage(msg *SendMessage) (*SentMessage, err
}
func readerToFile(reader io.Reader) (file *os.File, cb func(), err error) {
var ok bool
if file, ok = reader.(*os.File); ok {
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()
_ = file.Close()
_ = os.Remove(file.Name())
return nil, nil, err
}
_, err = file.Seek(0, io.SeekStart)
if err = file.Close(); err != nil {
_ = os.Remove(file.Name())
return nil, nil, err
}
file, err = os.Open(file.Name())
if err != nil {
cb()
_ = os.Remove(file.Name())
return nil, nil, err
}
return file, cb, nil
return file, func() {
_ = file.Close()
_ = os.Remove(file.Name())
}, nil
}

View File

@ -314,8 +314,6 @@ 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)
@ -360,11 +358,7 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
path.RawQuery = params.Encode()
cookies := c.Jar().Cookies(path)
webWxDataTicket, err := getWebWxDataTicket(cookies)
if err != nil {
return nil, err
}
webWxDataTicket := getWebWxDataTicket(cookies)
uploadMediaRequest := map[string]interface{}{
"UploadType": 2,
@ -416,17 +410,16 @@ 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)
}
formBuffer.Reset()
var formBuffer = bytes.NewBuffer(nil)
writer := multipart.NewWriter(formBuffer)
@ -441,33 +434,34 @@ func (c *Client) WebWxUploadMediaByChunk(file *os.File, request *BaseRequest, in
}
w, err := writer.CreateFormFile("filename", file.Name())
if err != nil {
return nil, err
}
n, err := file.Read(chunkBuff)
chunkData := make([]byte, chunkSize)
n, err := file.Read(chunkData)
if err != nil && err != io.EOF {
return nil, err
}
if _, err = w.Write(chunkBuff[:n]); err != nil {
if _, err = w.Write(chunkData[: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}
@ -597,18 +591,13 @@ 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", webWxDataTicket)
params.Add("webwx_data_ticket", getWebWxDataTicket(c.Jar().Cookies(path)))
path.RawQuery = params.Encode()
req, _ := http.NewRequest(http.MethodGet, path.String(), nil)
req.Header.Add("Referer", c.Domain.BaseHost()+"/")
@ -629,14 +618,6 @@ 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")
@ -658,29 +639,6 @@ 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

@ -32,9 +32,6 @@ var (
// 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

@ -57,9 +57,9 @@ type WebInitResponse struct {
SKey string
BaseResponse BaseResponse
SyncKey SyncKey
User *User
MPSubscribeMsgList []*MPSubscribeMsg
ContactList Members
User User
MPSubscribeMsgList []MPSubscribeMsg
ContactList []User
}
// MPSubscribeMsg 公众号的订阅信息
@ -68,14 +68,12 @@ type MPSubscribeMsg struct {
Time int64
UserName string
NickName string
MPArticleList []*MPArticle
}
type MPArticle struct {
MPArticleList []struct {
Title string
Cover string
Digest string
Url string
}
}
type UserDetailItem struct {

View File

@ -9,7 +9,6 @@ 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
@ -58,24 +57,3 @@ 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

@ -791,7 +791,7 @@ func (m *Message) IsAt() bool {
// IsPaiYiPai 判断消息是否为拍一拍
// 不要问我为什么取名为PaiYiPai因为我也不知道取啥名字好
func (m *Message) IsPaiYiPai() bool {
return m.IsTickled()
return m.IsSystem() && strings.Contains(m.Content, "拍了拍")
}
// IsJoinGroup 判断是否有人加入了群聊
@ -801,12 +801,7 @@ func (m *Message) IsJoinGroup() bool {
// IsTickled 判断消息是否为拍一拍
func (m *Message) IsTickled() bool {
return m.IsSystem() && strings.Contains(m.Content, "拍了拍")
}
// IsTickledMe 判断消息是否拍了拍自己
func (m *Message) IsTickledMe() bool {
return m.IsSystem() && strings.Count(m.Content, "拍了拍我") == 1
return m.IsPaiYiPai()
}
// IsVoipInvite 判断消息是否为语音或视频通话邀请

View File

@ -11,6 +11,14 @@ 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,6 +38,15 @@ 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

@ -9,12 +9,8 @@ import (
type Friend struct{ *User }
// implement fmt.Stringer
func (f *Friend) String() string {
display := f.NickName
if f.RemarkName != "" {
display = f.RemarkName
}
return fmt.Sprintf("<Friend:%s>", display)
func (f Friend) String() string {
return fmt.Sprintf("<Friend:%s>", f.NickName)
}
// SetRemarkName 重命名当前好友
@ -57,7 +53,7 @@ func (f Friends) Count() int {
// First 获取第一个好友
func (f Friends) First() *Friend {
if f.Count() > 0 {
return f.Sort()[0]
return f[0]
}
return nil
}
@ -65,7 +61,7 @@ func (f Friends) First() *Friend {
// Last 获取最后一个好友
func (f Friends) Last() *Friend {
if f.Count() > 0 {
return f.Sort()[f.Count()-1]
return f[f.Count()-1]
}
return nil
}
@ -159,7 +155,7 @@ func (f Friends) SendFile(file io.Reader, 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)
}
@ -242,7 +238,7 @@ func (g Groups) Count() int {
// First 获取第一个群组
func (g Groups) First() *Group {
if g.Count() > 0 {
return g.Sort()[0]
return g[0]
}
return nil
}
@ -250,7 +246,7 @@ func (g Groups) First() *Group {
// Last 获取最后一个群组
func (g Groups) Last() *Group {
if g.Count() > 0 {
return g.Sort()[g.Count()-1]
return g[g.Count()-1]
}
return nil
}
@ -304,6 +300,11 @@ 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 {
@ -339,7 +340,7 @@ func (g Groups) Uniq() Groups {
// Mp 公众号对象
type Mp struct{ *User }
func (m *Mp) String() string {
func (m Mp) String() string {
return fmt.Sprintf("<Mp:%s>", m.NickName)
}
@ -354,7 +355,7 @@ func (m Mps) Count() int {
// First 获取第一个
func (m Mps) First() *Mp {
if m.Count() > 0 {
return m.Sort()[0]
return m[0]
}
return nil
}
@ -362,7 +363,7 @@ func (m Mps) First() *Mp {
// Last 获取最后一个
func (m Mps) Last() *Mp {
if m.Count() > 0 {
return m.Sort()[m.Count()-1]
return m[m.Count()-1]
}
return nil
}
@ -444,6 +445,11 @@ 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()

View File

@ -1,25 +0,0 @@
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

@ -84,8 +84,6 @@ bot.Login()
// 创建热存储容器对象
reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
defer reloadStorage.Close()
// 执行热登录
bot.HotLogin(reloadStorage)
```
@ -97,7 +95,7 @@ bot.HotLogin(reloadStorage)
我们只需要在`HotLogin`增加一个参数,让它在失败后执行扫码登录即可
```go
bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption())
bot.HotLogin(reloadStorage, openwechat.HotLoginWithRetry(true))
```
当扫码登录成功后,会将会话信息写入到`热存储容器`中,下次再执行热登录的时候就会从`热存储容器`中读取会话信息,直接登录成功。
@ -121,23 +119,29 @@ type HotReloadStorage io.ReadWriter
openwechat也提供了这样的功能。
```go
bot.PushLogin(storage HotReloadStorage, opts ...openwechat.BotLoginOption) error
bot.PushLogin(storage HotReloadStorage, opts ...PushLoginOptionFunc) error
```
`PushLogin`需要传入一个`热存储容器`,和一些可选参数。
`HotReloadStorage` 跟上面一样,用来保存会话信息,必要参数。
`openwechat.BotLoginOption`是一个可选参数,用来设置一些额外的行为。
`PushLoginOptionFunc`是一个可选参数,用来设置一些额外的行为。
目前有下面几个可选参数:
```go
// NewSyncReloadDataLoginOption 登录成功后定时同步热存储容器数据
func NewSyncReloadDataLoginOption(duration time.Duration) BotLoginOption
// PushLoginWithoutUUIDCallback 设置 PushLogin 不执行二维码回调, 默认为 true
func PushLoginWithoutUUIDCallback(flag bool) PushLoginOptionFunc
// NewRetryLoginOption 登录失败后进行扫码登录
func NewRetryLoginOption() BotLoginOption
// PushLoginWithoutScanCallback 设置 PushLogin 不执行扫码回调, 默认为true
func PushLoginWithoutScanCallback(flag bool) PushLoginOptionFunc
// PushLoginWithoutLoginCallback 设置 PushLogin 不执行登录回调默认为false
func PushLoginWithoutLoginCallback(flag bool) PushLoginOptionFunc
// PushLoginWithRetry 设置 PushLogin 失败后执行扫码登录默认为false
func PushLoginWithRetry(flag bool) PushLoginOptionFunc
```
注意:如果是第一次登录,``PushLogin`` 一定会失败的,因为我们的`HotReloadStorage`里面没有会话信息,你需要设置失败会进行扫码登录。
@ -145,8 +149,7 @@ func NewRetryLoginOption() BotLoginOption
```go
bot := openwechat.DefaultBot()
reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
defer reloadStorage.Close()
err = bot.PushLogin(reloadStorage, openwechat.NewRetryLoginOption())
err = bot.PushLogin(reloadStorage, openwechat.PushLoginWithRetry(true))
```
这样当第一次登录失败的时候,会自动执行扫码登录。
@ -161,21 +164,13 @@ err = bot.PushLogin(reloadStorage, openwechat.NewRetryLoginOption())
通过对`bot`对象绑定扫码回调即可实现对应的功能。
```go
bot.ScanCallBack = func(body openwechat.CheckLoginResponse) { fmt.Println(string(body)) }
bot.ScanCallBack = func(body []byte) { fmt.Println(string(body)) }
```
用户扫码后body里面会携带用户的头像信息。
**注**:绑定扫码回调须在登录前执行。
`CheckLoginResponse` 是一个`[]byte`包装类型, 扫码成功后可以通过该类型获取用户的头像信息。
```go
type CheckLoginResponse []byte
func (c CheckLoginResponse) Avatar() (string, error)
```
### 登录回调
@ -183,13 +178,13 @@ func (c CheckLoginResponse) Avatar() (string, error)
`bot`对象绑定登录
```go
bot.LoginCallBack = func(body openwechat.CheckLoginResponse) {
bot.LoginCallBack = func(body []byte) {
fmt.Println(string(body))
// to do your business
}
```
登录回调的参数就是当前客户端需要跳转的链接,用户可以不用关心它。(其实可以拿来做一些骚操作😈)
登录回调的参数就是当前客户端需要跳转的链接,可以不用关心它。
登录回调函数可以当做一个信号处理,表示当前扫码登录的用户已经确认登录。
@ -241,7 +236,7 @@ dispatcher.OnText(func(ctx *openwechat.MessageContext){
})
// 注册消息回调函数
bot.MessageHandler = dispatcher.AsMessageHandler()
bot.MessageHandler = openwechat.DispatchMessage(dispatcher)
```
`openwechat.DispatchMessage`会将消息转发给`dispatcher`对象处理

View File

@ -1,5 +1,7 @@
# 消息
### 接受消息
被动接受的消息对象,由微信服务器发出
@ -7,15 +9,17 @@
消息对象通过绑定在`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
@ -26,6 +30,8 @@ msg.Content // 获取消息内容
由于消息分为很多种类型,它们都共用`Content`属性。一般当消息类型为文本类型的时候,我们才会去访问`Content`属性。
#### 消息类型判断
下面的判断消息类型的方法均返回`bool`
@ -111,17 +117,13 @@ msg.IsIsPaiYiPai() // 拍一拍消息
msg.IsTickled()
```
##### 判断是否拍了拍自己
```go
msg.IsTickledMe()
```
##### 判断是否有新人加入群聊
```go
msg.IsJoinGroup()
```
#### 获取消息的发送者
```go
@ -130,12 +132,16 @@ sender, err := msg.Sender()
如果是群聊消息,该方法返回的是群聊对象(需要自己将`User`转换为`Group`对象)
#### 获取消息的接受者
```go
receiver, err := msg.Receiver()
```
#### 获取消息在群里面的发送者
```go
@ -144,6 +150,8 @@ sender, err := msg.SenderInGroup()
获取群聊中具体发消息的用户,前提该消息必须来自群聊。
#### 是否由自己发送
```go
@ -156,24 +164,31 @@ msg.IsSendBySelf()
msg.IsTickled()
```
#### 消息是否由好友发出
```go
msg.IsSendByFriend()
```
#### 消息是否由群聊发出
```go
msg.IsSendByGroup()
```
#### 回复文本消息
```go
msg.ReplyText("hello")
```
#### 回复图片消息
```go
@ -182,6 +197,8 @@ defer img.Close()
msg.ReplyImage(img)
```
#### 回复文件消息
```go
@ -190,12 +207,14 @@ defer file.Close()
msg.ReplyFile(file)
```
#### 获取消息里的其他信息
##### 名片消息
```go
card, err := msg.Card()
card, err := msg. Card()
```
该方法调用的前提为`msg.IsCard()`返回为`true`
@ -211,29 +230,31 @@ 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
@ -246,17 +267,19 @@ 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
@ -268,6 +291,8 @@ friend, err := msg.Agree()
该方法调用成功的前提是`msg.IsFriendAdd()`返回为`true`
#### 设置为已读
```go
@ -276,6 +301,10 @@ msg.AsRead()
该当前消息设置为已读
#### 设置消息的上下文
用于多个消息处理函数之间的通信,并且是协程安全的。
@ -292,6 +321,10 @@ msg.Set("hello", "world")
value, exist := msg.Get("hello")
```
### 已发送消息
已发送消息指当前用户发送出去的消息
@ -306,6 +339,8 @@ sentMsg, err := msg.ReplyText("hello") // 通过回复消息获取
// and so on
```
#### 撤回消息
撤回刚刚发送的消息撤回消息的有效时间为2分钟超过了这个时间则无法撤回
@ -314,12 +349,16 @@ sentMsg, err := msg.ReplyText("hello") // 通过回复消息获取
sentMsg.Revoke()
```
#### 判断是否可以撤回
```go
sentMsg.CanRevoke()
```
#### 转发给好友
```go
@ -328,6 +367,8 @@ sentMsg.ForwardToFriends(friend1, friend2)
将刚发送的消息转发给好友
#### 转发给群聊
```go
@ -336,6 +377,10 @@ sentMsg.ForwardToGroups(group1, group2)
将刚发送的消息转发给群聊
### Emoji表情
openwechat提供了微信全套`emoji`表情的支持

View File

@ -3,7 +3,6 @@ package openwechat
import (
"io"
"os"
"sync"
"time"
)
@ -25,17 +24,14 @@ type HotReloadStorageItem struct {
// HotReloadStorage 热登陆存储接口
type HotReloadStorage io.ReadWriter
// fileHotReloadStorage 实现HotReloadStorage接口
// 以文件的形式存储
type fileHotReloadStorage struct {
// jsonFileHotReloadStorage 实现HotReloadStorage接口
// 默认json文件的形式存储
type jsonFileHotReloadStorage struct {
filename string
file *os.File
lock sync.Mutex
}
func (j *fileHotReloadStorage) Read(p []byte) (n int, err error) {
j.lock.Lock()
defer j.lock.Unlock()
func (j *jsonFileHotReloadStorage) Read(p []byte) (n int, err error) {
if j.file == nil {
j.file, err = os.OpenFile(j.filename, os.O_RDWR, 0600)
if os.IsNotExist(err) {
@ -48,47 +44,38 @@ func (j *fileHotReloadStorage) Read(p []byte) (n int, err error) {
return j.file.Read(p)
}
func (j *fileHotReloadStorage) Write(p []byte) (n int, err error) {
j.lock.Lock()
defer j.lock.Unlock()
func (j *jsonFileHotReloadStorage) Write(p []byte) (n int, err error) {
if j.file == nil {
j.file, err = os.Create(j.filename)
if err != nil {
return 0, err
}
}
// reset offset and truncate file
// 为什么这里要对文件进行Truncate操作呢?
// 这是为了方便每次Dump的时候对文件进行重新写入, 而不是追加
// json序列化写入只会调用一次Write方法, 所以不要把这个方法当成io.Writer的Write方法
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 *fileHotReloadStorage) Close() error {
j.lock.Lock()
defer j.lock.Unlock()
func (j *jsonFileHotReloadStorage) Close() error {
if j.file == nil {
return nil
}
return j.file.Close()
}
// Deprecated: use NewFileHotReloadStorage instead
// 不再单纯以json的格式存储支持了用户自定义序列化方式
// NewJsonFileHotReloadStorage 创建JsonFileHotReloadStorage
func NewJsonFileHotReloadStorage(filename string) io.ReadWriteCloser {
return NewFileHotReloadStorage(filename)
return &jsonFileHotReloadStorage{filename: filename}
}
// NewFileHotReloadStorage implements HotReloadStorage
func NewFileHotReloadStorage(filename string) io.ReadWriteCloser {
return &fileHotReloadStorage{filename: filename}
}
var _ HotReloadStorage = (*fileHotReloadStorage)(nil)
var _ HotReloadStorage = (*jsonFileHotReloadStorage)(nil)
type HotReloadStorageSyncer struct {
duration time.Duration

View File

@ -25,11 +25,7 @@ func (s SyncCheckResponse) Success() bool {
}
func (s SyncCheckResponse) NorMal() bool {
return s.Success() && s.Selector == SelectorNormal
}
func (s SyncCheckResponse) HasNewMessage() bool {
return s.Success() && s.Selector == SelectorNewMsg
return s.Success() && s.Selector == "0"
}
func (s SyncCheckResponse) Err() error {

34
user.go
View File

@ -58,14 +58,14 @@ type User struct {
// implement fmt.Stringer
func (u *User) String() string {
format := "User"
if u.IsSelf() {
format = "Self"
} else if u.IsFriend() {
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)
}
@ -263,7 +263,6 @@ func (s *Self) Members(update ...bool) (Members, error) {
return nil, err
}
}
s.members.Sort()
return s.members, nil
}
@ -288,18 +287,13 @@ 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 (len(update) > 0 && update[0]) || s.ChkFrdGrpMpNil() {
if s.friends == nil || (len(update) > 0 && update[0]) {
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
@ -307,14 +301,10 @@ func (s *Self) Friends(update ...bool) (Friends, error) {
// Groups 获取所有的群组
func (s *Self) Groups(update ...bool) (Groups, error) {
if (len(update) > 0 && update[0]) || s.ChkFrdGrpMpNil() {
if s.groups == nil || (len(update) > 0 && update[0]) {
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
@ -322,12 +312,10 @@ func (s *Self) Groups(update ...bool) (Groups, error) {
// Mps 获取所有的公众号
func (s *Self) Mps(update ...bool) (Mps, error) {
if (len(update) > 0 && update[0]) || s.ChkFrdGrpMpNil() {
if s.mps == nil || (len(update) > 0 && update[0]) {
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
@ -679,16 +667,6 @@ func (s *Self) SendVideoToGroups(video io.Reader, delay time.Duration, groups ..
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