Skip to content

Commit

Permalink
✨ 新增插件控制
Browse files Browse the repository at this point in the history
  • Loading branch information
fumiama committed Sep 8, 2021
1 parent be49ba8 commit 087c6c0
Show file tree
Hide file tree
Showing 21 changed files with 355 additions and 48 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
data/SetuTime/cache
data/control
data/SetuTime/search
data/manager
data/acgimage
Expand Down
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@
</div>

## 功能

- **插件控制**
- [x] /启用 xxx
- [x] /禁用 xxx
- [x] /用法 xxx
- [x] /服务列表
- **聊天** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_chat"`
- [x] [BOT名字]
- [x] [戳一戳BOT]
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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] 查询计算机当前活跃度 [身体检查]
- [ ] 简易语音
Expand All @@ -122,6 +128,8 @@
- [x] @Bot 任意文本(任意一句话回复)
- [x] 关闭自动回复
- [x] 启动自动回复
- **关键字搜图** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_image_finder"`
- [x] 来张 [xxx]
- **TODO...**

## 使用方法
Expand Down
14 changes: 14 additions & 0 deletions control/register.go
Original file line number Diff line number Diff line change
@@ -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
}
177 changes: 177 additions & 0 deletions control/rule.go
Original file line number Diff line number Diff line change
@@ -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))
})
}
13 changes: 13 additions & 0 deletions control/tables.go
Original file line number Diff line number Diff line change
@@ -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 // 帮助文本信息
}
53 changes: 39 additions & 14 deletions plugin_setutime/sqlite.go → data/sqlite.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package setutime
package data

import (
"database/sql"
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down Expand Up @@ -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=
Expand Down
Loading

0 comments on commit 087c6c0

Please sign in to comment.