From 46e6fb1afb35b30706a52e6a6b2a42f47120238e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9A=E5=90=83=E7=82=B9=E8=8B=B9=E6=9E=9C?= <73388495+eatmoreapple@users.noreply.github.com> Date: Thu, 5 Jan 2023 18:24:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20bot=20option=20(#176)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot.go | 12 ++++++------ bot_option.go | 30 ++++++++++++++++++++++++++++++ mode.go | 4 ++-- 3 files changed, 38 insertions(+), 8 deletions(-) create mode 100644 bot_option.go diff --git a/bot.go b/bot.go index 4864407..41f06a3 100644 --- a/bot.go +++ b/bot.go @@ -387,8 +387,8 @@ func (b *Bot) OnLogout(f func(bot *Bot)) { // 接收外部的 context.Context,用于控制Bot的存活 func NewBot(c context.Context) *Bot { caller := DefaultCaller() - // 默认行为为桌面模式 - caller.Client.SetMode(Normal) + // 默认行为为网页版微信模式 + caller.Client.SetMode(normal) ctx, cancel := context.WithCancel(c) return &Bot{Caller: caller, Storage: &Storage{}, context: ctx, cancel: cancel} } @@ -397,11 +397,8 @@ func NewBot(c context.Context) *Bot { // mode不传入默认为 openwechat.Desktop,详情见mode // // bot := openwechat.DefaultBot(openwechat.Desktop) -func DefaultBot(modes ...Mode) *Bot { +func DefaultBot(opts ...BotOptionFunc) *Bot { bot := NewBot(context.Background()) - if len(modes) > 0 { - bot.Caller.Client.SetMode(modes[0]) - } // 获取二维码回调 bot.UUIDCallback = PrintlnQrcodeUrl // 扫码回调 @@ -417,6 +414,9 @@ func DefaultBot(modes ...Mode) *Bot { bot.SyncCheckCallback = func(resp SyncCheckResponse) { log.Printf("RetCode:%s Selector:%s", resp.RetCode, resp.Selector) } + for _, opt := range opts { + opt(bot) + } return bot } diff --git a/bot_option.go b/bot_option.go new file mode 100644 index 0000000..e5e659e --- /dev/null +++ b/bot_option.go @@ -0,0 +1,30 @@ +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) + } +} diff --git a/mode.go b/mode.go index ed5a75d..49c9b15 100644 --- a/mode.go +++ b/mode.go @@ -13,9 +13,9 @@ type Mode interface { } var ( - Normal Mode = normalMode{} + normal Mode = normalMode{} - Desktop Mode = desktopMode{} + desktop Mode = desktopMode{} ) type normalMode struct{}