Compare commits

...

46 Commits

Author SHA1 Message Date
fumiama
38935937ae control 增加还原;调整禁用优先级 2021-10-26 00:05:45 +08:00
fumiama
a3685e2e83 ✏️ 尝试解决win下路径异常 2021-10-24 18:13:12 +08:00
fumiama
3a5e391191 修正代码问题 2021-10-23 11:51:32 +08:00
fumiama
09a9dd53fd 修正代码问题 2021-10-23 01:09:15 +08:00
github-actions[bot]
5e064249be 🎨 改进代码样式 2021-10-22 16:55:19 +00:00
fumiama
67555512e7 搜图下载使用animeapi,将文件判存移至utils 2021-10-23 00:54:38 +08:00
fumiama
591df6439c 更新 goreleaser 2021-10-22 11:37:40 +08:00
fumiama
7dfb7dfe24 更新 goreleaser 2021-10-22 11:20:01 +08:00
Kanri
8e56f137b6 ⬆️ 更新依赖 2021-10-22 09:36:11 +08:00
源文雨
3b61c73c17 Update README.md 2021-10-20 22:56:31 +08:00
fumiama
44dac98b37 Merge branch 'master' of https://github.com/FloatTech/ZeroBot-Plugin 2021-10-18 15:25:06 +08:00
fumiama
1a7f98379a ✏️ 修正 acgimage 发图 2021-10-18 15:24:56 +08:00
Kanri
4109ef0612 Update main.go 2021-10-17 23:56:34 +08:00
fumiama
93a9bf6c5b 更新 ZeroBot 到 v1.3.2 2021-10-16 19:07:41 +08:00
fumiama
0b7b35cdcc control 支持全局禁用&个人用户 2021-10-16 14:02:44 +08:00
fumiama
350ef86dd6 ✏️ control 减少 defer 开销 2021-10-16 13:33:12 +08:00
fumiama
2d69ae2e42 ✏️ driver 使用 api 写法 2021-10-16 13:25:13 +08:00
Kanri
e95367f4b2 Merge pull request #70 from Yiwen-Chan/master
⬆️ 更新依赖
2021-10-16 11:11:59 +08:00
Kanri
3101911aa2 ⬆️ 更新依赖 2021-10-16 11:09:26 +08:00
Kanri
ac73087f93 Merge pull request #69 from Yiwen-Chan/master
🎨 ctx.Send -> ctx.SendChain
2021-10-15 22:05:02 +08:00
Kanri
d375a3bbbb 🎨 小修改 2021-10-15 22:02:14 +08:00
Kanri
c46ca1d4c2 🎨 ctx.Send -> ctx.SendChain 2021-10-15 21:43:47 +08:00
fumiama
2a1cca8ebb ✏️ 防止文件名重复 2021-10-15 16:28:31 +08:00
fumiama
d1fdc989b6 ✏️ 防止文件名重复 2021-10-15 16:21:01 +08:00
fumiama
672215f753 ✏️ windows取消arm系 2021-10-15 16:10:58 +08:00
fumiama
4160175fcf ✏️ 修改编译逻辑 2021-10-15 16:02:11 +08:00
fumiama
8f8ba55fc9 ✏️ 改用 gocq 同款 release 2021-10-15 16:00:54 +08:00
fumiama
1dbb4aa837 ✏️ 改用 gocq 同款 release 2021-10-15 15:57:42 +08:00
fumiama
c183c4f17d ✏️ 修正zip缓存位置 2021-10-15 15:27:19 +08:00
fumiama
fa6d14d89a ✏️ 修正zip缓存位置 2021-10-15 15:10:09 +08:00
fumiama
65b92b9da3 更新 README 2021-10-15 14:43:31 +08:00
fumiama
a7056c4601 更新 README 2021-10-14 23:38:52 +08:00
fumiama
1dce0f7859 更新 README 2021-10-14 23:32:49 +08:00
fumiama
bdffbfab67 ✏️ 分离 data 2021-10-14 23:07:13 +08:00
fumiama
98b21d0fdf ✏️ str byte 转换改用 zb 的工具 2021-10-14 19:51:24 +08:00
fumiama
cccea70db1 ✏️ 分离 dyloader 2021-10-14 16:26:01 +08:00
fumiama
d2bcd0bc9f Merge branch 'master' of https://github.com/FloatTech/ZeroBot-Plugin 2021-10-14 13:46:44 +08:00
fumiama
08653fd3b6 🚮 删除多余文件 2021-10-14 13:46:30 +08:00
fumiama
75d0671d9b dyloader 缩小插件体积 2021-10-14 13:45:14 +08:00
fumiama
51ec3c32a9 dyloader 缩小插件体积 2021-10-14 13:44:16 +08:00
fumiama
ec0032c5ab dyloader 移除 win,增加加载插件 2021-10-14 00:06:13 +08:00
fumiama
2723f3662c ✏️ 禁用 dyloader 2021-10-13 18:40:40 +08:00
fumiama
539b050b97 ✏️ 完成插件卸载 2021-10-13 18:39:54 +08:00
fumiama
a0b9623a9f dyloader 增加 win,优化 register 2021-10-13 11:07:34 +08:00
fumiama
6b263418a0 升级 zb 到 v1.3.0 2021-10-13 00:34:43 +08:00
fumiama
92989ce9fd control 增加 Delete 2021-10-12 19:16:01 +08:00
38 changed files with 485 additions and 398 deletions

View File

@@ -1,55 +0,0 @@
name: 测试版
on:
push:
tags:
- p*
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
my-job:
name: Build ZeroBot-Plugin on Push Tag 🚀
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Cache Go
id: cache
uses: actions/cache@v2
with:
# A list of files, directories, and wildcard patterns to cache and restore
path: ~/go/pkg/mod
key: ${{ runner.os }}-build-${{ hashFiles('**/go.sum') }}
- name: Tidy Go modules
run: go mod tidy
- name: Build linux-x64
run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-x64
- name: Build linux-x86
run: CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-x86
- name: Build windows-x64
run: CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-windows-x64.exe
- name: Build windows-x86
run: CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-windows-x86.exe
- name: Build arm64
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=7 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-arm64
- name: Build armv6
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-armv6
- name: Upload binaries to release
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: artifacts/zerobot-plugin-*
tag: ${{ github.ref }}
overwrite: true
file_glob: true

View File

@@ -1,55 +1,27 @@
name: 稳定版
name: compile
on:
push:
tags:
- v*
env:
GITHUB_TOKEN: ${{ github.token }}
- 'v*'
jobs:
my-job:
name: Build ZeroBot-Plugin on Push Tag 🚀
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
go-version: '1.17'
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Cache Go
id: cache
uses: actions/cache@v2
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
# A list of files, directories, and wildcard patterns to cache and restore
path: ~/go/pkg/mod
key: ${{ runner.os }}-build-${{ hashFiles('**/go.sum') }}
- name: Tidy Go modules
run: go mod tidy
- name: Build linux-x64
run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-x64
- name: Build linux-x86
run: CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-x86
- name: Build windows-x64
run: CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-windows-x64.exe
- name: Build windows-x86
run: CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-windows-x86.exe
- name: Build arm64
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=7 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-arm64
- name: Build armv6
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags="-s -w" -o artifacts/zerobot-plugin-linux-armv6
- name: Upload binaries to release
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: artifacts/zerobot-plugin-*
tag: ${{ github.ref }}
overwrite: true
file_glob: true
version: latest
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

2
.gitignore vendored
View File

@@ -6,8 +6,10 @@ data/acgimage
data/fortune
data/hs
plugins/*.so
plugins/*.dll
.idea/
.DS_Store
.vscode
go-zero*
nohup.out
zerobot

79
.goreleaser.yml Normal file
View File

@@ -0,0 +1,79 @@
project_name: zbp
env:
- GO111MODULE=on
before:
hooks:
- go mod tidy
builds:
- id: nowin
env:
- CGO_ENABLED=0
- GO111MODULE=on
goos:
- linux
- darwin
goarch:
- 386
- amd64
- arm
- arm64
goarm:
- 6
- 7
ignore:
- goos: darwin
goarch: arm
- goos: darwin
goarch: 386
mod_timestamp: "{{ .CommitTimestamp }}"
flags:
- -trimpath
ldflags:
- -s -w
- id: win
env:
- CGO_ENABLED=0
- GO111MODULE=on
goos:
- windows
goarch:
- 386
- amd64
mod_timestamp: "{{ .CommitTimestamp }}"
flags:
- -trimpath
ldflags:
- -s -w
checksum:
name_template: "zbp_checksums.txt"
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
- fix typo
- Merge pull request
- Merge branch
- Merge remote-tracking
- go mod tidy
archives:
- id: nowin
builds:
- nowin
- win
name_template: "zbp_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
format_overrides:
- goos: windows
format: zip
nfpms:
- license: GPL 3.0
homepage: https://github.com/FloatTech/ZeroBot-Plugin
file_name_template: "zbp_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
formats:
- deb
- rpm
maintainer: FloatTech

View File

@@ -10,9 +10,9 @@
[![OICQ](https://img.shields.io/badge/OneBot-OICQ-green.svg?style=social&logo=appveyor)](https://github.com/takayama-lily/node-onebot)
[![MIRAI](https://img.shields.io/badge/OneBot-Mirai-green.svg?style=social&logo=appveyor)](https://github.com/yyuueexxiinngg/onebot-kotlin)
[![Go Report Card](https://goreportcard.com/badge/github.com/Yiwen-Chan/ZeroBot-Plugin?style=flat-square&logo=go)](https://goreportcard.com/report/github.com/github.com/Yiwen-Chan/ZeroBot-Plugin)
[![Go Report Card](https://goreportcard.com/badge/github.com/FloatTech/ZeroBot-Plugin?style=flat-square&logo=go)](https://goreportcard.com/report/github.com/github.com/FloatTech/ZeroBot-Plugin)
[![Badge](https://img.shields.io/badge/onebot-v11-black?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAMAAADxPgR5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRF////29vbr6+vAAAAk1hCcwAAAAR0Uk5T////AEAqqfQAAAKcSURBVHja7NrbctswDATQXfD//zlpO7FlmwAWIOnOtNaTM5JwDMa8E+PNFz7g3waJ24fviyDPgfhz8fHP39cBcBL9KoJbQUxjA2iYqHL3FAnvzhL4GtVNUcoSZe6eSHizBcK5LL7dBr2AUZlev1ARRHCljzRALIEog6H3U6bCIyqIZdAT0eBuJYaGiJaHSjmkYIZd+qSGWAQnIaz2OArVnX6vrItQvbhZJtVGB5qX9wKqCMkb9W7aexfCO/rwQRBzsDIsYx4AOz0nhAtWu7bqkEQBO0Pr+Ftjt5fFCUEbm0Sbgdu8WSgJ5NgH2iu46R/o1UcBXJsFusWF/QUaz3RwJMEgngfaGGdSxJkE/Yg4lOBryBiMwvAhZrVMUUvwqU7F05b5WLaUIN4M4hRocQQRnEedgsn7TZB3UCpRrIJwQfqvGwsg18EnI2uSVNC8t+0QmMXogvbPg/xk+Mnw/6kW/rraUlvqgmFreAA09xW5t0AFlHrQZ3CsgvZm0FbHNKyBmheBKIF2cCA8A600aHPmFtRB1XvMsJAiza7LpPog0UJwccKdzw8rdf8MyN2ePYF896LC5hTzdZqxb6VNXInaupARLDNBWgI8spq4T0Qb5H4vWfPmHo8OyB1ito+AysNNz0oglj1U955sjUN9d41LnrX2D/u7eRwxyOaOpfyevCWbTgDEoilsOnu7zsKhjRCsnD/QzhdkYLBLXjiK4f3UWmcx2M7PO21CKVTH84638NTplt6JIQH0ZwCNuiWAfvuLhdrcOYPVO9eW3A67l7hZtgaY9GZo9AFc6cryjoeFBIWeU+npnk/nLE0OxCHL1eQsc1IciehjpJv5mqCsjeopaH6r15/MrxNnVhu7tmcslay2gO2Z1QfcfX0JMACG41/u0RrI9QAAAABJRU5ErkJggg==)](https://github.com/howmanybots/onebot)
[![Badge](https://img.shields.io/badge/zerobot-v1.2.3-black?style=flat-square&logo=go)](https://github.com/wdvxdr1123/ZeroBot)
[![Badge](https://img.shields.io/badge/zerobot-v1.3.2-black?style=flat-square&logo=go)](https://github.com/wdvxdr1123/ZeroBot)
[![License](https://img.shields.io/github/license/Yiwen-Chan/OneBot-YaYa.svg?style=flat-square&logo=gnu)](https://raw.githubusercontent.com/FloatTech/ZeroBot-Plugin/master/LICENSE)
[![qq group](https://img.shields.io/badge/group-1048452984-red?style=flat-square&logo=tencent-qq)](https://jq.qq.com/?_wv=1027&k=QMb7x1mM)
@@ -32,21 +32,17 @@ zerobot -h -t token -u url [-d|w] [-g] qq1 qq2 qq3 ...
## 功能
> 在编译时,以下功能除插件控制外,均可通过注释`main.go`中的相应`import`而物理禁用,减小插件体积。
> 通过插件控制,还可动态管理某个功能在某个群的打开/关闭。
- **web管理**
- 因为开启后可执行文件大约增加 5M ,默认注释不开启。
- **web管理** `import _ "github.com/FloatTech/ZeroBot-Plugin/control/web"`
- 开启后可执行文件大约增加 5M ,默认注释不开启。如需开启请自行编辑`main.go`取消注释
- 需要配合 [webgui](https://github.com/FloatTech/bot-manager) 使用
- **动态加载插件**
- [x] /刷新插件
- 仅 Linux, FreeBSD, macOS 可用,默认注释不开启。
- 开启后`zbp`可执行文件约增大 2M ,每个插件的`.so`文件约 4 ~ 20 M ,如非必要建议不开启。
- 动态加载的插件需放置在`plugins/`下,编译命令如下。插件包名必须为`main`
```bash
go build -ldflags "-s -w" -buildmode=plugin
```
- 插件一经加载,无法再卸载,只能通过`control`控制。
- **动态加载插件** `import _ github.com/FloatTech/ZeroBot-Plugin-Dynamic/dyloader`
- 本功能需要`cgo`,故已分离出主线。详见[ZeroBot-Plugin-Dynamic](https://github.com/FloatTech/ZeroBot-Plugin-Dynamic)
- **插件控制**
- [x] /启用 xxx
- [x] /禁用 xxx
- [x] /启用 xxx (在发送的群/用户启用xxx)
- [x] /禁用 xxx (在发送的群/用户禁用xxx)
- [x] /全局启用 xxx
- [x] /全局禁用 xxx
- [x] /还原 xxx (在发送的群/用户还原xxx的开启状态到初始状态)
- [x] /用法 xxx
- [x] /服务列表
- **聊天** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_chat"`
@@ -126,10 +122,10 @@ zerobot -h -t token -u url [-d|w] [-g] qq1 qq2 qq3 ...
- [x] 设置随机图片网址[url]
- [x] 太涩了(撤回最近发的图)
- [x] 评价图片(发送一张图片让bot评分)
- **每日运势** `github.com/FloatTech/ZeroBot-Plugin/plugin_fortune`
- **每日运势** `import _ github.com/FloatTech/ZeroBot-Plugin/plugin_fortune`
- [x] 运势|抽签
- [x] 设置底图[车万 DC4 爱因斯坦 星空列车 樱云之恋 富婆妹 李清歌 公主连结 原神 明日方舟 碧蓝航线 碧蓝幻想 战双 阴阳师]
- **浅草寺求签** `github.com/FloatTech/ZeroBot-Plugin/plugin_omikuji`
- **浅草寺求签** `import _ github.com/FloatTech/ZeroBot-Plugin/plugin_omikuji`
- [x] 求签|占卜
- **bilibili** `import _ "github.com/FloatTech/ZeroBot-Plugin/plugin_bilibili"`
- [x] >vup info [名字|uid]
@@ -184,7 +180,7 @@ zerobot -h -t token -u url [-d|w] [-g] qq1 qq2 qq3 ...
### 本地运行
1. 下载安装 [Go](https://studygolang.com/dl) 环境
2. 下载本项目[压缩包](https://github.com/Yiwen-Chan/ZeroBot-Plugin/archive/master.zip),本地解压
2. 下载本项目[压缩包](https://github.com/FloatTech/ZeroBot-Plugin/archive/master.zip),本地解压
3. 编辑 main.go 文件,内容按需修改
4. 双击 build.bat 文件 或 直接双击 run.bat 文件
5. 运行 OneBot 框架,并同时运行本插件
@@ -236,4 +232,4 @@ GOOS=linux GOARCH=mips GOMIPS=softfloat CGO_ENABLED=0 go build -ldflags "-s -w"
## License
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FYiwen-Chan%2FZeroBot-Plugin.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FYiwen-Chan%2FZeroBot-Plugin?ref=badge_large)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FFloatTech%2FZeroBot-Plugin.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FFloatTech%2FZeroBot-Plugin?ref=badge_large)

View File

@@ -4,9 +4,28 @@ import (
zero "github.com/wdvxdr1123/ZeroBot"
)
var enmap = make(map[string]*zero.Engine)
// Register 注册插件控制器
func Register(service string, o *Options) *zero.Engine {
engine := zero.New()
engine.UsePreHandler(newctrl(service, o).Handler())
enmap[service] = engine
return engine
}
// Delete 删除插件控制器,不会删除数据
func Delete(service string) {
engine, ok := enmap[service]
if ok {
engine.Delete()
mu.RLock()
_, ok = managers[service]
mu.RUnlock()
if ok {
mu.Lock()
delete(managers, service)
mu.Unlock()
}
}
}

View File

@@ -4,6 +4,7 @@ package control
import (
"os"
"strconv"
"strings"
"sync"
"github.com/sirupsen/logrus"
@@ -11,11 +12,11 @@ import (
"github.com/wdvxdr1123/ZeroBot/extension"
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/data"
"github.com/FloatTech/ZeroBot-Plugin/utils/sql"
)
var (
db = &data.Sqlite{DBPath: "data/control/plugins.db"}
db = &sql.Sqlite{DBPath: "data/control/plugins.db"}
// managers 每个插件对应的管理
managers = map[string]*Control{}
mu = sync.RWMutex{}
@@ -40,8 +41,8 @@ func newctrl(service string, o *Options) *Control {
}(),
}
mu.Lock()
defer mu.Unlock()
managers[service] = m
mu.Unlock()
err := db.Create(service, &grpcfg{})
if err != nil {
panic(err)
@@ -50,40 +51,59 @@ func newctrl(service string, o *Options) *Control {
}
// Enable enables a group to pass the Manager.
// groupID == 0 (ALL) will operate on all grps.
func (m *Control) Enable(groupID int64) {
m.Lock()
err := db.Insert(m.service, &grpcfg{groupID, 0})
m.Unlock()
if err != nil {
logrus.Errorf("[control] %v", err)
}
m.Unlock()
}
// Disable disables a group to pass the Manager.
// groupID == 0 (ALL) will operate on all grps.
func (m *Control) Disable(groupID int64) {
m.Lock()
err := db.Insert(m.service, &grpcfg{groupID, 1})
m.Unlock()
if err != nil {
logrus.Errorf("[control] %v", err)
}
m.Unlock()
}
func (m *Control) IsEnabledIn(gid int64) bool {
m.RLock()
var c grpcfg
err := db.Find(m.service, &c, "WHERE gid = "+strconv.FormatInt(gid, 10))
if err == nil {
m.RUnlock()
logrus.Debugf("[control] plugin %s of grp %d : %d", m.service, c.GroupID, c.Disable)
return c.Disable == 0
// Reset resets the default config of a group.
// groupID == 0 (ALL) is not allowed.
func (m *Control) Reset(groupID int64) {
if groupID != 0 {
m.Lock()
err := db.Del(m.service, "WHERE gid = "+strconv.FormatInt(groupID, 10))
m.Unlock()
if err != nil {
logrus.Errorf("[control] %v", err)
}
}
logrus.Errorf("[control] %v", err)
}
// IsEnabledIn 开启群
func (m *Control) IsEnabledIn(gid int64) bool {
var c grpcfg
var err error
if gid != 0 {
m.RLock()
err = db.Find(m.service, &c, "WHERE gid = "+strconv.FormatInt(gid, 10))
m.RUnlock()
if err == nil {
logrus.Debugf("[control] plugin %s of grp %d : %d", m.service, c.GroupID, c.Disable)
return c.Disable == 0
}
}
m.RLock()
err = db.Find(m.service, &c, "WHERE gid = 0")
m.RUnlock()
if m.options.DisableOnDefault {
m.Disable(gid)
} else {
m.Enable(gid)
if err == nil {
logrus.Debugf("[control] plugin %s of all : %d", m.service, c.GroupID, c.Disable)
return c.Disable == 0
}
return !m.options.DisableOnDefault
}
@@ -92,7 +112,12 @@ func (m *Control) IsEnabledIn(gid int64) bool {
func (m *Control) Handler() zero.Rule {
return func(ctx *zero.Ctx) bool {
ctx.State["manager"] = m
return m.IsEnabledIn(ctx.Event.GroupID)
grp := ctx.Event.GroupID
if grp == 0 {
// 个人用户
grp = -ctx.Event.UserID
}
return m.IsEnabledIn(grp)
}
}
@@ -100,8 +125,8 @@ func (m *Control) Handler() zero.Rule {
// not exist, it will returns nil.
func Lookup(service string) (*Control, bool) {
mu.RLock()
defer mu.RUnlock()
m, ok := managers[service]
mu.RUnlock()
return m, ok
}
@@ -134,29 +159,58 @@ func init() {
panic(err)
} else {
hasinit = true
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{
"启用", "enable", "禁用", "disable",
"全局启用", "enableall", "全局禁用", "disableall",
}, func(ctx *zero.Ctx) bool {
if zero.OnlyGroup(ctx) {
return zero.AdminPermission(ctx)
}
return zero.OnlyToMe(ctx)
}).Handle(func(ctx *zero.Ctx) {
model := extension.CommandModel{}
_ = ctx.Parse(&model)
service, ok := Lookup(model.Args)
if !ok {
ctx.SendChain(message.Text("没有找到指定服务!"))
}
grp := ctx.Event.GroupID
if grp == 0 {
// 个人用户
grp = -ctx.Event.UserID
}
if strings.Contains(model.Command, "全局") || strings.Contains(model.Command, "all") {
grp = 0
}
if strings.Contains(model.Command, "启用") || strings.Contains(model.Command, "enable") {
service.Enable(grp)
ctx.SendChain(message.Text("已启用服务: " + model.Args))
} else {
service.Disable(grp)
ctx.SendChain(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{"还原", "reset"}, func(ctx *zero.Ctx) bool {
if zero.OnlyGroup(ctx) {
return zero.AdminPermission(ctx)
}
return zero.OnlyToMe(ctx)
}).Handle(func(ctx *zero.Ctx) {
model := extension.CommandModel{}
_ = ctx.Parse(&model)
service, ok := Lookup(model.Args)
if !ok {
ctx.SendChain(message.Text("没有找到指定服务!"))
}
grp := ctx.Event.GroupID
if grp == 0 {
// 个人用户
grp = -ctx.Event.UserID
}
service.Reset(grp)
ctx.SendChain(message.Text("已还原服务的默认启用状态: " + model.Args))
})
zero.OnCommandGroup([]string{"用法", "usage"}, zero.AdminPermission, zero.OnlyGroup).
Handle(func(ctx *zero.Ctx) {
@@ -164,12 +218,12 @@ func init() {
_ = ctx.Parse(&model)
service, ok := Lookup(model.Args)
if !ok {
ctx.Send("没有找到指定服务!")
ctx.SendChain(message.Text("没有找到指定服务!"))
}
if service.options.Help != "" {
ctx.Send(service.options.Help)
ctx.SendChain(message.Text(service.options.Help))
} else {
ctx.Send("该服务无帮助!")
ctx.SendChain(message.Text("该服务无帮助!"))
}
})
@@ -187,7 +241,7 @@ func init() {
}
return true
})
ctx.Send(message.Text(msg))
ctx.SendChain(message.Text(msg))
})
}
}

View File

@@ -1,17 +0,0 @@
package data
// min 返回两数最大值,该函数将被内联
func Max(a, b int) int {
if a > b {
return a
}
return b
}
// min 返回两数最小值,该函数将被内联
func Min(a, b int) int {
if a > b {
return b
}
return a
}

View File

@@ -1,15 +0,0 @@
package data
import "unsafe"
// Str2bytes Fast convert
func Str2bytes(s string) []byte {
x := (*[2]uintptr)(unsafe.Pointer(&s))
h := [3]uintptr{x[0], x[1], x[1]}
return *(*[]byte)(unsafe.Pointer(&h))
}
// Bytes2str Fast convert
func Bytes2str(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

View File

@@ -1,49 +0,0 @@
//go:build !windows
// +build !windows
package dyloader
import (
"io/fs"
"path/filepath"
"plugin"
"strings"
"github.com/sirupsen/logrus"
zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/message"
)
func init() {
_ = scan()
zero.OnCommand("刷新插件", zero.SuperUserPermission).SetBlock(true).FirstPriority().
Handle(func(ctx *zero.Ctx) {
err := scan()
if err != nil {
ctx.SendChain(message.Text("Error: " + err.Error()))
}
})
}
func scan() error {
return filepath.WalkDir("plugins/", load)
}
func load(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if strings.HasSuffix(d.Name(), ".so") {
_, err = plugin.Open(path)
if err == nil {
logrus.Infoln("[dyloader]加载插件", path, "成功")
}
if err != nil {
logrus.Errorln("[dyloader]加载插件", path, "错误:", err)
}
}
return nil
}

View File

@@ -1,4 +0,0 @@
//go:build windows
// +build windows
package dyloader

8
go.mod
View File

@@ -3,8 +3,8 @@ module github.com/FloatTech/ZeroBot-Plugin
go 1.16
require (
github.com/FloatTech/AnimeAPI v1.1.9
github.com/FloatTech/ZeroBot-Plugin-Gif v0.2.3
github.com/FloatTech/AnimeAPI v1.1.10
github.com/FloatTech/ZeroBot-Plugin-Gif v0.2.4
github.com/FloatTech/ZeroBot-Plugin-Timer v1.4.3
github.com/FloatTech/bot-manager v1.0.0
github.com/fogleman/gg v1.3.0
@@ -16,7 +16,7 @@ require (
github.com/robfig/cron v1.2.0
github.com/shirou/gopsutil v3.21.9+incompatible
github.com/sirupsen/logrus v1.8.1
github.com/tidwall/gjson v1.9.3
github.com/wdvxdr1123/ZeroBot v1.2.4
github.com/tidwall/gjson v1.10.0
github.com/wdvxdr1123/ZeroBot v1.3.2
modernc.org/sqlite v1.13.1
)

19
go.sum
View File

@@ -1,8 +1,9 @@
github.com/FloatTech/AnimeAPI v1.1.9 h1:H1hZmgwZPNHdx39K9JvY3awT8TTsCl9kKA1uVMyCjRg=
github.com/FloatTech/AnimeAPI v1.1.9/go.mod h1:CC+vF30UGBlcIUxwFOcXIEHoJ4r7c5x2iLQsnUCVdDI=
github.com/FloatTech/AnimeAPI v1.1.10 h1:fYkv65P1HBukHi3GpzYulGx/xLshEL9635QXALDryf0=
github.com/FloatTech/AnimeAPI v1.1.10/go.mod h1:CC+vF30UGBlcIUxwFOcXIEHoJ4r7c5x2iLQsnUCVdDI=
github.com/FloatTech/ZeroBot-Plugin v1.1.5/go.mod h1:kWuUARvU7gs4xLggi8Sy37ja2GRL6k0X6kewe5TiZRs=
github.com/FloatTech/ZeroBot-Plugin-Gif v0.2.3 h1:TGQHhiPR/XIxYYoB6IxOzgMhsZs2tDYQlaJHT04gkQ8=
github.com/FloatTech/ZeroBot-Plugin-Gif v0.2.3/go.mod h1:W7ag6hml1pZTNzRXKU74OMr6rS8awQKSU+o2g7Gj4O0=
github.com/FloatTech/ZeroBot-Plugin-Gif v0.2.4 h1:WW0BmmLLqAg+m6qGkrKbsfSIm91fkj3/udt3R7Myodo=
github.com/FloatTech/ZeroBot-Plugin-Gif v0.2.4/go.mod h1:W7ag6hml1pZTNzRXKU74OMr6rS8awQKSU+o2g7Gj4O0=
github.com/FloatTech/ZeroBot-Plugin-Timer v1.4.3 h1:jn/dH+OwPSRozkmeCeQQPrAGJRBudcm3OK5tXhGItRk=
github.com/FloatTech/ZeroBot-Plugin-Timer v1.4.3/go.mod h1:MVOQQ4e6AVGFm993blXXU4Sd6bAsLY2+Zb+/HMrEeEc=
github.com/FloatTech/bot-manager v1.0.0 h1:d63J5htLhVBc2ITG09WBJI+qAB0ubPjYhfXl6hljBNk=
@@ -88,7 +89,6 @@ github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6O
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ=
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/shirou/gopsutil v3.21.8+incompatible h1:sh0foI8tMRlCidUJR+KzqWYWxrkuuPIGiO6Vp+KXdCU=
github.com/shirou/gopsutil v3.21.8+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shirou/gopsutil v3.21.9+incompatible h1:LTLpUnfX81MkHeCtSrwNKZwuW5Id6kCa7/P43NdcNn4=
github.com/shirou/gopsutil v3.21.9+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
@@ -107,15 +107,12 @@ github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816/go
github.com/tdf1939/ZeroBot-Plugin-Gif v0.0.0-20210828060956-389b1dc33652/go.mod h1:bkxKi7un9gCDvUUZAiIJF6k90pyj8rmxiXLJkiHcsMY=
github.com/tdf1939/img v0.0.0-20210827153520-90cb4e9580a3/go.mod h1:FgTEOcosTWrkOr7++gbtPSj1rX5loRWrf/AL+hm3Cnw=
github.com/tidwall/gjson v1.8.0/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/gjson v1.9.0 h1:+Od7AE26jAaMgVC31cQV/Ope5iKXulNMflrlB7k+F9E=
github.com/tidwall/gjson v1.9.0/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/gjson v1.9.3 h1:hqzS9wAHMO+KVBBkLxYdkEeeFHuqr95GfClRLKlgK0E=
github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
github.com/tidwall/gjson v1.10.0 h1:FcpcxUhNwjb4ppKSlz5Bv8V1jc9ncrVAySohlNBrPUk=
github.com/tidwall/gjson v1.10.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8=
github.com/tidwall/pretty v1.1.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
@@ -129,8 +126,9 @@ github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/wdvxdr1123/ZeroBot v1.2.2/go.mod h1:83nHtG8V5TAxPwH/LCDxLpZk4khIgs29dkr5TBWf7fc=
github.com/wdvxdr1123/ZeroBot v1.2.3/go.mod h1:83nHtG8V5TAxPwH/LCDxLpZk4khIgs29dkr5TBWf7fc=
github.com/wdvxdr1123/ZeroBot v1.2.4 h1:eC/41Tlkj1jxXW91x4K+qjUlaQXKGgUeLhxw7C6+qkM=
github.com/wdvxdr1123/ZeroBot v1.2.4/go.mod h1:83nHtG8V5TAxPwH/LCDxLpZk4khIgs29dkr5TBWf7fc=
github.com/wdvxdr1123/ZeroBot v1.3.2 h1:EFZNb3awNbwxRtmDkWv3PH6Z9rUV6ZLFa3hBmRMRRCA=
github.com/wdvxdr1123/ZeroBot v1.3.2/go.mod h1:i2DIqQjtjE+3gvVi9r9sc+QpNaUuyTXx/HNXXayIpwI=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
@@ -221,7 +219,6 @@ modernc.org/memory v1.0.5 h1:XRch8trV7GgvTec2i7jc33YlUI0RKVDBvZ5eZ5m8y14=
modernc.org/memory v1.0.5/go.mod h1:B7OYswTRnfGg+4tDH1t1OeUNnsy2viGTdME4tzd+IjM=
modernc.org/opt v0.1.1 h1:/0RX92k9vwVeDXj+Xn23DKp2VJubL7k8qNffND6qn3A=
modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sqlite v1.13.0 h1:cwhUj0jTBgPjk/demWheV+T6xi6ifTfsGIFKFq0g3Ck=
modernc.org/sqlite v1.13.0/go.mod h1:2qO/6jZJrcQaxFUHxOwa6Q6WfiGSsiVj6GXX0Ker+Jg=
modernc.org/sqlite v1.13.1 h1:s/qk6VTTVyQIyhVNWa50whBBcI3+2oREbx85t227iOo=
modernc.org/sqlite v1.13.1/go.mod h1:2qO/6jZJrcQaxFUHxOwa6Q6WfiGSsiVj6GXX0Ker+Jg=

21
main.go
View File

@@ -10,7 +10,7 @@ import (
// 下列插件可与 wdvxdr1123/ZeroBot v1.1.2 以上配合单独使用
// 插件控制
//_ "github.com/FloatTech/ZeroBot-Plugin/control/web" // web 后端控制
// _ "github.com/FloatTech/ZeroBot-Plugin/control/web" // web 后端控制
// 词库类
_ "github.com/FloatTech/ZeroBot-Plugin/plugin_atri" // ATRI词库
@@ -51,14 +51,14 @@ import (
"github.com/sirupsen/logrus"
zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/driver"
//_ "github.com/FloatTech/ZeroBot-Plugin/dyloader"
"github.com/wdvxdr1123/ZeroBot/message"
)
var (
contents = []string{
"* OneBot + ZeroBot + Golang",
"* Version 1.1.6 - 2021-10-09 12:50:23 +0800 CST",
"* Copyright © 2020 - 2021 Kanri, DawnNights, Fumiama, Suika",
"* Version 1.1.7 - 2021-10-09 12:50:23 +0800 CST",
"* Copyright © 2020 - 2021 FloatTech. All Rights Reserved.",
"* Project: https://github.com/FloatTech/ZeroBot-Plugin",
}
banner = strings.Join(contents, "\n")
@@ -104,25 +104,20 @@ func main() {
zero.Run(zero.Config{
NickName: []string{"椛椛", "ATRI", "atri", "亚托莉", "アトリ"},
CommandPrefix: "/",
// SuperUsers 某些功能需要主人权限,可通过以下两种方式修改
// []string{}:通过代码写死的方式添加主人账号
// flag.Args():通过命令行参数的方式添加主人账号
SuperUsers: append([]string{"12345678", "87654321"}, flag.Args()...),
Driver: []zero.Driver{
&driver.WSClient{
// OneBot 正向WS 默认使用 6700 端口
Url: *url,
AccessToken: *token,
},
driver.NewWebSocketClient(*url, *token),
},
})
},
)
// 帮助
zero.OnFullMatchGroup([]string{"/help", ".help", "菜单"}, zero.OnlyToMe).SetBlock(true).FirstPriority().
Handle(func(ctx *zero.Ctx) {
ctx.Send(banner)
ctx.SendChain(message.Text(banner))
})
select {}
}

View File

@@ -3,7 +3,6 @@ package acgimage
import (
"net/url"
"os"
"strconv"
"strings"
@@ -13,6 +12,7 @@ import (
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
)
const (
@@ -21,9 +21,8 @@ const (
)
var (
botpath, _ = os.Getwd()
datapath = botpath + "/data/acgimage/"
cacheuri = "file:///" + datapath + "cache"
datapath = file.BOT_PATH + "/data/acgimage/"
cacheuri = "file:///" + datapath + "cache"
// r18有一定保护一般不会发出图片
randapi = "&loli=true&r18=true"
msgof = make(map[int64]int64)
@@ -46,10 +45,10 @@ func init() { // 插件主体
Handle(func(ctx *zero.Ctx) {
url := ctx.State["regex_matched"].([]string)[1]
if !strings.HasPrefix(url, "http") {
ctx.Send("URL非法!")
ctx.SendChain(message.Text("URL非法!"))
} else {
randapi = url
ctx.Send("设置好啦")
ctx.SendChain(message.Text("设置好啦"))
}
})
// 有保护的随机图片
@@ -61,14 +60,14 @@ func init() { // 插件主体
replyClass(ctx, dhash, class, false, lastvisit, comment)
}()
} else {
ctx.Send("你太快啦!")
ctx.SendChain(message.Text("你太快啦!"))
}
})
// 直接随机图片无r18保护后果自负。如果出r18图可尽快通过发送"太涩了"撤回
engine.OnFullMatch("直接随机", zero.OnlyGroup, zero.AdminPermission).SetBlock(true).SetPriority(24).
Handle(func(ctx *zero.Ctx) {
if block {
ctx.Send("请稍后再试哦")
ctx.SendChain(message.Text("请稍后再试哦"))
} else if randapi != "" {
block = true
var url string
@@ -77,7 +76,7 @@ func init() { // 插件主体
} else {
url = randapi
}
setLastMsg(ctx.Event.GroupID, ctx.Send(message.Image(url).Add("cache", "0")))
setLastMsg(ctx.Event.GroupID, ctx.SendChain(message.Image(url).Add("cache", "0")))
block = false
}
})
@@ -89,7 +88,7 @@ func init() { // 插件主体
// 上传一张图进行评价
engine.OnKeywordGroup([]string{"评价图片"}, zero.OnlyGroup, picture.CmdMatch, picture.MustGiven).SetBlock(true).SetPriority(24).
Handle(func(ctx *zero.Ctx) {
ctx.Send("少女祈祷中...")
ctx.SendChain(message.Text("少女祈祷中..."))
for _, url := range ctx.State["image_url"].([]string) {
go func(target string) {
class, lastvisit, dhash, comment := classify.Classify(target, true)
@@ -101,7 +100,7 @@ func init() { // 插件主体
Handle(func(ctx *zero.Ctx) {
dhash := ctx.State["regex_matched"].([]string)[1]
if len(dhash) == 5*3 {
ctx.Send(message.Image(apihead + dhash))
ctx.SendChain(message.Image(apihead + dhash))
}
})
}
@@ -124,19 +123,18 @@ func replyClass(ctx *zero.Ctx, dhash string, class int, noimg bool, lv int64, co
if dhash != "" && !noimg {
b14, err3 := url.QueryUnescape(dhash)
if err3 == nil {
ctx.Send(comment + "\n给你点提示哦" + b14)
ctx.SendChain(message.Text(comment + "\n给你点提示哦" + b14))
ctx.Event.GroupID = 0
ctx.Send(img)
ctx.SendChain(img)
}
} else {
ctx.Send(comment)
ctx.SendChain(message.Text(comment))
}
} else {
comment := message.Text(comment)
if !noimg {
ctx.SendChain(img, comment)
ctx.SendChain(img, message.Text(comment))
} else {
ctx.SendChain(message.Reply(ctx.Event.MessageID), comment)
ctx.SendChain(message.Reply(ctx.Event.MessageID), message.Text(comment))
}
}
}

View File

@@ -35,9 +35,9 @@ func init() { // 插件主体
Handle(func(ctx *zero.Ctx) {
err := os.RemoveAll("data/cache/*")
if err != nil {
ctx.Send("错误: " + err.Error())
ctx.SendChain(message.Text("错误: ", err.Error()))
} else {
ctx.Send("成功!")
ctx.SendChain(message.Text("成功!"))
}
})
}

View File

@@ -12,17 +12,16 @@ import (
"github.com/FloatTech/ZeroBot-Plugin/control"
)
var engine *zero.Engine
var engine = control.Register("bilibili", &control.Options{
DisableOnDefault: false,
Help: "bilibili\n" +
"- >vup info [名字|uid]\n" +
"- >user info [名字|uid]\n" +
"- /开启粉丝日报",
})
// 查成分的
func init() {
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})$`).SetBlock(true).
Handle(func(ctx *zero.Ctx) {
keyword := ctx.State["regex_matched"].([]string)[1]

View File

@@ -2,11 +2,11 @@
package diana
import (
fmt "fmt"
"math/rand"
"time"
zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/plugin_diana/data"
@@ -28,22 +28,22 @@ func init() {
Handle(func(ctx *zero.Ctx) {
rand.Seed(time.Now().UnixNano())
// 绕过第一行发病
ctx.Send((*data.Array)[rand.Intn(len(*data.Array)-1)+1])
ctx.SendChain(message.Text((*data.Array)[rand.Intn(len(*data.Array)-1)+1]))
})
// 逆天
engine.OnFullMatch("发大病").SetBlock(true).
Handle(func(ctx *zero.Ctx) {
// 第一行是发病
ctx.Send((*data.Array)[0])
ctx.SendChain(message.Text((*data.Array)[0]))
})
// 增加小作文
engine.OnRegex(`^教你一篇小作文(.*)$`, zero.AdminPermission).SetBlock(true).
Handle(func(ctx *zero.Ctx) {
err := data.AddText(ctx.State["regex_matched"].([]string)[1])
if err != nil {
ctx.Send(fmt.Sprintf("ERROR: %v", err))
ctx.SendChain(message.Text("ERROR: ", err))
} else {
ctx.Send("记住啦!")
ctx.SendChain(message.Text("记住啦!"))
}
})
}

View File

@@ -3,6 +3,7 @@ package data
import (
"crypto/md5"
"errors"
"io"
"net/http"
"os"
@@ -10,8 +11,9 @@ import (
"time"
log "github.com/sirupsen/logrus"
"github.com/wdvxdr1123/ZeroBot/utils/helper"
"github.com/FloatTech/ZeroBot-Plugin/data"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
)
const (
@@ -43,7 +45,7 @@ func init() {
log.Printf("[Diana]读取%d条小作文", arrl)
md5s = make([]*[16]byte, arrl)
for i, t := range *Array {
m := md5.Sum(data.Str2bytes(t))
m := md5.Sum(helper.StringToBytes(t))
md5s[i] = &m
}
} else {
@@ -54,7 +56,7 @@ func init() {
// LoadText 加载小作文
func LoadText() error {
if _, err := os.Stat(pbfile); err == nil || os.IsExist(err) {
if file.IsExist(pbfile) {
f, err := os.Open(pbfile)
if err == nil {
defer f.Close()
@@ -93,7 +95,7 @@ func LoadText() error {
// AddText 添加小作文
func AddText(txt string) error {
sum := md5.Sum(data.Str2bytes(txt))
sum := md5.Sum(helper.StringToBytes(txt))
if txt != "" && !isin(&sum) {
m.Lock()
defer m.Unlock()
@@ -117,7 +119,7 @@ func isin(sum *[16]byte) bool {
func savecompo() error {
data, err := compo.Marshal()
if err == nil {
if _, err := os.Stat(datapath); err == nil || os.IsExist(err) {
if file.IsExist(datapath) {
f, err1 := os.OpenFile(pbfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err1 == nil {
_, err2 := f.Write(data)
@@ -126,6 +128,7 @@ func savecompo() error {
}
return err1
}
return errors.New("datapath is not exist")
}
return err
}

View File

@@ -1,3 +1,4 @@
// Package diana 嘉然相关
package diana
import (
@@ -37,12 +38,12 @@ func init() {
zhiwangjson := zhiwangapi(msg)
if zhiwangjson == nil || zhiwangjson.Code != 0 {
ctx.Send("api返回错误")
ctx.SendChain(message.Text("api返回错误"))
return
}
if len(zhiwangjson.Data.Related) == 0 {
ctx.Send("枝网没搜到查重率为0%,我的评价是:一眼真")
ctx.SendChain(message.Text("枝网没搜到查重率为0%,我的评价是:一眼真"))
return
}

View File

@@ -1,9 +1,12 @@
package fortune
import (
"errors"
io "io"
"os"
"sync"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
)
var (
@@ -13,7 +16,7 @@ var (
func loadcfg(name string) error {
name = base + name
if _, err := os.Stat(name); err == nil || os.IsExist(err) {
if file.IsExist(name) {
f, err := os.Open(name)
if err == nil {
defer f.Close()
@@ -35,7 +38,7 @@ func savecfg(name string) error {
name = base + name
data, err := conf.Marshal()
if err == nil {
if _, err := os.Stat(base); err == nil || os.IsExist(err) {
if file.IsExist(base) {
f, err1 := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err1 == nil {
mu.Lock()
@@ -46,6 +49,7 @@ func savecfg(name string) error {
}
return err1
}
return errors.New("base dir is not exist")
}
return err
}

View File

@@ -15,11 +15,14 @@ import (
"time"
"github.com/fogleman/gg"
"github.com/sirupsen/logrus"
zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/wdvxdr1123/ZeroBot/utils/helper"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/data"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
"github.com/FloatTech/ZeroBot-Plugin/utils/math"
)
var (
@@ -73,9 +76,9 @@ func init() {
Handle(func(ctx *zero.Ctx) {
// 检查签文文件是否存在
mikuji := base + "运势签文.json"
if _, err := os.Stat(mikuji); err != nil && !os.IsExist(err) {
if file.IsNotExist(mikuji) {
ctx.SendChain(message.Text("正在下载签文文件,请稍后..."))
err := data.DownloadTo(site+"运势签文.json", mikuji)
err := file.DownloadTo(site+"运势签文.json", mikuji)
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))
return
@@ -84,9 +87,9 @@ func init() {
}
// 检查字体文件是否存在
ttf := base + "sakura.ttf"
if _, err := os.Stat(ttf); err != nil && !os.IsExist(err) {
if file.IsNotExist(ttf) {
ctx.SendChain(message.Text("正在下载字体文件,请稍后..."))
err := data.DownloadTo(site+"sakura.ttf", ttf)
err := file.DownloadTo(site+"sakura.ttf", ttf)
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))
return
@@ -100,28 +103,30 @@ func init() {
// 个人用户设为负数
gid = -ctx.Event.UserID
}
logrus.Debugln("[fortune]gid:", ctx.Event.GroupID, "uid:", ctx.Event.UserID)
if v, ok := conf.Kind[gid]; ok {
kind = table[v]
}
// 检查背景图片是否存在
folder := base + kind
if _, err := os.Stat(folder); err != nil && !os.IsExist(err) {
if file.IsNotExist(folder) {
ctx.SendChain(message.Text("正在下载背景图片,请稍后..."))
zipfile := kind + ".zip"
err := data.DownloadTo(site+zipfile, zipfile)
zipcache := base + zipfile
err := file.DownloadTo(site+zipfile, zipcache)
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))
return
}
ctx.SendChain(message.Text("下载背景图片完毕"))
err = unpack(zipfile, folder+"/")
err = unpack(zipcache, folder+"/")
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))
return
}
ctx.SendChain(message.Text("解压背景图片完毕"))
// 释放空间
os.Remove(zipfile)
os.Remove(zipcache)
}
// 生成种子
t, _ := strconv.ParseInt(time.Now().Format("20060102"), 10, 64)
@@ -145,7 +150,7 @@ func init() {
return
}
// 发送图片
ctx.SendChain(message.Image("base64://" + data.Bytes2str(d)))
ctx.SendChain(message.Image("base64://" + helper.BytesToString(d)))
})
}
@@ -155,7 +160,7 @@ func init() {
// @return 错误信息
func unpack(tgt, dest string) error {
// 路径目录不存在则创建目录
if _, err := os.Stat(dest); err != nil && !os.IsExist(err) {
if file.IsNotExist(dest) {
if err := os.MkdirAll(dest, 0755); err != nil {
panic(err)
}
@@ -254,7 +259,7 @@ func draw(background, title, text string) ([]byte, error) {
default:
for i, o := range r {
xnow := rowsnum(i+1, 9)
ysum := data.Min(len(r)-(xnow-1)*9, 9)
ysum := math.Min(len(r)-(xnow-1)*9, 9)
ynow := i%9 + 1
canvas.DrawString(string(o), -offest(xsum, xnow, tw)+115, offest(ysum, ynow, th)+320.0)
}
@@ -262,7 +267,7 @@ func draw(background, title, text string) ([]byte, error) {
div := rowsnum(len(r), 2)
for i, o := range r {
xnow := rowsnum(i+1, div)
ysum := data.Min(len(r)-(xnow-1)*div, div)
ysum := math.Min(len(r)-(xnow-1)*div, div)
ynow := i%div + 1
switch xnow {
case 1:

View File

@@ -14,10 +14,10 @@ import (
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
)
var botpath, _ = os.Getwd()
var cachedir = botpath + "/data/hs/"
var cachedir = file.BOT_PATH + "/data/hs/"
var header = req.Header{
"user-agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Mobile Safari/537.36`,
@@ -53,7 +53,7 @@ func init() {
cid := gjson.Get(g, `list.`+strconv.Itoa(i)+`.CardID`).String()
cachefile := cachedir + cid
imgcq := `[CQ:image,file=` + "file:///" + cachefile + `]`
if _, err := os.Stat(cachefile); err != nil {
if file.IsNotExist(cachefile) {
im, err := req.Get(`https://res.fbigame.com/hs/v13/`+cid+
`.png?auth_key=`+gjson.Get(g, `list.`+strconv.Itoa(i)+`.auth_key`).String(),
header,

View File

@@ -11,7 +11,7 @@ import (
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/data"
"github.com/FloatTech/ZeroBot-Plugin/utils/math"
)
const (
@@ -31,7 +31,7 @@ func init() {
}).OnFullMatch("来份萝莉").SetBlock(true).
Handle(func(ctx *zero.Ctx) {
go func() {
for i := 0; i < data.Min(cap(queue)-len(queue), 2); i++ {
for i := 0; i < math.Min(cap(queue)-len(queue), 2); i++ {
resp, err := http.Get(api)
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))

View File

@@ -17,7 +17,8 @@ import (
timer "github.com/FloatTech/ZeroBot-Plugin-Timer"
"github.com/FloatTech/ZeroBot-Plugin/data"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
"github.com/FloatTech/ZeroBot-Plugin/utils/math"
)
const (
@@ -58,7 +59,7 @@ func init() { // 插件主体
// 菜单
zero.OnFullMatch("群管系统", zero.AdminPermission).SetBlock(true).FirstPriority().
Handle(func(ctx *zero.Ctx) {
ctx.Send(hint)
ctx.SendChain(message.Text(hint))
})
// 升为管理
zero.OnRegex(`^升为管理.*?(\d+)`, zero.OnlyGroup, zero.SuperUserPermission).SetBlock(true).SetPriority(40).
@@ -254,9 +255,9 @@ func init() { // 插件主体
ts.Grpid = uint64(ctx.Event.GroupID)
if ts.Enable {
go timer.RegisterTimer(ts, true)
ctx.Send("记住了~")
ctx.SendChain(message.Text("记住了~"))
} else {
ctx.Send("参数非法!")
ctx.SendChain(message.Text("参数非法!"))
}
}
})
@@ -273,9 +274,9 @@ func init() { // 插件主体
t.Enable = false
delete(*timer.Timers, ti) // 避免重复取消
_ = timer.SaveTimers()
ctx.Send("取消成功~")
ctx.SendChain(message.Text("取消成功~"))
} else {
ctx.Send("没有这个定时器哦~")
ctx.SendChain(message.Text("没有这个定时器哦~"))
}
}
})
@@ -283,7 +284,7 @@ func init() { // 插件主体
zero.OnFullMatch("列出所有提醒", zero.AdminPermission).SetBlock(true).SetPriority(40).
Handle(func(ctx *zero.Ctx) {
if ctx.Event.GroupID > 0 {
ctx.Send(fmt.Sprint(timer.ListTimers(uint64(ctx.Event.GroupID))))
ctx.SendChain(message.Text(timer.ListTimers(uint64(ctx.Event.GroupID))))
}
})
// 随机点名
@@ -302,7 +303,7 @@ func init() { // 插件主体
sort.SliceStable(temp, func(i, j int) bool {
return temp[i].Get("last_sent_time").Int() < temp[j].Get("last_sent_time").Int()
})
temp = temp[data.Max(0, len(temp)-10):]
temp = temp[math.Max(0, len(temp)-10):]
rand.Seed(time.Now().UnixNano())
who := temp[rand.Intn(len(temp))]
if who.Get("user_id").Int() == ctx.Event.SelfID {
@@ -330,9 +331,9 @@ func init() { // 插件主体
if ctx.Event.NoticeType == "group_increase" {
word, ok := config.Welcome[uint64(ctx.Event.GroupID)]
if ok {
ctx.Send(word)
ctx.SendChain(message.Text(word))
} else {
ctx.Send("欢迎~")
ctx.SendChain(message.Text("欢迎~"))
}
enable, ok1 := config.Checkin[uint64(ctx.Event.GroupID)]
if ok1 && enable {
@@ -349,7 +350,7 @@ func init() { // 插件主体
ans, err := strconv.Atoi(text)
if err == nil {
if ans != r {
ctx.Send("答案不对哦,再想想吧~")
ctx.SendChain(message.Text("答案不对哦,再想想吧~"))
return false
}
return true
@@ -362,12 +363,12 @@ func init() { // 插件主体
recv, cancel := next.Repeat()
select {
case <-time.After(time.Minute):
ctx.Send("拜拜啦~")
ctx.SendChain(message.Text("拜拜啦~"))
ctx.SetGroupKick(ctx.Event.GroupID, uid, false)
cancel()
case <-recv:
cancel()
ctx.Send("答对啦~")
ctx.SendChain(message.Text("答对啦~"))
}
}
}
@@ -384,9 +385,9 @@ func init() { // 插件主体
Handle(func(ctx *zero.Ctx) {
config.Welcome[uint64(ctx.Event.GroupID)] = ctx.State["regex_matched"].([]string)[1]
if saveConfig() == nil {
ctx.Send("记住啦!")
ctx.SendChain(message.Text("记住啦!"))
} else {
ctx.Send("出错啦!")
ctx.SendChain(message.Text("出错啦!"))
}
})
// 入群验证开关
@@ -402,9 +403,9 @@ func init() { // 插件主体
return
}
if saveConfig() == nil {
ctx.Send("已" + option)
ctx.SendChain(message.Text("已", option))
} else {
ctx.Send("出错啦!")
ctx.SendChain(message.Text("出错啦!"))
}
})
// 运行 CQ 码
@@ -413,6 +414,7 @@ func init() { // 插件主体
var cmd = ctx.State["regex_matched"].([]string)[1]
cmd = strings.ReplaceAll(cmd, "&#91;", "[")
cmd = strings.ReplaceAll(cmd, "&#93;", "]")
// 可注入,权限为主人
ctx.Send(cmd)
})
}
@@ -426,7 +428,7 @@ func strToInt(str string) int64 {
func loadConfig() {
mkdirerr := os.MkdirAll(datapath, 0755)
if mkdirerr == nil {
if _, err := os.Stat(confile); err == nil || os.IsExist(err) {
if file.IsExist(confile) {
f, err := os.Open(confile)
if err == nil {
data, err1 := io.ReadAll(f)
@@ -451,7 +453,7 @@ func saveConfig() error {
data, err := config.Marshal()
if err != nil {
return err
} else if _, err := os.Stat(datapath); err == nil || os.IsExist(err) {
} else if file.IsExist(datapath) {
f, err1 := os.OpenFile(confile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err1 != nil {
return err1

View File

@@ -19,24 +19,23 @@ import (
const api = "http://your.addr:23333/api/start_server/%s/?apikey=apikey"
var engine *zero.Engine
var engine = control.Register("minecraft", &control.Options{
DisableOnDefault: false,
Help: "minecraft\n" +
"- /mcstart xxx\n" +
"- /mcstop xxx\n" +
"- /mclist servername\n" +
"- https://github.com/Suwings/MCSManager",
})
func init() {
engine = control.Register("minecraft", &control.Options{
DisableOnDefault: false,
Help: "minecraft\n" +
"- /mcstart xxx\n" +
"- /mcstop xxx\n" +
"- /mclist servername\n" +
"- https://github.com/Suwings/MCSManager",
})
engine.OnCommand("mcstart").SetBlock(true).
Handle(func(ctx *zero.Ctx) {
model := extension.CommandModel{}
_ = ctx.Parse(&model)
ctx.SendChain(message.Text("开启服务器: ", model.Args, "....."))
result := start(model.Args)
ctx.Send(result)
ctx.SendChain(message.Text(result))
})
engine.OnCommand("mcstop").SetBlock(true).
Handle(func(ctx *zero.Ctx) {
@@ -44,7 +43,7 @@ func init() {
_ = ctx.Parse(&model)
ctx.SendChain(message.Text("开启服务器: ", model.Args, "....."))
result := stop(model.Args)
ctx.Send(result)
ctx.SendChain(message.Text(result))
})
}

View File

@@ -32,7 +32,7 @@ func init() {
}).OnRegex("^(.{0,2})点歌(.{1,25})$").SetBlock(true).FirstPriority().
Handle(func(ctx *zero.Ctx) {
if !limit.Load(ctx.Event.UserID).Acquire() {
ctx.Send("请稍后重试0x0...")
ctx.SendChain(message.Text("请稍后重试0x0..."))
return
}
// switch 平台

View File

@@ -9,6 +9,8 @@ import (
wr "github.com/mroth/weightedrand"
log "github.com/sirupsen/logrus"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
)
const (
@@ -53,7 +55,7 @@ func init() {
// load 加载rate数据
func load(area *rate) error {
if _, err := os.Stat(jsonfile); err == nil || os.IsExist(err) {
if file.IsExist(jsonfile) {
f, err := os.Open(jsonfile)
if err == nil {
defer f.Close()

View File

@@ -107,7 +107,7 @@ func init() {
}).OnRegex(`^>runcode\s(.+?)\s([\s\S]+)$`).SetBlock(true).SecondPriority().
Handle(func(ctx *zero.Ctx) {
if !limit.Load(ctx.Event.UserID).Acquire() {
ctx.Send("请稍后重试0x0...")
ctx.SendChain(message.Text("请稍后重试0x0..."))
} else {
language := ctx.State["regex_matched"].([]string)[1]
language = strings.ToLower(language)

View File

@@ -3,20 +3,31 @@ package saucenao
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/FloatTech/AnimeAPI/ascii2d"
"github.com/FloatTech/AnimeAPI/picture"
"github.com/FloatTech/AnimeAPI/pixiv"
"github.com/FloatTech/AnimeAPI/saucenao"
"github.com/sirupsen/logrus"
zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/utils/file"
)
var (
datapath = file.BOT_PATH + "/data/saucenao/"
)
func init() { // 插件主体
_ = os.RemoveAll(datapath)
err := os.MkdirAll(datapath, 0755)
if err != nil {
panic(err)
}
engine := control.Register("saucenao", &control.Options{
DisableOnDefault: false,
Help: "搜图\n" +
@@ -27,7 +38,7 @@ func init() { // 插件主体
engine.OnRegex(`^搜图(\d+)$`).SetBlock(true).FirstPriority().
Handle(func(ctx *zero.Ctx) {
id, _ := strconv.ParseInt(ctx.State["regex_matched"].([]string)[1], 10, 64)
ctx.Send("少女祈祷中......")
ctx.SendChain(message.Text("少女祈祷中......"))
// 获取P站插图信息
illust, err := pixiv.Works(id)
if err != nil {
@@ -35,30 +46,48 @@ func init() { // 插件主体
return
}
if illust.Pid > 0 {
// 改用 i.pixiv.cat 镜像站
link := illust.ImageUrls
link = strings.ReplaceAll(link, "i.pximg.net", "i.pixiv.cat")
// 发送搜索结果
ctx.SendChain(
message.Image(link),
message.Text(
"\n",
"标题:", illust.Title, "\n",
"插画ID", illust.Pid, "\n",
"画师:", illust.UserName, "\n",
"画师ID", illust.UserId, "\n",
"直链:", "https://pixivel.moe/detail?id=", illust.Pid,
),
name := strconv.FormatInt(illust.Pid, 10)
filepath := datapath + name
switch {
case file.IsExist(filepath + ".jpg"):
filepath = "file:///" + filepath + ".jpg"
case file.IsExist(filepath + ".png"):
filepath = "file:///" + filepath + ".png"
case file.IsExist(filepath + ".gif"):
filepath = "file:///" + filepath + ".gif"
default:
filepath = ""
}
if filepath == "" {
logrus.Debug("[sausenao]开始下载", name)
filepath, err = pixiv.Download(illust.ImageUrls, datapath, name)
if err == nil {
filepath = "file:///" + filepath
}
}
txt := message.Text(
"标题:", illust.Title, "\n",
"插画ID", illust.Pid, "\n",
"画师:", illust.UserName, "\n",
"画师ID", illust.UserId, "\n",
"直链:", "https://pixivel.moe/detail?id=", illust.Pid,
)
if filepath != "" {
// 发送搜索结果
ctx.SendChain(message.Image(filepath), message.Text("\n"), txt)
} else {
// 图片下载失败,仅发送文字结果
ctx.SendChain(txt)
}
} else {
ctx.Send("图片不存在!")
ctx.SendChain(message.Text("图片不存在!"))
}
})
// 以图搜图
engine.OnKeywordGroup([]string{"以图搜图", "搜索图片", "以图识图"}, picture.CmdMatch, picture.MustGiven).SetBlock(true).FirstPriority().
Handle(func(ctx *zero.Ctx) {
// 开始搜索图片
ctx.Send("少女祈祷中......")
ctx.SendChain(message.Text("少女祈祷中......"))
for _, pic := range ctx.State["image_url"].([]string) {
fmt.Println(pic)
if result, err := saucenao.SauceNAO(pic); err != nil {

View File

@@ -18,13 +18,15 @@ import (
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/FloatTech/ZeroBot-Plugin/control"
"github.com/FloatTech/ZeroBot-Plugin/data"
fileutil "github.com/FloatTech/ZeroBot-Plugin/utils/file"
"github.com/FloatTech/ZeroBot-Plugin/utils/math"
"github.com/FloatTech/ZeroBot-Plugin/utils/sql"
)
// Pools 图片缓冲池
type imgpool struct {
Lock sync.Mutex
DB *data.Sqlite
DB *sql.Sqlite
Path string
Group int64
List []string
@@ -40,7 +42,7 @@ const (
// NewPoolsCache 返回一个缓冲池对象
func newPools() *imgpool {
cache := &imgpool{
DB: &data.Sqlite{DBPath: "data/SetuTime/SetuTime.db"},
DB: &sql.Sqlite{DBPath: "data/SetuTime/SetuTime.db"},
Path: "data/SetuTime/cache/",
Group: 0,
List: []string{"涩图", "二次元", "风景", "车万"}, // 可以自己加类别,得自己加图片进数据库
@@ -106,7 +108,7 @@ func init() { // 插件主体
var imgtype = ctx.State["regex_matched"].([]string)[1]
// 补充池子
go func() {
times := data.Min(pool.Max-pool.size(imgtype), 2)
times := math.Min(pool.Max-pool.size(imgtype), 2)
for i := 0; i < times; i++ {
illust := &pixiv.Illust{}
// 查询出一张图片
@@ -168,7 +170,7 @@ func init() { // 插件主体
ctx.SendChain(message.Text("ERROR: ", err))
return
}
ctx.Send("添加成功")
ctx.SendChain(message.Text("添加成功"))
})
engine.OnRegex(`^删除(.*?)(\d+)$`, firstValueInList(pool.List), zero.SuperUserPermission).SetBlock(true).SetPriority(22).
@@ -179,10 +181,10 @@ func init() { // 插件主体
)
// 查询数据库
if err := pool.DB.Del(imgtype, fmt.Sprintf("WHERE pid=%d", id)); err != nil {
ctx.Send(fmt.Sprintf("ERROR: %v", err))
ctx.SendChain(message.Text("ERROR: ", err))
return
}
ctx.Send("删除成功")
ctx.SendChain(message.Text("删除成功"))
})
// 查询数据库涩图数量
@@ -199,7 +201,7 @@ func init() { // 插件主体
state = append(state, ": ")
state = append(state, fmt.Sprintf("%d", num))
}
ctx.Send(strings.Join(state, ""))
ctx.SendChain(message.Text(state))
})
}
@@ -248,8 +250,7 @@ func (p *imgpool) pop(imgtype string) (illust *pixiv.Illust) {
func file(i *pixiv.Illust) string {
filename := fmt.Sprint(i.Pid)
pwd, _ := os.Getwd()
filepath := pwd + `/` + pool.Path + filename
filepath := fileutil.BOT_PATH + `/` + pool.Path + filename
if _, err := os.Stat(filepath + ".jpg"); err == nil || os.IsExist(err) {
return `file:///` + filepath + ".jpg"
}

View File

@@ -1,3 +1,10 @@
/*
* @Author: Kanri
* @Date: 2021-10-15 21:23:14
* @LastEditors: Kanri
* @LastEditTime: 2021-10-15 21:42:51
* @Description:
*/
// Package shindan 基于 https://shindanmaker.com 的测定小功能
package shindan
@@ -52,6 +59,7 @@ func handle(ctx *zero.Ctx) {
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))
}
// TODO: 可注入
ctx.Send(text)
}

11
utils/file/dir_nowin.go Normal file
View File

@@ -0,0 +1,11 @@
//go:build !windows
// +build !windows
package file
import "os"
func Pwd() (path string) {
path, _ = os.Getwd()
return
}

14
utils/file/dir_win.go Normal file
View File

@@ -0,0 +1,14 @@
//go:build windows
// +build windows
package file
import (
"os"
"strings"
)
func Pwd() string {
path, _ := os.Getwd()
return strings.ReplaceAll(path, "\\", "/")
}

View File

@@ -1,4 +1,5 @@
package data
// Package file 文件实用工具
package file
import (
"io"
@@ -6,6 +7,7 @@ import (
"os"
)
// DownloadTo 下载到路径
func DownloadTo(url, file string) error {
resp, err := http.Get(url)
if err == nil {

17
utils/file/f.go Normal file
View File

@@ -0,0 +1,17 @@
package file
import "os"
var BOT_PATH = Pwd()
// IsExist 文件/路径存在
func IsExist(path string) bool {
_, err := os.Stat(path)
return err == nil || os.IsExist(err)
}
// IsExist 文件/路径不存在
func IsNotExist(path string) bool {
_, err := os.Stat(path)
return err != nil && os.IsNotExist(err)
}

18
utils/math/math.go Normal file
View File

@@ -0,0 +1,18 @@
// Package math 计算实用工具
package math
// Max 返回两数最大值,该函数将被内联
func Max(a, b int) int {
if a > b {
return a
}
return b
}
// Min 返回两数最小值,该函数将被内联
func Min(a, b int) int {
if a > b {
return b
}
return a
}

View File

@@ -1,5 +1,5 @@
// Package data 数据库/数据处理相关工具
package data
// Package sql 数据库/数据处理相关工具
package sql
import (
"database/sql"