From 087c6c02987344ea0decc04bc4a3887aeef8e0a0 Mon Sep 17 00:00:00 2001 From: fumiama Date: Thu, 9 Sep 2021 00:20:04 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=20=E6=96=B0=E5=A2=9E=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + README.md | 18 ++- control/register.go | 14 +++ control/rule.go | 177 ++++++++++++++++++++++++++++ control/tables.go | 13 ++ {plugin_setutime => data}/sqlite.go | 53 ++++++--- go.sum | 2 + main.go | 2 + plugin_acgimage/classify.go | 22 +++- plugin_ai_false/ai_false.go | 8 +- plugin_aiwife/non-existent.go | 8 +- plugin_bilibili/fansDaily.go | 2 +- plugin_bilibili/info.go | 12 +- plugin_bilibili/live_info.go | 2 +- plugin_diana/bing.go | 17 ++- plugin_diana/data/text.go | 5 +- plugin_diana/zhiwang.go | 2 +- plugin_github/repo_searcher.go | 9 +- plugin_hs/run.go | 13 +- plugin_image_finder/keyword.go | 8 +- plugin_setutime/setu_geter.go | 15 +-- 21 files changed, 355 insertions(+), 48 deletions(-) create mode 100644 control/register.go create mode 100644 control/rule.go create mode 100644 control/tables.go rename {plugin_setutime => data}/sqlite.go (83%) diff --git a/.gitignore b/.gitignore index fa6c45c5..5736e33f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ data/SetuTime/cache +data/control data/SetuTime/search data/manager data/acgimage diff --git a/README.md b/README.md index 0e82d755..c99cdea9 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,11 @@ ## 功能 - +- **插件控制** + - [x] /启用 xxx + - [x] /禁用 xxx + - [x] /用法 xxx + - [x] /服务列表 - **聊天** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_chat"` - [x] [BOT名字] - [x] [戳一戳BOT] @@ -59,8 +63,8 @@ - [ ] 警告[@xxx] - [x] run[xxx] - **GitHub仓库搜索** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_github"` - - [x] > github [xxx] - - [x] > github -p [xxx] + - [x] >github [xxx] + - [x] >github -p [xxx] - **在线代码运行** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_runcode"` - [x] > runcode help - [x] > runcode [on/off] @@ -99,14 +103,16 @@ - [x] 太涩了(撤回最近发的图) - [x] 评价图片(发送一张图片让bot评分) - **浅草寺求签** `github.com/FloatTech/ZeroBot-Plugin/plugin_omikuji` - - 本插件要求`Go`版本大于等于`1.17` - [x] @BOT 求签|运势|占卜 - **bilibili** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_bilibili"` - - [x] > bili info [名字] + - [x] >vup info [名字|uid] + - [x] >user info [名字|uid] + - [x] /开启粉丝日报 - **嘉然** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_diana"` - [x] @BOT 小作文 - [x] @BOT 发大病 - [x] @BOT 教你一篇小作文[作文] + = [x] [回复]查重 - **AIfalse** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_ai_false"` - [x] 查询计算机当前活跃度 [身体检查] - [ ] 简易语音 @@ -122,6 +128,8 @@ - [x] @Bot 任意文本(任意一句话回复) - [x] 关闭自动回复 - [x] 启动自动回复 +- **关键字搜图** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_image_finder"` + - [x] 来张 [xxx] - **TODO...** ## 使用方法 diff --git a/control/register.go b/control/register.go new file mode 100644 index 00000000..8228a6bc --- /dev/null +++ b/control/register.go @@ -0,0 +1,14 @@ +package control + +import ( + zero "github.com/wdvxdr1123/ZeroBot" +) + +var m Control + +func Register(service string, o *Options) *zero.Engine { + engine := zero.New() + m = *New(service, o) + engine.UsePreHandler(m.Handler()) + return engine +} diff --git a/control/rule.go b/control/rule.go new file mode 100644 index 00000000..1a114167 --- /dev/null +++ b/control/rule.go @@ -0,0 +1,177 @@ +// Package control 控制插件的启用与优先级等 +package control + +import ( + "os" + "strconv" + "sync" + + . "github.com/FloatTech/ZeroBot-Plugin/data" + "github.com/sirupsen/logrus" + zero "github.com/wdvxdr1123/ZeroBot" + "github.com/wdvxdr1123/ZeroBot/extension" + "github.com/wdvxdr1123/ZeroBot/message" +) + +var ( + db = &Sqlite{DBPath: "data/control/plugins.db"} + // managers 每个插件对应的管理 + managers = map[string]*Control{} + mu = sync.RWMutex{} +) + +// Control is to control the plugins. +type Control struct { + sync.RWMutex + service string + options Options +} + +// New returns Manager with settings. +func New(service string, o *Options) *Control { + m := &Control{service: service, + options: func() Options { + if o == nil { + return Options{} + } + return *o + }(), + } + mu.Lock() + defer mu.Unlock() + managers[service] = m + err := db.Create(service, &grpcfg{}) + if err != nil { + panic(err) + } + return m +} + +// Enable enables a group to pass the Manager. +func (m *Control) Enable(groupID int64) { + m.Lock() + err := db.Insert(m.service, &grpcfg{groupID, 0}) + if err != nil { + logrus.Errorf("[control] %v", err) + } + m.Unlock() +} + +// Disable disables a group to pass the Manager. +func (m *Control) Disable(groupID int64) { + m.Lock() + err := db.Insert(m.service, &grpcfg{groupID, 1}) + if err != nil { + logrus.Errorf("[control] %v", err) + } + m.Unlock() +} + +// Handler 返回 预处理器 +func (m *Control) Handler() zero.Rule { + return func(ctx *zero.Ctx) bool { + m.RLock() + ctx.State["manager"] = m + var c grpcfg + err := db.Find(m.service, &c, "WHERE gid = "+strconv.FormatInt(ctx.Event.GroupID, 10)) + if err == nil { + m.RUnlock() + return c.Disable == 0 + } else { + logrus.Errorf("[control] %v", err) + } + m.RUnlock() + if m.options.DisableOnDefault { + m.Disable(ctx.Event.GroupID) + } else { + m.Enable(ctx.Event.GroupID) + } + return !m.options.DisableOnDefault + } +} + +// Lookup returns a Manager by the service name, if +// not exist, it will returns nil. +func Lookup(service string) (*Control, bool) { + mu.RLock() + defer mu.RUnlock() + m, ok := managers[service] + return m, ok +} + +// ForEach iterates through managers. +func ForEach(iterator func(key string, manager *Control) bool) { + mu.RLock() + m := copyMap(managers) + mu.RUnlock() + for k, v := range m { + if !iterator(k, v) { + return + } + } +} + +func copyMap(m map[string]*Control) map[string]*Control { + ret := make(map[string]*Control, len(m)) + for k, v := range m { + ret[k] = v + } + return ret +} + +func Init() { + err := os.MkdirAll("data/control", 0755) + if err != nil { + panic(err) + } + zero.OnCommandGroup([]string{"启用", "enable"}, zero.AdminPermission, zero.OnlyGroup). + Handle(func(ctx *zero.Ctx) { + model := extension.CommandModel{} + _ = ctx.Parse(&model) + service, ok := Lookup(model.Args) + if !ok { + ctx.Send("没有找到指定服务!") + } + service.Enable(ctx.Event.GroupID) + ctx.Send(message.Text("已启用服务: " + model.Args)) + }) + + zero.OnCommandGroup([]string{"禁用", "disable"}, zero.AdminPermission, zero.OnlyGroup). + Handle(func(ctx *zero.Ctx) { + model := extension.CommandModel{} + _ = ctx.Parse(&model) + service, ok := Lookup(model.Args) + if !ok { + ctx.Send("没有找到指定服务!") + } + service.Disable(ctx.Event.GroupID) + ctx.Send(message.Text("已关闭服务: " + model.Args)) + }) + + zero.OnCommandGroup([]string{"用法", "usage"}, zero.AdminPermission, zero.OnlyGroup). + Handle(func(ctx *zero.Ctx) { + model := extension.CommandModel{} + _ = ctx.Parse(&model) + service, ok := Lookup(model.Args) + if !ok { + ctx.Send("没有找到指定服务!") + } + if service.options.Help != "" { + ctx.Send(service.options.Help) + } else { + ctx.Send("该服务无帮助!") + } + }) + + zero.OnCommandGroup([]string{"服务列表", "service_list"}, zero.AdminPermission, zero.OnlyGroup). + Handle(func(ctx *zero.Ctx) { + msg := `---服务列表---` + i := 0 + ForEach(func(key string, manager *Control) bool { + i++ + msg += "\n" + strconv.Itoa(i) + `: ` + key + return true + }) + ctx.Send(message.Text(msg)) + }) +} diff --git a/control/tables.go b/control/tables.go new file mode 100644 index 00000000..74d41657 --- /dev/null +++ b/control/tables.go @@ -0,0 +1,13 @@ +package control + +// grpcfg holds the group config for the Manager. +type grpcfg struct { + GroupID int64 `db:"gid"` // GroupID 群号 + Disable int64 `db:"disable"` // Disable 默认启用该插件 +} + +// Options holds the optional parameters for the Manager. +type Options struct { + DisableOnDefault bool + Help string // 帮助文本信息 +} diff --git a/plugin_setutime/sqlite.go b/data/sqlite.go similarity index 83% rename from plugin_setutime/sqlite.go rename to data/sqlite.go index e0a2de6a..ee55403b 100644 --- a/plugin_setutime/sqlite.go +++ b/data/sqlite.go @@ -1,4 +1,4 @@ -package setutime +package data import ( "database/sql" @@ -8,16 +8,16 @@ import ( _ "modernc.org/sqlite" // 引入sqlite ) -// sqlite 数据库对象 -type sqlite struct { +// Sqlite 数据库对象 +type Sqlite struct { DB *sql.DB DBPath string } -// create 生成数据库 +// Create 生成数据库 // 默认结构体的第一个元素为主键 // 返回错误 -func (db *sqlite) create(table string, objptr interface{}) (err error) { +func (db *Sqlite) Create(table string, objptr interface{}) (err error) { if db.DB == nil { database, err := sql.Open("sqlite", db.DBPath) if err != nil { @@ -53,10 +53,10 @@ func (db *sqlite) create(table string, objptr interface{}) (err error) { return nil } -// insert 插入数据集 +// Insert 插入数据集 // 默认结构体的第一个元素为主键 // 返回错误 -func (db *sqlite) insert(table string, objptr interface{}) (err error) { +func (db *Sqlite) Insert(table string, objptr interface{}) (err error) { rows, err := db.DB.Query("SELECT * FROM " + table) if err != nil { return err @@ -71,7 +71,7 @@ func (db *sqlite) insert(table string, objptr interface{}) (err error) { top = len(tags) - 1 cmd = []string{} ) - cmd = append(cmd, "INSERT INTO") + cmd = append(cmd, "REPLACE INTO") cmd = append(cmd, table) for i := range tags { switch i { @@ -112,11 +112,11 @@ func (db *sqlite) insert(table string, objptr interface{}) (err error) { return nil } -// find 查询数据库 +// Find 查询数据库 // condition 可为"WHERE id = 0" // 默认字段与结构体元素顺序一致 // 返回错误 -func (db *sqlite) find(table string, objptr interface{}, condition string) (err error) { +func (db *Sqlite) Find(table string, objptr interface{}, condition string) (err error) { var cmd = []string{} cmd = append(cmd, "SELECT * FROM ") cmd = append(cmd, table) @@ -142,10 +142,35 @@ func (db *sqlite) find(table string, objptr interface{}, condition string) (err return nil } -// del 删除数据库 +// ListTables 列出所有表名 +// 返回所有表名+错误 +func (db *Sqlite) ListTables() (s []string, err error) { + rows, err := db.DB.Query("SELECT name FROM sqlite_master where type='table' order by name;") + if err != nil { + return + } + if rows.Err() != nil { + return nil, rows.Err() + } + defer rows.Close() + + for rows.Next() { + if err != nil { + return + } + objptr := new(string) + err = rows.Scan(objptr) + if err == nil { + s = append(s, *objptr) + } + } + return +} + +// Del 删除数据库 // condition 可为"WHERE id = 0" // 返回错误 -func (db *sqlite) del(table string, condition string) (err error) { +func (db *Sqlite) Del(table string, condition string) (err error) { var cmd = []string{} cmd = append(cmd, "DELETE FROM") cmd = append(cmd, table) @@ -161,9 +186,9 @@ func (db *sqlite) del(table string, condition string) (err error) { return nil } -// count 查询数据库行数 +// Count 查询数据库行数 // 返回行数以及错误 -func (db *sqlite) count(table string) (num int, err error) { +func (db *Sqlite) Count(table string) (num int, err error) { var cmd = []string{} cmd = append(cmd, "SELECT * FROM") cmd = append(cmd, table) diff --git a/go.sum b/go.sum index c8e068c5..bf105faa 100644 --- a/go.sum +++ b/go.sum @@ -22,6 +22,7 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= @@ -68,6 +69,7 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE= github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ= github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 h1:J6v8awz+me+xeb/cUTotKgceAYouhIB3pjzgRd6IlGk= github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816/go.mod h1:tzym/CEb5jnFI+Q0k4Qq3+LvRF4gO3E2pxS8fHP8jcA= diff --git a/main.go b/main.go index a09ffb6c..34b21446 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( // 注:以下插件均可通过前面加 // 注释,注释后停用并不加载插件 // 下列插件可与 wdvxdr1123/ZeroBot v1.1.2 以上配合单独使用 // 词库类 + "github.com/FloatTech/ZeroBot-Plugin/control" _ "github.com/FloatTech/ZeroBot-Plugin/plugin_atri" // ATRI词库 _ "github.com/FloatTech/ZeroBot-Plugin/plugin_chat" // 基础词库 _ "github.com/FloatTech/ZeroBot-Plugin/plugin_qingyunke" //青云客 @@ -60,6 +61,7 @@ func init() { LogFormat: "[zero][%time%][%lvl%]: %msg% \n", }) log.SetLevel(log.DebugLevel) + control.Init() } func main() { diff --git a/plugin_acgimage/classify.go b/plugin_acgimage/classify.go index 7e18a51b..24e85890 100644 --- a/plugin_acgimage/classify.go +++ b/plugin_acgimage/classify.go @@ -9,6 +9,7 @@ import ( "github.com/FloatTech/AnimeAPI/classify" "github.com/FloatTech/AnimeAPI/picture" + "github.com/FloatTech/ZeroBot-Plugin/control" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/message" ) @@ -31,7 +32,16 @@ var ( func init() { // 插件主体 // 初始化 classify classify.Init(datapath) - zero.OnRegex(`^设置随机图片网址(.*)$`, zero.OnlyPrivate, zero.SuperUserPermission).SetBlock(true).SetPriority(20). + engine := control.Register("acgimage", &control.Options{ + DisableOnDefault: false, + Help: "随机图片与AI点评\n" + + "- 随机图片(评级大于6的图将私发)\n" + + "- 直接随机(无r18检测,务必小心,仅管理可用)\n" + + "- 设置随机图片网址[url]\n" + + "- 太涩了(撤回最近发的图)\n" + + "- 评价图片(发送一张图片让bot评分)", + }) + engine.OnRegex(`^设置随机图片网址(.*)$`, zero.OnlyPrivate, zero.SuperUserPermission).SetBlock(true).SetPriority(20). Handle(func(ctx *zero.Ctx) { url := ctx.State["regex_matched"].([]string)[1] if !strings.HasPrefix(url, "http") { @@ -42,7 +52,7 @@ func init() { // 插件主体 } }) // 有保护的随机图片 - zero.OnFullMatch("随机图片", zero.OnlyGroup).SetBlock(true).SetPriority(24). + engine.OnFullMatch("随机图片", zero.OnlyGroup).SetBlock(true).SetPriority(24). Handle(func(ctx *zero.Ctx) { if classify.CanVisit(5) { go func() { @@ -54,7 +64,7 @@ func init() { // 插件主体 } }) // 直接随机图片,无r18保护,后果自负。如果出r18图可尽快通过发送"太涩了"撤回 - zero.OnFullMatch("直接随机", zero.OnlyGroup, zero.AdminPermission).SetBlock(true).SetPriority(24). + engine.OnFullMatch("直接随机", zero.OnlyGroup, zero.AdminPermission).SetBlock(true).SetPriority(24). Handle(func(ctx *zero.Ctx) { if block { ctx.Send("请稍后再试哦") @@ -71,12 +81,12 @@ func init() { // 插件主体 } }) // 撤回最后的直接随机图片 - zero.OnFullMatch("太涩了").SetBlock(true).SetPriority(24). + engine.OnFullMatch("太涩了").SetBlock(true).SetPriority(24). Handle(func(ctx *zero.Ctx) { go cancel(ctx) }) // 上传一张图进行评价 - zero.OnKeywordGroup([]string{"评价图片"}, zero.OnlyGroup, picture.CmdMatch, picture.MustGiven).SetBlock(true).SetPriority(24). + engine.OnKeywordGroup([]string{"评价图片"}, zero.OnlyGroup, picture.CmdMatch, picture.MustGiven).SetBlock(true).SetPriority(24). Handle(func(ctx *zero.Ctx) { ctx.Send("少女祈祷中...") for _, url := range ctx.State["image_url"].([]string) { @@ -86,7 +96,7 @@ func init() { // 插件主体 }(url) } }) - zero.OnRegex(`^给你点提示哦:(.*)$`, zero.OnlyPrivate).SetBlock(true).SetPriority(20). + engine.OnRegex(`^给你点提示哦:(.*)$`, zero.OnlyPrivate).SetBlock(true).SetPriority(20). Handle(func(ctx *zero.Ctx) { dhash := ctx.State["regex_matched"].([]string)[1] if len(dhash) == 5*3 { diff --git a/plugin_ai_false/ai_false.go b/plugin_ai_false/ai_false.go index 15d907ab..bdde7bd2 100644 --- a/plugin_ai_false/ai_false.go +++ b/plugin_ai_false/ai_false.go @@ -5,6 +5,7 @@ import ( "math" "time" + "github.com/FloatTech/ZeroBot-Plugin/control" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/mem" @@ -14,7 +15,12 @@ import ( ) func init() { // 插件主体 - zero.OnFullMatchGroup([]string{"检查身体", "自检", "启动自检", "系统状态"}, zero.AdminPermission). + engine := control.Register("aifalse", &control.Options{ + DisableOnDefault: false, + Help: "AIfalse\n" + + "- 查询计算机当前活跃度[检查身体|自检|启动自检|系统状态", + }) + engine.OnFullMatchGroup([]string{"检查身体", "自检", "启动自检", "系统状态"}, zero.AdminPermission). Handle(func(ctx *zero.Ctx) { ctx.SendChain(message.Text( "* CPU占用率: ", cpuPercent(), "%\n", diff --git a/plugin_aiwife/non-existent.go b/plugin_aiwife/non-existent.go index 0f69e431..5825a990 100644 --- a/plugin_aiwife/non-existent.go +++ b/plugin_aiwife/non-existent.go @@ -6,6 +6,7 @@ import ( "math/rand" "time" + "github.com/FloatTech/ZeroBot-Plugin/control" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/message" ) @@ -18,7 +19,12 @@ func init() { // 插件主体 // TODO: 1.17 特性暂不增加 // rand.Seed(time.Now().UnixMicro()) rand.Seed(time.Now().UnixNano()) - zero.OnFullMatchGroup([]string{"waifu", "随机waifu"}).SetPriority(10). + engine := control.Register("aiwife", &control.Options{ + DisableOnDefault: false, + Help: "AIWife\n" + + "- waifu|随机waifu", + }) + engine.OnFullMatchGroup([]string{"waifu", "随机waifu"}).SetPriority(10). Handle(func(ctx *zero.Ctx) { miku := rand.Intn(100000) + 1 ctx.SendChain(message.At(ctx.Event.UserID), message.Image(fmt.Sprintf(bed, miku))) diff --git a/plugin_bilibili/fansDaily.go b/plugin_bilibili/fansDaily.go index 12b0d800..5e56ad67 100644 --- a/plugin_bilibili/fansDaily.go +++ b/plugin_bilibili/fansDaily.go @@ -23,7 +23,7 @@ type follower struct { // 开启日报推送 func init() { - zero.OnFullMatch("/开启粉丝日报", zero.AdminPermission). + engine.OnFullMatch("/开启粉丝日报", zero.AdminPermission). Handle(func(ctx *zero.Ctx) { fansDaily(ctx.Event.GroupID) // 群号传进去给下面发信息的函数 }) diff --git a/plugin_bilibili/info.go b/plugin_bilibili/info.go index 84d39a18..6f02e69a 100644 --- a/plugin_bilibili/info.go +++ b/plugin_bilibili/info.go @@ -5,14 +5,24 @@ import ( "io/ioutil" "net/http" + "github.com/FloatTech/ZeroBot-Plugin/control" "github.com/tidwall/gjson" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/message" ) +var engine *zero.Engine + // 查成分的 func init() { - zero.OnRegex(`^>user info\s(.{1,25})$`). + engine = control.Register("bilibili", &control.Options{ + DisableOnDefault: false, + Help: "bilibili\n" + + "- >vup info [名字|uid]\n" + + "- >user info [名字|uid]\n" + + "- /开启粉丝日报", + }) + engine.OnRegex(`^>user info\s(.{1,25})$`). Handle(func(ctx *zero.Ctx) { keyword := ctx.State["regex_matched"].([]string)[1] rest, err := uid(keyword) diff --git a/plugin_bilibili/live_info.go b/plugin_bilibili/live_info.go index 0c94869d..b9b5a48d 100644 --- a/plugin_bilibili/live_info.go +++ b/plugin_bilibili/live_info.go @@ -13,7 +13,7 @@ import ( // 查vup粉丝数据 func init() { - zero.OnRegex(`^>vup info\s?(.{1,25})$`). + engine.OnRegex(`^>vup info\s?(.{1,25})$`). Handle(func(ctx *zero.Ctx) { keyword := ctx.State["regex_matched"].([]string)[1] res, err := uid(keyword) diff --git a/plugin_diana/bing.go b/plugin_diana/bing.go index c0b7ac2f..7e2c1fd7 100644 --- a/plugin_diana/bing.go +++ b/plugin_diana/bing.go @@ -8,25 +8,36 @@ import ( zero "github.com/wdvxdr1123/ZeroBot" + "github.com/FloatTech/ZeroBot-Plugin/control" "github.com/FloatTech/ZeroBot-Plugin/plugin_diana/data" ) +var engine *zero.Engine + func init() { + engine = control.Register("diana", &control.Options{ + DisableOnDefault: false, + Help: "嘉然\n" + + "- @BOT 小作文\n" + + "- @BOT 发大病\n" + + "- @BOT 教你一篇小作文[作文]\n" + + "- [回复]查重", + }) // 随机发送一篇上面的小作文 - zero.OnFullMatch("小作文", zero.OnlyToMe). + engine.OnFullMatch("小作文", zero.OnlyToMe). Handle(func(ctx *zero.Ctx) { rand.Seed(time.Now().UnixNano()) // 绕过第一行发病 ctx.Send((*data.Array)[rand.Intn(len(*data.Array)-1)+1]) }) // 逆天 - zero.OnFullMatch("发大病", zero.OnlyToMe). + engine.OnFullMatch("发大病", zero.OnlyToMe). Handle(func(ctx *zero.Ctx) { // 第一行是发病 ctx.Send((*data.Array)[0]) }) // 增加小作文 - zero.OnRegex(`^教你一篇小作文(.*)$`, zero.AdminPermission). + engine.OnRegex(`^教你一篇小作文(.*)$`, zero.AdminPermission). Handle(func(ctx *zero.Ctx) { err := data.AddText(ctx.State["regex_matched"].([]string)[1]) if err != nil { diff --git a/plugin_diana/data/text.go b/plugin_diana/data/text.go index 12cccd39..e654c7f7 100644 --- a/plugin_diana/data/text.go +++ b/plugin_diana/data/text.go @@ -93,6 +93,8 @@ func LoadText() error { func AddText(txt string) error { sum := md5.Sum(str2bytes(txt)) if txt != "" && !isin(sum) { + m.Lock() + defer m.Unlock() compo.Array = append(compo.Array, txt) md5s = append(md5s, sum) return savecompo() @@ -114,13 +116,10 @@ func savecompo() error { data, err := compo.Marshal() if err == nil { if _, err := os.Stat(datapath); err == nil || os.IsExist(err) { - m.Lock() - defer m.Unlock() f, err1 := os.OpenFile(pbfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) if err1 == nil { _, err2 := f.Write(data) f.Close() - return err2 } return err1 diff --git a/plugin_diana/zhiwang.go b/plugin_diana/zhiwang.go index db5c34da..6ad11dfb 100644 --- a/plugin_diana/zhiwang.go +++ b/plugin_diana/zhiwang.go @@ -28,7 +28,7 @@ type zhiwang struct { // 小作文查重: 回复要查的消息 查重 func init() { - zero.OnMessage(fullmatch("查重")). + engine.OnMessage(fullmatch("查重")). Handle(func(ctx *zero.Ctx) { msg := ctx.Event.Message if msg[0].Type == "reply" { diff --git a/plugin_github/repo_searcher.go b/plugin_github/repo_searcher.go index 036d2185..9a01f22f 100644 --- a/plugin_github/repo_searcher.go +++ b/plugin_github/repo_searcher.go @@ -9,6 +9,7 @@ import ( "net/url" "strings" + "github.com/FloatTech/ZeroBot-Plugin/control" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/message" @@ -16,7 +17,13 @@ import ( ) func init() { // 插件主体 - zero.OnRegex(`^>github\s(-.{1,10}? )?(.*)$`).SetBlock(true).FirstPriority(). + engine := control.Register("github", &control.Options{ + DisableOnDefault: false, + Help: "GitHub仓库搜索\n" + + "- >github [xxx]\n" + + "- >github -p [xxx]", + }) + engine.OnRegex(`^>github\s(-.{1,10}? )?(.*)$`).SetBlock(true).FirstPriority(). Handle(func(ctx *zero.Ctx) { // 发送请求 header := http.Header{ diff --git a/plugin_hs/run.go b/plugin_hs/run.go index cbbc7064..6816ce49 100644 --- a/plugin_hs/run.go +++ b/plugin_hs/run.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "github.com/FloatTech/ZeroBot-Plugin/control" "github.com/imroc/req" "github.com/tidwall/gjson" zero "github.com/wdvxdr1123/ZeroBot" @@ -27,7 +28,15 @@ func init() { if err != nil { panic(err) } - zero.OnRegex(`^搜卡(.+)$`). + + engine := control.Register("hs", &control.Options{ + DisableOnDefault: false, + Help: "炉石\n" + + "- 搜卡[xxxx]\n" + + "- [卡组代码xxx]\n" + + "- 更多搜卡指令参数:https://hs.fbigame.com/misc/searchhelp", + }) + engine.OnRegex(`^搜卡(.+)$`). SetBlock(true).SetPriority(20).Handle(func(ctx *zero.Ctx) { List := ctx.State["regex_matched"].([]string)[1] g := sh(List) @@ -67,7 +76,7 @@ func init() { } }) // 卡组 - zero.OnRegex(`^[\s\S]*?(AAE[a-zA-Z0-9/\+=]{70,})[\s\S]*$`). + engine.OnRegex(`^[\s\S]*?(AAE[a-zA-Z0-9/\+=]{70,})[\s\S]*$`). SetBlock(true).SetPriority(20).Handle(func(ctx *zero.Ctx) { fmt.Print("成功") List := ctx.State["regex_matched"].([]string)[1] diff --git a/plugin_image_finder/keyword.go b/plugin_image_finder/keyword.go index ca739b6f..1c4ae8d0 100644 --- a/plugin_image_finder/keyword.go +++ b/plugin_image_finder/keyword.go @@ -8,6 +8,7 @@ import ( "net/http" "time" + "github.com/FloatTech/ZeroBot-Plugin/control" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/message" ) @@ -59,7 +60,12 @@ type resultjson struct { } func init() { - zero.OnRegex(`^来张 (.*)$`, zero.AdminPermission). + engine := control.Register("imgfinder", &control.Options{ + DisableOnDefault: false, + Help: "关键字搜图\n" + + "- 来张 [xxx]", + }) + engine.OnRegex(`^来张 (.*)$`, zero.AdminPermission). Handle(func(ctx *zero.Ctx) { keyword := ctx.State["regex_matched"].([]string)[1] soutujson := soutuapi(keyword) diff --git a/plugin_setutime/setu_geter.go b/plugin_setutime/setu_geter.go index 0df53efe..c556bda0 100644 --- a/plugin_setutime/setu_geter.go +++ b/plugin_setutime/setu_geter.go @@ -12,6 +12,7 @@ import ( "time" "github.com/FloatTech/AnimeAPI/pixiv" + . "github.com/FloatTech/ZeroBot-Plugin/data" "github.com/sirupsen/logrus" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/extension/rate" @@ -21,7 +22,7 @@ import ( // Pools 图片缓冲池 type imgpool struct { Lock sync.Mutex - DB *sqlite + DB *Sqlite Path string Group int64 List []string @@ -37,7 +38,7 @@ const ( // NewPoolsCache 返回一个缓冲池对象 func newPools() *imgpool { cache := &imgpool{ - DB: &sqlite{DBPath: "data/SetuTime/SetuTime.db"}, + DB: &Sqlite{DBPath: "data/SetuTime/SetuTime.db"}, Path: "data/SetuTime/cache/", Group: 0, List: []string{"涩图", "二次元", "风景", "车万"}, // 可以自己加类别,得自己加图片进数据库 @@ -71,7 +72,7 @@ func newPools() *imgpool { } } for i := range cache.List { - if err := cache.DB.create(cache.List[i], &pixiv.Illust{}); err != nil { + if err := cache.DB.Create(cache.List[i], &pixiv.Illust{}); err != nil { panic(err) } } @@ -97,7 +98,7 @@ func init() { // 插件主体 for i := 0; i < times; i++ { illust := &pixiv.Illust{} // 查询出一张图片 - if err := pool.DB.find(imgtype, illust, "ORDER BY RANDOM() limit 1"); err != nil { + if err := pool.DB.Find(imgtype, illust, "ORDER BY RANDOM() limit 1"); err != nil { ctx.SendChain(message.Text("ERROR: ", err)) continue } @@ -152,7 +153,7 @@ func init() { // 插件主体 return } // 添加插画到对应的数据库table - if err := pool.DB.insert(imgtype, illust); err != nil { + if err := pool.DB.Insert(imgtype, illust); err != nil { ctx.SendChain(message.Text("ERROR: ", err)) return } @@ -166,7 +167,7 @@ func init() { // 插件主体 id, _ = strconv.ParseInt(ctx.State["regex_matched"].([]string)[2], 10, 64) ) // 查询数据库 - if err := pool.DB.del(imgtype, fmt.Sprintf("WHERE pid=%d", id)); err != nil { + if err := pool.DB.Del(imgtype, fmt.Sprintf("WHERE pid=%d", id)); err != nil { ctx.Send(fmt.Sprintf("ERROR: %v", err)) return } @@ -178,7 +179,7 @@ func init() { // 插件主体 Handle(func(ctx *zero.Ctx) { state := []string{"[SetuTime]"} for i := range pool.List { - num, err := pool.DB.count(pool.List[i]) + num, err := pool.DB.Count(pool.List[i]) if err != nil { num = 0 }