mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-09-29 00:32:06 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32e420efbb | ||
|
|
6db9bef115 | ||
|
|
a0b440efcd | ||
|
|
d2bb7ae493 | ||
|
|
b4e213518b | ||
|
|
e3b0da4717 | ||
|
|
155de5a032 | ||
|
|
57e166940d | ||
|
|
721efb79fd | ||
|
|
5338342208 | ||
|
|
c49ef3052f | ||
|
|
802f4df2ce | ||
|
|
1edcee9ce3 | ||
|
|
3acd7d7d41 | ||
|
|
83dc29a562 | ||
|
|
b25b9ca928 | ||
|
|
0dc11b7edb | ||
|
|
9b477e2eb8 | ||
|
|
272f6726ea | ||
|
|
181717001a | ||
|
|
43b654285f | ||
|
|
50e7d5036e | ||
|
|
b6b2f2e2a6 | ||
|
|
b9d08855d0 | ||
|
|
93deb2b1be | ||
|
|
b3871d550c | ||
|
|
ab8e87899c | ||
|
|
9d6f44849a | ||
|
|
380588c11d | ||
|
|
5810c28294 | ||
|
|
c039015e8f | ||
|
|
0dda0a228a | ||
|
|
940514b16b | ||
|
|
8adff43113 | ||
|
|
b59699dabe | ||
|
|
f496ce4861 | ||
|
|
5fb4eccd0f | ||
|
|
31e4cadecb | ||
|
|
994484f3b0 | ||
|
|
7b3a3451f6 | ||
|
|
14d075bc17 | ||
|
|
75369411b3 | ||
|
|
d97542a3fd | ||
|
|
2f70fcd92a | ||
|
|
182f93d618 | ||
|
|
34e28384dd | ||
|
|
f6f095f949 | ||
|
|
08609bdf53 | ||
|
|
5de5667f80 | ||
|
|
69b3ba47b3 | ||
|
|
11c1d0b827 | ||
|
|
8f97880754 | ||
|
|
ff435bea95 | ||
|
|
cd66b7f5b8 | ||
|
|
a60286c328 | ||
|
|
49e38862af | ||
|
|
75b8cc0766 | ||
|
|
a8e2f00e16 | ||
|
|
d099a85c59 | ||
|
|
55b2a86397 | ||
|
|
d39dfbe62f | ||
|
|
a41e62cefe | ||
|
|
c981562f90 | ||
|
|
e6cd57cc26 | ||
|
|
074152ae14 | ||
|
|
91ca7b40b8 | ||
|
|
5321c8d9c0 | ||
|
|
b7f753ebb6 | ||
|
|
c5e8ba3cdf | ||
|
|
658ef5309b | ||
|
|
823f642225 | ||
|
|
57ea6bad07 | ||
|
|
109c645e68 | ||
|
|
5ef0ce5aa8 | ||
|
|
f6d9e083b8 | ||
|
|
499517e882 | ||
|
|
648db532bb | ||
|
|
1ce4537605 | ||
|
|
701812ed9d | ||
|
|
8d9e81827b | ||
|
|
f51a2816b4 | ||
|
|
3d4a7950c5 | ||
|
|
ba6668f144 | ||
|
|
e1f7a77d15 | ||
|
|
64e2c512d3 | ||
|
|
6082e68a1f | ||
|
|
f135d48e55 | ||
|
|
751fc8fdb4 | ||
|
|
df73e79ee4 | ||
|
|
fa6cfdb609 | ||
|
|
b057a05520 | ||
|
|
cb0938721c | ||
|
|
4f3f8de734 | ||
|
|
5ba303aada | ||
|
|
bd42fefe4e | ||
|
|
d24c081973 | ||
|
|
1b9eddd905 | ||
|
|
0bfe398dc4 | ||
|
|
e9216a472f | ||
|
|
8b93ec0df6 | ||
|
|
7497706a0d | ||
|
|
6e41cb0630 | ||
|
|
62d99e7e90 | ||
|
|
43cddb3580 | ||
|
|
c9c1beda75 | ||
|
|
3ee9ae5fb8 | ||
|
|
ea6344fae1 | ||
|
|
6f54e91f5c | ||
|
|
27fb3aaa19 | ||
|
|
86d736745d | ||
|
|
821fe21c2b | ||
|
|
7f4aa518dc | ||
|
|
8cf589e433 | ||
|
|
105a29cd70 | ||
|
|
cb6a5e81e7 | ||
|
|
9c073383ad | ||
|
|
5e0756825d | ||
|
|
933523ae6d | ||
|
|
ed6b05605c | ||
|
|
71a9c34620 | ||
|
|
e29f2cb920 | ||
|
|
d47dd88d6c | ||
|
|
fb34bbce7a | ||
|
|
100236da83 | ||
|
|
a45a3002d5 | ||
|
|
9214a4c978 | ||
|
|
70761dc222 | ||
|
|
32e8136f71 | ||
|
|
8b20d99b2c | ||
|
|
1174b5cc7f | ||
|
|
ec448cfdfb | ||
|
|
f3e44b1baf |
@@ -1,38 +0,0 @@
|
||||
name: Generate poetry.lock
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "main"
|
||||
paths:
|
||||
- 'pyproject.toml'
|
||||
|
||||
jobs:
|
||||
poetry_lock:
|
||||
name: Generate
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Set up Python
|
||||
uses: he0119/setup-python@main
|
||||
with:
|
||||
python-version: "3.9"
|
||||
- name: poetry lock
|
||||
run: |
|
||||
rm -f poetry.lock
|
||||
sed -i.bak "8,11d" pyproject.toml
|
||||
poetry lock
|
||||
mv pyproject.toml.bak pyproject.toml
|
||||
# commit
|
||||
- name: commit file
|
||||
run: |
|
||||
git config --local user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git config --local user.name "github-actions[bot]"
|
||||
git add poetry.lock
|
||||
git commit -m "Auto generate poetry.lock" -a
|
||||
# push
|
||||
- name: push changes
|
||||
uses: ad-m/github-push-action@master
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
+9
-7
@@ -154,10 +154,12 @@ bot.py
|
||||
data/
|
||||
.env
|
||||
.env.dev
|
||||
resources/
|
||||
!/configs/config.py
|
||||
!/configs/config.yaml
|
||||
!/.env
|
||||
!/.env.dev
|
||||
!/plugins/csgo_server/
|
||||
!/plugins/activity/
|
||||
/resources/text/
|
||||
/resources/image/
|
||||
!/resources/template/
|
||||
configs/config.py
|
||||
configs/config.yaml
|
||||
./.env
|
||||
./.env.dev
|
||||
plugins/csgo_server/
|
||||
plugins/activity/
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
|
||||
如果该项目的图片等等侵犯猫豆腐老师权益请联系我删除!
|
||||
|
||||
如果希望有个地方讨论绪山真寻Bot,或者有问题或建议,可以发送issues或加入[ <strong>[是真寻酱哒](https://jq.qq.com/?_wv=1027&k=u8PgBkMZ) </strong>]
|
||||
是新手!希望有个地方讨论绪山真寻Bot,或者有问题或建议,可以发送issues或加入[ <strong>[是真寻酱哒(萌新版)](https://jq.qq.com/?_wv=1027&k=u8PgBkMZ) </strong>]
|
||||
|
||||
[//]: # (是老手!讨论插件开发,nonebot2开发,可以加入[ <strong>[真寻酱的技术群](https://jq.qq.com/?_wv=1027&k=u8PgBkMZ) </strong>])
|
||||
|
||||
## 声明
|
||||
此项目仅用于学习交流,请勿用于非法用途
|
||||
@@ -31,7 +33,10 @@
|
||||
请对真寻说: '真寻帮助' or '管理员帮助' or '超级用户帮助' or '真寻帮助 指令'
|
||||
|
||||
## 普通帮助图片
|
||||

|
||||

|
||||
|
||||
## HTML版帮助图片
|
||||

|
||||
|
||||
## Web UI
|
||||
[zhenxun_bot_webui](https://github.com/HibiKier/zhenxun_bot_webui)
|
||||
@@ -252,6 +257,21 @@ PS: **ARM平台** 请使用全量版 同时 **如果你的机器 RAM < 1G 可能
|
||||
|
||||
### 感谢名单
|
||||
(可以告诉我你的 __github__ 地址,我偷偷换掉0v|)
|
||||
|
||||
[阿奎](https://afdian.net/u/da41f72845d511ed930d52540025c377)
|
||||
[醉梦尘逸](https://afdian.net/u/bc11d2683cd011ed99b552540025c377)
|
||||
[Abc](https://afdian.net/u/870dc10a3cd311ed828852540025c377)
|
||||
[本喵无敌哒](https://afdian.net/u/dffaa9005bc911ebb69b52540025c377)
|
||||
[椎名冬羽](https://afdian.net/u/ca1ebd64395e11ed81b452540025c377)
|
||||
[kaito](https://afdian.net/u/a055e20a498811eab1f052540025c377)
|
||||
[笑柒XIAO_Q7](https://afdian.net/u/4696db5c529111ec84ea52540025c377)
|
||||
[请问一份爱多少钱](https://afdian.net/u/f57ef6602dbd11ed977f52540025c377)
|
||||
[咸鱼鱼鱼鱼](https://afdian.net/u/8e39b9a400e011ed9f4a52540025c377)
|
||||
[Kafka](https://afdian.net/u/41d66798ef6911ecbc5952540025c377)
|
||||
[墨然](https://afdian.net/u/8aa5874a644d11eb8a6752540025c377)
|
||||
[爱发电用户_T9e4](https://afdian.net/u/2ad1bb82f3a711eca22852540025c377)
|
||||
[笑柒XIAO_Q7](https://afdian.net/u/4696db5c529111ec84ea52540025c377)
|
||||
[noahzark](https://afdian.net/a/noahzark)
|
||||
[腊条](https://afdian.net/u/f739c4d69eca11eba94b52540025c377)
|
||||
[ze roller](https://afdian.net/u/0e599e96257211ed805152540025c377)
|
||||
[爱发电用户_4jrf](https://afdian.net/u/6b2cdcc817c611ed949152540025c377)
|
||||
@@ -263,7 +283,7 @@ PS: **ARM平台** 请使用全量版 同时 **如果你的机器 RAM < 1G 可能
|
||||
[爱发电用户_eNr9](https://afdian.net/u/05fdb41c0c9a11ed814952540025c377)
|
||||
[MangataAkihi](https://github.com/Sakuracio)
|
||||
[炀](https://afdian.net/u/69b76e9ec77b11ec874f52540025c377)
|
||||
[爱发电用户_Bc6j](https://afdian.net/u/8546be24f44111eca64052540025c377)
|
||||
[爱发电用户_Bc6j](https://afdian.net/u/8546be24f44111eca64052540025c377)
|
||||
[大魔王](https://github.com/xipesoy)
|
||||
[CopilotLaLaLa](https://github.com/CopilotLaLaLa)
|
||||
[嘿小欧](https://afdian.net/u/daa4bec4f24911ec82e552540025c377)
|
||||
@@ -279,6 +299,173 @@ PS: **ARM平台** 请使用全量版 同时 **如果你的机器 RAM < 1G 可能
|
||||
|
||||
## 更新
|
||||
|
||||
### 2022/12/27 \[v0.1.6.6]
|
||||
|
||||
* 添加权限检查依赖注入
|
||||
|
||||
### 2022/12/26
|
||||
|
||||
* 优化`gamedraw`插件
|
||||
* 提供全局被动控制
|
||||
* 群被动状态改为图片
|
||||
* 修复epic获取到的简介不是中文的bug [@pull/1221](https://github.com/HibiKier/zhenxun_bot/pull/1221)
|
||||
|
||||
## 2022/12/24
|
||||
|
||||
* 修复群管理员权限检测会阻挡超级用户权限
|
||||
|
||||
### 2022/12/23
|
||||
|
||||
* 优化`管理员帮助`,`超级用户帮助`图片
|
||||
* 重新移植`gamedraw`
|
||||
* 修复pil帮助私聊时无法生成
|
||||
|
||||
### 2022/12/17
|
||||
|
||||
* 修复查看插件仓库当已安装插件版本不一致时出错
|
||||
|
||||
### 2022/12/15
|
||||
|
||||
* 修复自定义群欢迎消息无法使用
|
||||
|
||||
### 2022/12/13
|
||||
|
||||
* 修复.unban
|
||||
|
||||
### 2022/12/12
|
||||
|
||||
* 修改HTML帮助禁用提示文本错误
|
||||
* 修复HTML帮助私聊无法生成
|
||||
|
||||
### 2022/12/11
|
||||
|
||||
* 词条问题支持真寻的昵称开头与at真寻开头并优化回复
|
||||
* 帮助新增HTML生成(新布局),添加配置`TYPE`切换
|
||||
* 更正私聊时功能管理回复错误
|
||||
* 修复加入新群聊时初始化功能开关错误
|
||||
* 添加单例注解
|
||||
* 添加统计表
|
||||
|
||||
### 2022/12/10
|
||||
|
||||
* 重写帮助,删除 `详细帮助` 命令
|
||||
|
||||
### 2022/12/4
|
||||
|
||||
* 优化管理代码
|
||||
|
||||
### 2022/11/28
|
||||
|
||||
* 修复web_ui群组无法获取
|
||||
* 修复web_ui修改插件数据时cmd格式错误
|
||||
|
||||
### 2022/11/28
|
||||
|
||||
* :bug: Fix a bug in open_cases to get vanilla knives' prices [@pull/1188](https://github.com/HibiKier/zhenxun_bot/pull/1188)
|
||||
|
||||
### 2022/11/24
|
||||
|
||||
* 修复管理员插件加载路径错误
|
||||
|
||||
### 2022/11/23
|
||||
|
||||
* 修复webui插件无法获取修改
|
||||
|
||||
### 2022/11/22
|
||||
|
||||
* fix switch_rule [@pull/1185](https://github.com/HibiKier/zhenxun_bot/pull/1185)
|
||||
|
||||
### 2022/11/21 \[v0.1.6.5]
|
||||
|
||||
* 优化manager, hook代码
|
||||
* 修复pid搜图 [@pull/1180](https://github.com/HibiKier/zhenxun_bot/pull/1180)
|
||||
|
||||
### 2022/11/19
|
||||
|
||||
* 修改优化帮助图片生成逻辑
|
||||
|
||||
### 2022/11/18
|
||||
|
||||
* poetry添加适配器依赖,更新支持py3.10 [@pull/1176](https://github.com/HibiKier/zhenxun_bot/pull/1176)
|
||||
|
||||
### 2022/11/13
|
||||
|
||||
* 更新天气api
|
||||
* 使用道具可以附带额外信息供函数使用
|
||||
* 限制帮助图片最小宽度
|
||||
|
||||
### 2022/11/12
|
||||
|
||||
* 更新yiqing插件数据显示 [@pull/1168](https://github.com/HibiKier/zhenxun_bot/pull/1168)
|
||||
|
||||
### 2022/11/11
|
||||
|
||||
* fix: B站直播订阅的相关问题 [@pull/1158](https://github.com/HibiKier/zhenxun_bot/pull/1158)
|
||||
|
||||
### 2022/10/30
|
||||
|
||||
* 商店简介动态行数,根据文字长度自动换行
|
||||
|
||||
### 2022/10/28
|
||||
|
||||
* 为exec指令进行了SELECT语句适配,添加了查看所有表指令 [@pull/1155](https://github.com/HibiKier/zhenxun_bot/pull/1155)
|
||||
* 修复复读 [@pull/1154](https://github.com/HibiKier/zhenxun_bot/pull/1154)
|
||||
|
||||
### 2022/10/23
|
||||
|
||||
* 复读修改回图片下载
|
||||
|
||||
### 2022/10/22
|
||||
|
||||
* 更新依赖注入
|
||||
|
||||
### 2022/10/16 \[v0.1.6.4]
|
||||
|
||||
* 修改商店道具icon可以为空
|
||||
|
||||
### 2022/10/15
|
||||
|
||||
* nonebot2版本更新为rc1
|
||||
* 我的道具改为图片形式
|
||||
* 商品添加图标与是否为被动道具(被动道具无法被主动使用)
|
||||
* 商品添加使用前方法和使用后方法(类似hook),使用方法具体查看文档或签到商品文件中注册的例子
|
||||
* 新增用户使用道具,花费金币(包括插件)及用途记录
|
||||
* 更细致的金币使用依赖注入
|
||||
* 更多的依赖注入(包含图片获取等等..
|
||||
* 修复我的道具仅有被动或主动道具时图片显示错误
|
||||
* 色图插件p站反向代理失效 [@pull/1139](https://github.com/HibiKier/zhenxun_bot/pull/1139)
|
||||
|
||||
### 2022/10/9
|
||||
|
||||
* 修复碧蓝档案角色获取问题,换源 [@pull/1124](https://github.com/HibiKier/zhenxun_bot/pull/1124)
|
||||
|
||||
### 2022/10/7
|
||||
|
||||
* 修复 B 站请求返回 -401 错误 [@pull/1119](https://github.com/HibiKier/zhenxun_bot/pull/1119)
|
||||
* 关闭功能与被动时不再区分大小写,同名时仅被动关闭操作生效
|
||||
|
||||
### 2022/9/30
|
||||
|
||||
* 修改重置开箱的使用权限 [@pull/1118](https://github.com/HibiKier/zhenxun_bot/pull/1118)
|
||||
|
||||
### 2022/9/27
|
||||
|
||||
* 更新b站转发解析 [@pull/1117](https://github.com/HibiKier/zhenxun_bot/pull/1117)
|
||||
|
||||
### 2022/9/24
|
||||
|
||||
* 修复b站订阅 [@pull/1112](https://github.com/HibiKier/zhenxun_bot/pull/1112)
|
||||
* fix: 重载赛马娘卡池失败 [@pull/1114](https://github.com/HibiKier/zhenxun_bot/pull/1114)
|
||||
|
||||
### 2022/9/19
|
||||
|
||||
* 更换bilibili_sub获取用户昵称用的API&尝试修了一下get_video() [@pull/1097](https://github.com/HibiKier/zhenxun_bot/pull/1097)
|
||||
* 修复csgo每日开箱可以多开一次
|
||||
|
||||
### 2022/9/18
|
||||
|
||||
* 修复 bilireq 版本过低导致 B 站视频解析错误 [@pull/1090](https://github.com/HibiKier/zhenxun_bot/pull/1096)
|
||||
|
||||
### 2022/9/16
|
||||
|
||||
* fix: bilibili_sub, azur_draw_card [@pull/1090](https://github.com/HibiKier/zhenxun_bot/pull/1090)
|
||||
@@ -334,7 +521,7 @@ PS: **ARM平台** 请使用全量版 同时 **如果你的机器 RAM < 1G 可能
|
||||
* 修复b站转发解析av号无法解析
|
||||
* B站订阅直播订阅支持短号
|
||||
* 开箱提供重置开箱命令,重置今日所有开箱数据(重置次数,并不会删除今日已开箱记录)
|
||||
* 提供全局字典GDict,通过from utils.manager import GDict导入
|
||||
* 提供全局字典GDict,通过from utils.utils import GDict导入
|
||||
* 适配omega 13w张图的数据结构表(建议删表重导)
|
||||
* 除首次启动外将配置替换加入单次定时任务,加快启动速度
|
||||
* fix: WordBank.check() [@pull/1008](https://github.com/HibiKier/zhenxun_bot/pull/1008)
|
||||
@@ -360,481 +547,6 @@ PS: **ARM平台** 请使用全量版 同时 **如果你的机器 RAM < 1G 可能
|
||||
|
||||
* 修复了原神自动签到返回invalid request的问题,新增查看我的cookie命令 [@pull/971](https://github.com/HibiKier/zhenxun_bot/pull/971)
|
||||
|
||||
### 2022/7/31
|
||||
|
||||
* 对nonebot.beta4中PluginMeta进行解析
|
||||
* 修改webui元祖类型无法正确转换类型
|
||||
* 查看订阅以图片形式发送
|
||||
* 修复pix无图时不会提醒而是出错
|
||||
|
||||
### 2022/7/30
|
||||
|
||||
* 替换了cos和bt的url [@pull/951](https://github.com/HibiKier/zhenxun_bot/pull/951)
|
||||
* 发言记录统计添加日消息统计 [@pull/953](https://github.com/HibiKier/zhenxun_bot/pull/953)
|
||||
|
||||
### 2022/7/24 \[v0.1.6.2]
|
||||
|
||||
* 订阅up动态提供直链
|
||||
|
||||
### 2022/7/23
|
||||
|
||||
* 优化开箱次数判断
|
||||
|
||||
### 2022/7/16
|
||||
|
||||
* cos提供连发命令
|
||||
* 修复B站视频解析中b23解析错误
|
||||
|
||||
### 2022/7/13
|
||||
|
||||
* B站订阅提供配置项`LIVE_MSG_AT_ALL`,`UP_MSG_AT_ALL`:控制UP动态投稿和直播是否AT全体
|
||||
* 修改了Omega图库检测的数据库文件名
|
||||
* game_utils提供了Game类
|
||||
|
||||
### 2022/7/7
|
||||
|
||||
* 微博热搜选择单条热搜时也会检测时效性 [@pull/891](https://github.com/HibiKier/zhenxun_bot/pull/891)
|
||||
|
||||
### 2022/7/4
|
||||
|
||||
* 修复商品未设置限购时无法购买
|
||||
* 修复B站订阅UP动态 [@pull/886](https://github.com/HibiKier/zhenxun_bot/pull/886)
|
||||
* 修复色图命令带tag时配置项`MAX_ONCE_NUM2FORWARD`无法生效
|
||||
|
||||
### 2022/7/3 \[v0.1.6.1]
|
||||
|
||||
* BagUser提供方法`check_props`方法,用于判断用户是否含有该道具并是否使用
|
||||
* 优化商品显示图片,提供限制,限购,折扣提示
|
||||
* 修复图库内图片无法被连续删除的问题 [@pull/879](https://github.com/HibiKier/zhenxun_bot/pull/879)
|
||||
* 色图提供配置项`MAX_ONCE_NUM2FORWARD`:群聊中单次发送图片数量达到指定时使用合并转发
|
||||
* 优化修复了商品修改命令
|
||||
* B站订阅UP动态改为详情页截图
|
||||
|
||||
### 2022/6/28
|
||||
|
||||
* 修复色图插件api修改无法搜索图片 [@pull/866](https://github.com/HibiKier/zhenxun_bot/pull/866)
|
||||
|
||||
### 2022/6/26
|
||||
|
||||
* 替换了bt URL
|
||||
* PIX当使用pid查询图片时,会发送该pid下所有图片
|
||||
* 商店提供了每日购买次数限制
|
||||
|
||||
### 2022/6/24
|
||||
|
||||
* 对WSL虚拟机 代理 添加写法 [@pull/847](https://github.com/HibiKier/zhenxun_bot/pull/847)
|
||||
|
||||
### 2022/6/21
|
||||
|
||||
* update parse_bilibili [@pull/840](https://github.com/HibiKier/zhenxun_bot/pull/840)
|
||||
|
||||
### 2022/6/19 \[v0.1.6.0]
|
||||
|
||||
* 暂时使用hook修复webui中plugins2setting修改时会改变plugins2setting.cmd为字符串
|
||||
* 修复原神树脂重复提醒的bug [@pull/828](https://github.com/HibiKier/zhenxun_bot/pull/828)
|
||||
* 词条优化问题展示,修改含机器人昵称和@逻辑 [@pull/835](https://github.com/HibiKier/zhenxun_bot/pull/835)
|
||||
|
||||
### 2022/6/18
|
||||
|
||||
* 修复昵称系统`BLACK_WORD`为空时造成报错
|
||||
* 修复特殊头像时背景透明化出错
|
||||
* 修复text2image纯文本时换行时颜色不统一
|
||||
* 优化webUI,当有插件出错时不会影响其他插件显示
|
||||
* 优化Config类型注释 [@pull/830](https://github.com/HibiKier/zhenxun_bot/pull/830)
|
||||
* 优化browser
|
||||
|
||||
### 2022/6/17
|
||||
|
||||
* 修复wordbank的一些小问题 @pull/820
|
||||
|
||||
### 2022/6/14
|
||||
|
||||
* AsyncHttpx提供可关闭 ssl 验证参数 [@pull/812](https://github.com/HibiKier/zhenxun_bot/pull/812)
|
||||
* fix: 自动更新群组 [@pull/810](https://github.com/HibiKier/zhenxun_bot/pull/810)
|
||||
* fix: 修复添加词条时对answer中图片的处理 [@pull/806](https://github.com/HibiKier/zhenxun_bot/pull/806)
|
||||
* 修复pix中指定num无法生效
|
||||
* 替换了bt URL
|
||||
|
||||
### 2022/6/13
|
||||
|
||||
* Windows 重启适配 [@pull/804](https://github.com/HibiKier/zhenxun_bot/pull/804)
|
||||
* 色图等提供修改md5方法 [@pull/800](https://github.com/HibiKier/zhenxun_bot/pull/800)
|
||||
* webui中token.json文件写入补充 [@pull/798](https://github.com/HibiKier/zhenxun_bot/pull/798)
|
||||
* 修复识图某些图片可能会出错
|
||||
|
||||
### 2022/6/11
|
||||
|
||||
* pix当只有一个tag时且为数字时可以通过添加'#'防止判定为数量
|
||||
|
||||
### 2022/6/9
|
||||
|
||||
* 修复b站订阅同群二人以上相同订阅时发送多次信息
|
||||
* 修复超级用户帮助中缺少了 ‘插件商店’ 相关帮助
|
||||
* 昵称系统提供了详细帮助
|
||||
|
||||
### 2022/6/5 \[v0.1.5.9]
|
||||
|
||||
* webui修复plugin2setting中cmd从list转变为str
|
||||
* 当命令`我的金币`被风控时将以图片形式发送
|
||||
* fix gold_redbag [@pull/763](https://github.com/HibiKier/zhenxun_bot/pull/763)
|
||||
* 金币红包功能增加更多封面 [@pull/764](https://github.com/HibiKier/zhenxun_bot/pull/764)
|
||||
|
||||
### 2022/6/3
|
||||
|
||||
* 插件仓库在已安装插件边上会提示\[已安装]
|
||||
* 修复ShopRegister kwargs某些字段无效
|
||||
* 调整了一下查看所有请求中的年龄绘制 [@pull/745](https://github.com/HibiKier/zhenxun_bot/pull/745)
|
||||
* 修复原神树脂提醒bug [@pull/756](https://github.com/HibiKier/zhenxun_bot/pull/756)
|
||||
|
||||
### 2022/5/31
|
||||
|
||||
* 修复开启/关闭全部功能时帮助图片未重绘 [@pull/721](https://github.com/HibiKier/zhenxun_bot/pull/721)
|
||||
* bot_friend_group将group_handle.修改为friend_handle. [@pull/711](https://github.com/HibiKier/zhenxun_bot/pull/711)
|
||||
* 修复发红包图片背景未透明化;修复原神树脂提醒参数错误 [@pull/712](https://github.com/HibiKier/zhenxun_bot/pull/712)
|
||||
* 修复抽卡插件:方舟更新UP池信息时,若公告的第一个池子过期会导致无法更新UP池信息 [@pull/707](https://github.com/HibiKier/zhenxun_bot/pull/707)
|
||||
* 商店插件判断是否有requirements.txt文件 [@pull/705](https://github.com/HibiKier/zhenxun_bot/pull/705)
|
||||
* 删除原神玩家查询api返回变更的多余键值
|
||||
* 优化了text2image方法
|
||||
|
||||
### 2022/5/29 \[v0.1.5.8]
|
||||
|
||||
* 提供了真寻适配仓库的插件 安装/卸载 操作
|
||||
* 暂时关闭了插件资源清空
|
||||
* 通过指令安装插件时会在插件目录下生成plugin_info.json记录当前插件信息
|
||||
|
||||
### 2022/5/28
|
||||
|
||||
* 修复私聊无法添加昵称
|
||||
* 修复原神玩家查询层岩巨渊地下矿区没开时报错
|
||||
* 修复 ```休息吧``` 无法阻断戳一戳
|
||||
* 当图库无图片时,戳一戳将略过发送图片
|
||||
* 新增搜图提供配置项```ALLOW_GROUP_R18```:允许在群聊中使用r18参数
|
||||
* 新增自动更新插件```UPDATE_REMIND```:新版本提醒,原配置项```AUTO_UPDATE_ZHENXUN```改为自动更新升级
|
||||
* black_word新增当群权限为-1时不再检测该群
|
||||
* 修复非超级用户绑定原神cookie会被black_word阻拦
|
||||
* 修复微博热搜报错,发红包小bug [@pull/688](https://github.com/HibiKier/zhenxun_bot/pull/688)
|
||||
* 更多的中文提示
|
||||
|
||||
### 2022/5/26
|
||||
|
||||
* 修复\[滴滴滴]会被转义成[滴滴滴]导致无法触发的问题
|
||||
* 将一些错误以中文提示输出
|
||||
* 更新BT搜索源地址 [@pull/668](https://github.com/HibiKier/zhenxun_bot/pull/668)
|
||||
* 更新抽卡插件 [@pull/667](https://github.com/HibiKier/zhenxun_bot/pull/667)
|
||||
|
||||
### 2022/5/25
|
||||
|
||||
* 修复webui中CountLimit字段limit_type类型错误
|
||||
* 修改nickname插件:一处文案错误,添加敏感词 [@pull/624](https://github.com/HibiKier/zhenxun_bot/pull/624)
|
||||
* gamedraw的ba卡池搬运了过来并且进行了真寻的适配 [@pull/617](https://github.com/HibiKier/zhenxun_bot/pull/617)
|
||||
* feat: stream downloading and progress [@pull/607](https://github.com/HibiKier/zhenxun_bot/pull/607)
|
||||
* 修改翻译插件,添加缺失的冒号 [@pull/602](https://github.com/HibiKier/zhenxun_bot/pull/602)
|
||||
* 修复碧蓝航线/明日方舟up池解析出错的问题 [@pull/610](https://github.com/HibiKier/zhenxun_bot/pull/602)
|
||||
|
||||
### 2022/5/24
|
||||
|
||||
* fix: 修正了签到时日期时间的显示不补齐零的bug (符合日期时间表示法 ISO 8601)[@pull/600](https://github.com/HibiKier/zhenxun_bot/pull/600)
|
||||
* 更新"微博热搜"接口 [@pull/579](https://github.com/HibiKier/zhenxun_bot/pull/579)
|
||||
* refactor&fix(manager): modify argument [@pull/576](https://github.com/HibiKier/zhenxun_bot/pull/576)
|
||||
* 修复复读不能复读图片的问题 [@pull/573](https://github.com/HibiKier/zhenxun_bot/pull/573)
|
||||
* 修复抽卡插件:方舟抽卡的抽取和显示问题 [@pull/581](https://github.com/HibiKier/zhenxun_bot/pull/581)
|
||||
|
||||
### 2022/5/23 \[v0.1.5.6]
|
||||
|
||||
* 修复"清除已删除插件数据" [@pull/545](https://github.com/HibiKier/zhenxun_bot/pull/545)
|
||||
* 修复有置顶的up主B站动态获取失败 [@pull/552](https://github.com/HibiKier/zhenxun_bot/pull/552)
|
||||
* 添加pixiv搜图多关键词支持;修复p站搜图数量参数问题 [@pull/441](https://github.com/HibiKier/zhenxun_bot/pull/441)
|
||||
* 修复开箱更新价格错误传参
|
||||
* 修复pix无法正确查询uid
|
||||
* 新增色图插件添加配置项```ALLOW_GROUP_R18```:允许群聊中使用色图r
|
||||
* 新增PIX插件添加配置项```ALLOW_GROUP_SETU```:允许非超级用户使用-s参数
|
||||
* 新增PIX插件添加配置项```ALLOW_GROUP_R18```:允许非超级用户使用-r参数
|
||||
|
||||
### 2022/5/22 \[v0.1.5.4]
|
||||
|
||||
* 使用action自动更新poetry.lock [@pull/515](https://github.com/HibiKier/zhenxun_bot/pull/515)
|
||||
* fix(bilibili_sub): card is None and timeout [@pull/516](https://github.com/HibiKier/zhenxun_bot/pull/516)
|
||||
* 修复了epic有时获取新免费游戏消息时获取不到图片
|
||||
* 修复好感度满时签到出错(虽然是不可能满的
|
||||
* 修复原神资源图标下载路径错误
|
||||
* 修复自动更新群组可能失败
|
||||
|
||||
### 2022/5/21
|
||||
|
||||
* 修复搜番无结果时报错无正确反馈
|
||||
* 解锁了windows上无法使用playwright的限制
|
||||
* 修复p搜对应pid有多张图时出错,改为连续发送图片
|
||||
* 修复p搜对数字的错误判断
|
||||
* 修复添加商品折扣无法正确添加
|
||||
* 修复了bilibili订阅直播间订阅up名称不一致的问题
|
||||
* 修复原神玩家查询没开地图时报错
|
||||
* 最低priority修改为 999
|
||||
* 修复刷屏检测失效
|
||||
* 修复刷屏检测设置命令无法生效
|
||||
* 优化刷屏显示设置禁言时长显示,并改为分钟
|
||||
* 修复了多连开箱无法指定武器箱
|
||||
* 修复识番链接无法正确获取
|
||||
* 新增真寻入群时即刻刷新权限
|
||||
* 提高了微博热搜截图的等待时间
|
||||
|
||||
### 2022/5/19
|
||||
|
||||
* fix: mihoyo bbs api changed [@pull/357](https://github.com/HibiKier/zhenxun_bot/pull/357)
|
||||
* Add word_clouds [@pull/265](https://github.com/HibiKier/zhenxun_bot/pull/265)
|
||||
* Fix wrong live streamer name [@pull/284](https://github.com/HibiKier/zhenxun_bot/pull/284)
|
||||
|
||||
### 2022/5/16
|
||||
|
||||
* 词条支持图片和@问题 [@pull/160](https://github.com/HibiKier/zhenxun_bot/pull/160)
|
||||
|
||||
### 2022/5/15
|
||||
|
||||
* 修复了商店商品无法正确添加
|
||||
* 修复了多张色图无法正确发送
|
||||
|
||||
### 2022/5/14
|
||||
|
||||
* 修复B站动态生成失败的问题 [@pull/159](https://github.com/HibiKier/zhenxun_bot/pull/159)
|
||||
|
||||
### 2022/5/11
|
||||
|
||||
* fix: 更改p搜api,解决p搜无法使用的问题 [@pull/155](https://github.com/HibiKier/zhenxun_bot/pull/155)
|
||||
|
||||
### 2022/5/9 \[v0.1.5.3]
|
||||
|
||||
* 替换了疫情API
|
||||
* 修复了私聊.ban/.unban出错
|
||||
|
||||
### 2022/5/5
|
||||
|
||||
* 修改bilibili_sub插件在windows平台下报错 [@pull/153](https://github.com/HibiKier/zhenxun_bot/pull/153)
|
||||
|
||||
### 2022/5/3 \[v0.1.5.2]
|
||||
|
||||
* 商品使用函数可以添加特定参数,例如:user_id, group_id, ShopParam等以及自己提供的参数
|
||||
* 添加商品注册装饰器shop_register
|
||||
* 修复商品函数kwargs无法获取参数值
|
||||
|
||||
|
||||
### 2022/5/1
|
||||
|
||||
* 删除了`group_last_chat`插件(该功能可由`chat_history`替代
|
||||
* 新增敏感词检测(全新反击系统,是时候重拳出击了
|
||||
|
||||
### 2022/4/26
|
||||
|
||||
* 修复了群白名单无法正确添加
|
||||
* 优化了管理员帮助图片,背景图层将位于最下层
|
||||
* 修复了树脂140时不断提醒(未测试
|
||||
* 新增了消息记录的消息排行
|
||||
* WebUI新增CPU,内存,磁盘监控
|
||||
* WebUI新增资源文件夹统计可视化
|
||||
|
||||
### 2022/4/12
|
||||
|
||||
* 修复b了命令私聊出错
|
||||
|
||||
### 2022/4/10 \[v0.1.4.7]
|
||||
|
||||
* 新增消息记录模块
|
||||
* 丰富处理请求操作提示
|
||||
* web ui新增配置项修改
|
||||
|
||||
### 2022/4/9
|
||||
|
||||
* fix: 更新问题,戳一戳图片路径问题 [@pull/144](https://github.com/HibiKier/zhenxun_bot/pull/144)
|
||||
|
||||
### 2022/4/8
|
||||
|
||||
* 修复原神玩家查询
|
||||
|
||||
### 2022/4/6
|
||||
|
||||
* update search_type [@pull/143](https://github.com/HibiKier/zhenxun_bot/pull/143)
|
||||
|
||||
### 2022/4/5 \[v0.1.4.6]
|
||||
|
||||
* 修复web修改插件后帮助图片生成错误
|
||||
|
||||
### 2022/4/4 \[v0.1.4.5]
|
||||
|
||||
* 替换了bt搜索URL
|
||||
* 优化使用playwright的相关代码
|
||||
* 原神玩家查询新增层岩巨渊探索
|
||||
* 修复原神便笺角色头像黑框
|
||||
* 修复同意群聊请求错误
|
||||
* 提供webui方面的api
|
||||
* 新增web-ui(前端简易管理页面插件)插件
|
||||
|
||||
### 2022/3/21
|
||||
|
||||
* 修复statistics_handle.py乱码
|
||||
|
||||
### 2022/3/18 \[v0.1.4.4]
|
||||
|
||||
* 修复戳一戳无法功能关闭与ban禁用
|
||||
* 新增图片搜索 search_image
|
||||
|
||||
### 2022/3/7
|
||||
|
||||
* 优化增删权限插件
|
||||
|
||||
### 2022/3/6
|
||||
|
||||
* 修复树脂提醒无法开启
|
||||
* 修复p搜图片路径错误
|
||||
|
||||
### 2022/3/3 \[v0.1.4.3]
|
||||
|
||||
* 修复手动同意群聊请求依旧退出
|
||||
|
||||
### 2022/3/1 \[v0.1.4.2]
|
||||
|
||||
* 0.1.4内容
|
||||
|
||||
### 2022/2/27 \[v0.1.4.1]
|
||||
|
||||
* 优化抽卡
|
||||
|
||||
### 2022/2/25 \[v0.1.4]
|
||||
|
||||
* PIX提供配置MAX_ONCE_NUM2FORWARD:当单次发送图片超过指定张数且在群聊时,将转为合并消息
|
||||
* 修复点歌无法正确发送
|
||||
* 修复我有一个朋友有时文本会包含CQ码
|
||||
* 修复群欢消息被动控制文本未删除 [@pull/124](https://github.com/HibiKier/zhenxun_bot/pull/124)
|
||||
* message_builder.image不再提供参数:abspath
|
||||
|
||||
### 2022/2/23
|
||||
|
||||
* 插件状态将从已加载插件模块中读取
|
||||
* 修复b站订阅插件订阅失败问题
|
||||
* 修复重启命令无法使用
|
||||
|
||||
### 2022/2/21 \[v0.1.3.2]
|
||||
|
||||
* 群权限为-1时,超级用户发送的命令依旧生效
|
||||
* 当群权限为-1时,被动技能也将不会发送
|
||||
* 修复功能开关,b站转发解析,复读 ignore无法使用
|
||||
* 修复色图下载文件名与路径错误
|
||||
* 修复被动技能提醒有时无法删除控制文本
|
||||
|
||||
|
||||
### 2022/2/20 \[v0.1.3.1]
|
||||
|
||||
* 修复pix下载临时文件目录错误
|
||||
* 修复AI,天气,发送图片ignore导致无法使用
|
||||
* 修复纯文本被动技能提醒有时无法删除控制文本
|
||||
|
||||
### 2022/2/19 \[v0.1.3] (nonebot beta2!)
|
||||
|
||||
* 由于nonebot升级版本,提供更新建议(__该次升级将会导致nonebot.beta1以下的插件无法使用__
|
||||
* 保证services,utils,configs,plugins,basic_plugins,文件夹均为最新
|
||||
* 根目录有pyproject.toml与poetry.lock
|
||||
* 执行命令:
|
||||
* pip3 install poetry
|
||||
* poetry install
|
||||
* poetry shell
|
||||
* playwright install chromium
|
||||
* python3 bot.py
|
||||
|
||||
|
||||
* 适配nonebot.beta2
|
||||
* 删除图片搜索 nonebot_plugin_picsearcher
|
||||
* 替换cos api
|
||||
* 原神签到树脂提醒新增绑定群里,在某群绑定uid就会在某群发送提醒信息(有好友则私聊,需要重新绑定uid
|
||||
* 修改update_info.json
|
||||
* 修复原神资源查询下载数据失败时导致报错
|
||||
* 优化BuildImage.circle()锯齿问题 [@pull/109](https://github.com/HibiKier/zhenxun_bot/pull/109)
|
||||
* epic restful 替换 [@pull/119](https://github.com/HibiKier/zhenxun_bot/pull/119)
|
||||
* fix: 修复远古时期残留的epic推送问题 [@pull/122](https://github.com/HibiKier/zhenxun_bot/pull/122)
|
||||
|
||||
### 2022/2/11
|
||||
|
||||
* 修复pix不使用反代无法下载图片
|
||||
|
||||
### 2022/2/10 \[v0.1.1]
|
||||
|
||||
* 修复购买道具出错
|
||||
|
||||
### 2022/2/9 \[v0.1]
|
||||
|
||||
* 新增原神自动签到和手动签到
|
||||
* 新增原神树脂提醒
|
||||
* 新增手动重载Config.yaml命令以及重载配置定时任务(极少部分帮助或配置可能需要重启
|
||||
* 修改了发送本地图库的matcher,改为on_message
|
||||
* register_use可以通过返回值发送消息
|
||||
* 修复修改商品时限制时间出错
|
||||
* 修复超时商品依旧可以被购买
|
||||
|
||||
### 2022/1/16 \[v0.0.9.0]
|
||||
|
||||
* Ai提供文本敏感词过滤器
|
||||
* 疫情插件适配新版腾讯API
|
||||
* 修复/t回复带空格切分
|
||||
* 修复原神玩家查询缺少渊下宫和稻妻家园以及角色不完全
|
||||
* 修复方法 text2image 中 padding 和 font 无法对纯文本生效
|
||||
* 修复签到图片中信息并未使用配置文件中的色图概率
|
||||
* 修改原神大地图合成方式,改为先压缩再合成
|
||||
* bag_user弃用字段props(该字段会在下次更新删除),使用新字段property
|
||||
* 数据库中所有belonging_group统一修改为group_id
|
||||
* 商店将registered_use和register_goods更名为register_use何register_goods
|
||||
* 商品注册提供了kwargs参数提供:
|
||||
* bot
|
||||
* event
|
||||
* 特殊字段
|
||||
* “send_success_msg”(发送成功的交互信息->即:使用道具 {name} {num} 次成功)
|
||||
* “_max_num_limit”(该道具单次使用的最多个数,默认1)
|
||||
|
||||
### 2022/1/5 \[v0.0.8.2]
|
||||
|
||||
* 提供金币消费hook,可在plugins2settings.yaml中配置该功能需要消费的金币
|
||||
* 商店插件将作为内置插件移动至basic_plugins
|
||||
* 商店插件通过export提供了方法,不需要修改商店插件代码添加商品数据和生效方法
|
||||
* 修改了hook插件顺序,主要以auth_hook为主
|
||||
* 修改商店图片样式
|
||||
* 取消每次启动更新城市列表(首次除外),采用定时更新,加快bot启动速度
|
||||
* 取消每次启动时截取今日素材,采用调用时截取保存,加快bot启动速度
|
||||
* 更新色图时当图片404时会删除并替换
|
||||
* 疫情消息回复改为图片
|
||||
* 修复商店折扣和限时时间无法生效
|
||||
* 修复原神玩家查询尘歌壶缺少图片
|
||||
|
||||
### 2021/12/26
|
||||
|
||||
* 修复群词条问题 空格 会被录入导致不断回复
|
||||
* 修复米游社app替换api导致无法正常查询
|
||||
|
||||
### 2021/12/24
|
||||
|
||||
* 支持国际疫情数据查询 [@pull/99](https://github.com/HibiKier/zhenxun_bot/pull/99)
|
||||
|
||||
### 2021/12/20
|
||||
|
||||
* 只有发布小于存储时间的新动态/视频的时候才获取并推送 [@pull/96](https://github.com/HibiKier/zhenxun_bot/pull/96)
|
||||
|
||||
### 2021/12/16 \[v0.0.7.0]
|
||||
|
||||
* 提供了真寻群聊功能总开关和对应默认配置项,命令:休息吧 醒来
|
||||
* 新增原神玩家查询,原神便笺查询
|
||||
* 群功能管理提供全部开启/关闭命令:开启/关闭全部功能
|
||||
* 提供主要数据自动备份,且提供自定义配置项
|
||||
* 提供命令:关于,用于介绍Bot之类的
|
||||
* 新增命令exec,用于执行sql语句
|
||||
* 签到提供参数 "all",用于签到所有群聊
|
||||
* Ban提醒提供cd
|
||||
* 本地图库提供配置项SHOW_ID,用于设置发送图片时是否显示id
|
||||
* 色图和PIX提供配置项SHOW_INFO,用于设置发送图片时是否显示图片信息
|
||||
* 所有被动技能提供了进群默认状态配置项
|
||||
* 修复添加权限第二种添加形式无法正确添加正确的权限
|
||||
* 修复签到获取好感度卡时金币不会增加
|
||||
* 修复当红包数量不合法时依旧扣除金币
|
||||
* 修复金币红包再次使用塞红包时无法正确退回上次未开完的金币
|
||||
* 修复 滴滴滴- 只包含图片时不会发送至管理员
|
||||
* 修复添加权限等级错误
|
||||
* 修复群词条以bot名称为开头时无法正确触发
|
||||
* 修改了权限插件加载顺序防止小概率优先加载权限插件引起报错
|
||||
* 本地图库新图库会统一建立在resource/img/image_management文件夹下,如果该文件夹内未找到图库,会从上级目录查找(即:resource/img/)
|
||||
|
||||
<br>
|
||||
|
||||
__..... 更多更新信息请查看文档__
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__: v0.1.6.3-fix1
|
||||
__version__: v0.1.6.6
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
from configs.config import Config
|
||||
import nonebot
|
||||
|
||||
@@ -27,4 +29,4 @@ Config.add_plugin_config(
|
||||
default_value=5
|
||||
)
|
||||
|
||||
nonebot.load_plugins("basic_plugins/admin_bot_manage")
|
||||
nonebot.load_plugins(str(Path(__file__).parent.resolve()))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from typing import List
|
||||
from nonebot.adapters.onebot.v11.message import MessageSegment
|
||||
from services.log import logger
|
||||
from configs.path_config import DATA_PATH
|
||||
from configs.path_config import DATA_PATH, IMAGE_PATH
|
||||
from utils.message_builder import image
|
||||
from utils.utils import get_bot, get_matchers
|
||||
from pathlib import Path
|
||||
@@ -16,53 +16,78 @@ from utils.http_utils import AsyncHttpx
|
||||
import asyncio
|
||||
import time
|
||||
import os
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
async def group_current_status(group_id: int) -> str:
|
||||
"""
|
||||
获取当前所有通知的开关
|
||||
:param group_id: 群号
|
||||
"""
|
||||
rst = "[被动技能 状态]\n"
|
||||
_data = group_manager.get_task_data()
|
||||
for task in _data.keys():
|
||||
rst += f'{_data[task]}: {"√" if await group_manager.check_group_task_status(group_id, task) else "×"}\n'
|
||||
return rst.strip()
|
||||
import ujson as json
|
||||
|
||||
|
||||
custom_welcome_msg_json = (
|
||||
Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
|
||||
)
|
||||
|
||||
ICON_PATH = IMAGE_PATH / 'other'
|
||||
|
||||
|
||||
async def group_current_status(group_id: int) -> str:
|
||||
"""
|
||||
说明:
|
||||
获取当前群聊所有通知的开关
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
_data = group_manager.get_task_data()
|
||||
image_list = []
|
||||
for i, task in enumerate(_data):
|
||||
name = _data[task]
|
||||
name_image = BuildImage(0, 0, plain_text=f"{i+1}.{name}", font_size=20)
|
||||
bk = BuildImage(name_image.w + 200, name_image.h + 20, color=(103, 177, 109), font_size=15)
|
||||
await bk.apaste(name_image, (10, 0), True, "by_height")
|
||||
a_icon = BuildImage(40, 40, background=ICON_PATH / "btn_false.png")
|
||||
if group_manager.check_group_task_status(group_id, task):
|
||||
a_icon = BuildImage(40, 40, background=ICON_PATH / "btn_true.png")
|
||||
b_icon = BuildImage(40, 40, background=ICON_PATH / "btn_false.png")
|
||||
if group_manager.check_task_super_status(task):
|
||||
b_icon = BuildImage(40, 40, background=ICON_PATH / "btn_true.png")
|
||||
await bk.atext((name_image.w + 20, 10), "状态")
|
||||
await bk.apaste(a_icon, (name_image.w + 50, 0), True)
|
||||
await bk.atext((name_image.w + 100, 10), "全局")
|
||||
await bk.apaste(b_icon, (name_image.w + 130, 0), True)
|
||||
image_list.append(bk)
|
||||
w = max([x.w for x in image_list])
|
||||
h = sum([x.h + 10 for x in image_list])
|
||||
A = BuildImage(w + 20, h + 70, font_size=30, color=(119, 97, 177))
|
||||
await A.atext((15, 20), "群被动状态")
|
||||
curr_h = 75
|
||||
for img in image_list:
|
||||
# await img.acircle_corner()
|
||||
await A.apaste(img, (0, curr_h), True)
|
||||
curr_h += img.h + 10
|
||||
return A.pic2bs4()
|
||||
|
||||
|
||||
async def custom_group_welcome(
|
||||
msg: str, imgs: List[str], user_id: int, group_id: int
|
||||
msg: str, img_list: List[str], user_id: int, group_id: int
|
||||
) -> str:
|
||||
"""
|
||||
替换群欢迎消息
|
||||
:param msg: 欢迎消息文本
|
||||
:param imgs: 欢迎消息图片,只取第一张
|
||||
:param user_id: 用户id,用于log记录
|
||||
:param group_id: 群号
|
||||
说明:
|
||||
替换群欢迎消息
|
||||
参数:
|
||||
:param msg: 欢迎消息文本
|
||||
:param img_list: 欢迎消息图片,只取第一张
|
||||
:param user_id: 用户id,用于log记录
|
||||
:param group_id: 群号
|
||||
"""
|
||||
img_result = ""
|
||||
img = imgs[0] if imgs else ""
|
||||
result = ""
|
||||
img = img_list[0] if img_list else ""
|
||||
if (DATA_PATH / f"custom_welcome_msg/{group_id}.jpg").exists():
|
||||
(DATA_PATH / f"custom_welcome_msg/{group_id}.jpg").unlink()
|
||||
data = {}
|
||||
if not custom_welcome_msg_json.exists():
|
||||
custom_welcome_msg_json.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {}
|
||||
else:
|
||||
try:
|
||||
data = json.load(open(custom_welcome_msg_json, "r"))
|
||||
except FileNotFoundError:
|
||||
data = {}
|
||||
pass
|
||||
try:
|
||||
if msg:
|
||||
data[str(group_id)] = str(msg)
|
||||
@@ -86,14 +111,48 @@ async def custom_group_welcome(
|
||||
task_data = None
|
||||
|
||||
|
||||
async def change_group_switch(cmd: str, group_id: int, is_super: bool = False):
|
||||
def change_global_task_status(cmd: str) -> str:
|
||||
"""
|
||||
说明:
|
||||
修改全局被动任务状态
|
||||
参数:
|
||||
:param cmd: 功能名称
|
||||
"""
|
||||
global task_data
|
||||
if not task_data:
|
||||
task_data = group_manager.get_task_data()
|
||||
status = cmd[:2]
|
||||
_cmd = cmd[4:]
|
||||
if '全部被动' in cmd:
|
||||
for task in task_data:
|
||||
if status == "开启":
|
||||
group_manager.open_global_task(task)
|
||||
else:
|
||||
group_manager.close_global_task(task)
|
||||
group_manager.save()
|
||||
return f"已 {status} 全局全部被动技能!"
|
||||
else:
|
||||
modules = [x for x in task_data if task_data[x].lower() == _cmd.lower()]
|
||||
if not modules:
|
||||
return '未查询到该被动任务'
|
||||
if status == "开启":
|
||||
group_manager.open_global_task(modules[0])
|
||||
else:
|
||||
group_manager.close_global_task(modules[0])
|
||||
group_manager.save()
|
||||
return f"已 {status} 全局{_cmd}"
|
||||
|
||||
|
||||
async def change_group_switch(cmd: str, group_id: int, is_super: bool = False) -> str:
|
||||
"""
|
||||
修改群功能状态
|
||||
:param cmd: 功能名称
|
||||
:param group_id: 群号
|
||||
:param is_super: 是否位超级用户,超级用户用于私聊开关功能状态
|
||||
说明:
|
||||
修改群功能状态
|
||||
参数:
|
||||
:param cmd: 功能名称
|
||||
:param group_id: 群号
|
||||
:param is_super: 是否位超级用户,超级用户用于私聊开关功能状态
|
||||
"""
|
||||
global task_data
|
||||
if not task_data:
|
||||
task_data = group_manager.get_task_data()
|
||||
group_help_file = DATA_PATH / "group_help" / f"{group_id}.png"
|
||||
@@ -104,43 +163,44 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False):
|
||||
if cmd == "全部被动":
|
||||
for task in task_data:
|
||||
if status == "开启":
|
||||
if not await group_manager.check_group_task_status(group_id, task):
|
||||
await group_manager.open_group_task(group_id, task)
|
||||
if not group_manager.check_group_task_status(group_id, task):
|
||||
group_manager.open_group_task(group_id, task)
|
||||
else:
|
||||
if await group_manager.check_group_task_status(group_id, task):
|
||||
await group_manager.close_group_task(group_id, task)
|
||||
if group_manager.check_group_task_status(group_id, task):
|
||||
group_manager.close_group_task(group_id, task)
|
||||
if group_help_file.exists():
|
||||
group_help_file.unlink()
|
||||
return f"已 {status} 全部被动技能!"
|
||||
if cmd == "全部功能":
|
||||
for f in plugins2settings_manager.get_data():
|
||||
if status == "开启":
|
||||
group_manager.unblock_plugin(f, group_id)
|
||||
group_manager.unblock_plugin(f, group_id, False)
|
||||
else:
|
||||
group_manager.block_plugin(f, group_id)
|
||||
group_manager.block_plugin(f, group_id, False)
|
||||
group_manager.save()
|
||||
if group_help_file.exists():
|
||||
group_help_file.unlink()
|
||||
return f"已 {status} 全部功能!"
|
||||
if cmd in [task_data[x] for x in task_data.keys()]:
|
||||
if cmd.lower() in [task_data[x].lower() for x in task_data.keys()]:
|
||||
type_ = "task"
|
||||
modules = [x for x in task_data.keys() if task_data[x] == cmd]
|
||||
modules = [x for x in task_data.keys() if task_data[x].lower() == cmd.lower()]
|
||||
for module in modules:
|
||||
if is_super:
|
||||
module = f"{module}:super"
|
||||
if status == "开启":
|
||||
if type_ == "task":
|
||||
if await group_manager.check_group_task_status(group_id, module):
|
||||
if group_manager.check_group_task_status(group_id, module):
|
||||
return f"被动 {task_data[module]} 正处于开启状态!不要重复开启."
|
||||
await group_manager.open_group_task(group_id, module)
|
||||
group_manager.open_group_task(group_id, module)
|
||||
else:
|
||||
if group_manager.get_plugin_status(module, group_id):
|
||||
return f"功能 {cmd} 正处于开启状态!不要重复开启."
|
||||
group_manager.unblock_plugin(module, group_id)
|
||||
else:
|
||||
if type_ == "task":
|
||||
if not await group_manager.check_group_task_status(group_id, module):
|
||||
if not group_manager.check_group_task_status(group_id, module):
|
||||
return f"被动 {task_data[module]} 正处于关闭状态!不要重复关闭."
|
||||
await group_manager.close_group_task(group_id, module)
|
||||
group_manager.close_group_task(group_id, module)
|
||||
else:
|
||||
if not group_manager.get_plugin_status(module, group_id):
|
||||
return f"功能 {cmd} 正处于关闭状态!不要重复关闭."
|
||||
@@ -160,9 +220,11 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False):
|
||||
|
||||
def set_plugin_status(cmd: str, block_type: str = "all"):
|
||||
"""
|
||||
设置插件功能状态(超级用户使用)
|
||||
:param cmd: 功能名称
|
||||
:param block_type: 限制类型, 'all': 私聊+群里, 'private': 私聊, 'group': 群聊
|
||||
说明:
|
||||
设置插件功能状态(超级用户使用)
|
||||
参数:
|
||||
:param cmd: 功能名称
|
||||
:param block_type: 限制类型, 'all': 私聊+群里, 'private': 私聊, 'group': 群聊
|
||||
"""
|
||||
status = cmd[:2]
|
||||
cmd = cmd[2:]
|
||||
@@ -178,14 +240,16 @@ def set_plugin_status(cmd: str, block_type: str = "all"):
|
||||
|
||||
async def get_plugin_status():
|
||||
"""
|
||||
获取功能状态
|
||||
说明:
|
||||
获取功能状态
|
||||
"""
|
||||
return await asyncio.get_event_loop().run_in_executor(None, _get_plugin_status)
|
||||
|
||||
|
||||
def _get_plugin_status() -> MessageSegment:
|
||||
"""
|
||||
合成功能状态图片
|
||||
说明:
|
||||
合成功能状态图片
|
||||
"""
|
||||
rst = "\t功能\n"
|
||||
flag_str = "状态".rjust(4) + "\n"
|
||||
@@ -197,7 +261,7 @@ def _get_plugin_status() -> MessageSegment:
|
||||
flag = plugins_manager.get_plugin_block_type(module)
|
||||
flag = flag.upper() + " CLOSE" if flag else "OPEN"
|
||||
try:
|
||||
plugin_name = plugins_manager.get(module)["plugin_name"]
|
||||
plugin_name = plugins_manager.get(module).plugin_name
|
||||
if (
|
||||
"[Hidden]" in plugin_name
|
||||
or "[Admin]" in plugin_name
|
||||
@@ -207,7 +271,7 @@ def _get_plugin_status() -> MessageSegment:
|
||||
rst += f"{plugin_name}"
|
||||
except KeyError:
|
||||
rst += f"{module}"
|
||||
if plugins_manager.get(module)["error"]:
|
||||
if plugins_manager.get(module).error:
|
||||
rst += "[ERROR]"
|
||||
rst += "\n"
|
||||
flag_str += f"{flag}\n"
|
||||
@@ -224,9 +288,11 @@ def _get_plugin_status() -> MessageSegment:
|
||||
|
||||
async def update_member_info(group_id: int, remind_superuser: bool = False) -> bool:
|
||||
"""
|
||||
更新群成员信息
|
||||
:param group_id: 群号
|
||||
:param remind_superuser: 失败信息提醒超级用户
|
||||
说明:
|
||||
更新群成员信息
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param remind_superuser: 失败信息提醒超级用户
|
||||
"""
|
||||
bot = get_bot()
|
||||
_group_user_list = await bot.get_group_member_list(group_id=group_id)
|
||||
@@ -237,14 +303,10 @@ async def update_member_info(group_id: int, remind_superuser: bool = False) -> b
|
||||
nickname = user_info["card"] or user_info["nickname"]
|
||||
async with db.transaction():
|
||||
# 更新权限
|
||||
if (
|
||||
user_info["role"]
|
||||
in [
|
||||
"owner",
|
||||
"admin",
|
||||
]
|
||||
and not await LevelUser.is_group_flag(user_info["user_id"], group_id)
|
||||
):
|
||||
if user_info["role"] in [
|
||||
"owner",
|
||||
"admin",
|
||||
] and not await LevelUser.is_group_flag(user_info["user_id"], group_id):
|
||||
await LevelUser.set_level(
|
||||
user_info["user_id"],
|
||||
user_info["group_id"],
|
||||
@@ -306,9 +368,11 @@ async def update_member_info(group_id: int, remind_superuser: bool = False) -> b
|
||||
|
||||
def set_group_bot_status(group_id: int, status: bool) -> str:
|
||||
"""
|
||||
设置群聊bot开关状态
|
||||
:param group_id: 群号
|
||||
:param status: 状态
|
||||
说明:
|
||||
设置群聊bot开关状态
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
:param status: 状态
|
||||
"""
|
||||
if status:
|
||||
if group_manager.check_group_bot_status(group_id):
|
||||
@@ -317,7 +381,4 @@ def set_group_bot_status(group_id: int, status: bool) -> str:
|
||||
return "呜..醒来了..."
|
||||
else:
|
||||
group_manager.shutdown_group_bot_status(group_id)
|
||||
# for x in group_manager.get_task_data():
|
||||
# group_manager.close_group_task(group_id, x)
|
||||
return "那我先睡觉了..."
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
from typing import List
|
||||
|
||||
from nonebot import on_command
|
||||
from utils.utils import get_message_img
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
|
||||
from nonebot.params import CommandArg
|
||||
from ._data_source import custom_group_welcome
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from configs.config import Config
|
||||
from services.log import logger
|
||||
from utils.depends import ImageList
|
||||
|
||||
|
||||
__zx_plugin_name__ = "自定义进群欢迎消息 [Admin]"
|
||||
@@ -35,9 +37,8 @@ custom_welcome = on_command(
|
||||
|
||||
|
||||
@custom_welcome.handle()
|
||||
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
async def _(event: GroupMessageEvent, arg: Message = CommandArg(), img: List[str] = ImageList()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
img = get_message_img(event.json())
|
||||
if not msg and not img:
|
||||
await custom_welcome.finish(__plugin_usage__)
|
||||
try:
|
||||
|
||||
@@ -2,30 +2,37 @@ from nonebot.adapters.onebot.v11 import Event
|
||||
from utils.manager import group_manager, plugins2settings_manager
|
||||
from utils.utils import get_message_text
|
||||
from services.log import logger
|
||||
import time
|
||||
|
||||
cmd = []
|
||||
|
||||
v = time.time()
|
||||
|
||||
|
||||
def switch_rule(event: Event) -> bool:
|
||||
"""
|
||||
检测文本是否是关闭功能命令
|
||||
:param event: pass
|
||||
说明:
|
||||
检测文本是否是关闭功能命令
|
||||
参数:
|
||||
:param event: pass
|
||||
"""
|
||||
global cmd
|
||||
global cmd, v
|
||||
try:
|
||||
if not cmd:
|
||||
if not cmd or time.time() - v > 60 * 60:
|
||||
cmd = ["关闭全部被动", "开启全部被动", "开启全部功能", "关闭全部功能"]
|
||||
_data = group_manager.get_task_data()
|
||||
for key in _data:
|
||||
cmd.append(f"开启{_data[key]}")
|
||||
cmd.append(f"关闭{_data[key]}")
|
||||
cmd.append(f"开启被动{_data[key]}")
|
||||
cmd.append(f"关闭被动{_data[key]}")
|
||||
cmd.append(f"开启 {_data[key]}")
|
||||
cmd.append(f"关闭 {_data[key]}")
|
||||
_data = plugins2settings_manager.get_data()
|
||||
for key in _data:
|
||||
for key in _data.keys():
|
||||
try:
|
||||
if isinstance(_data[key]["cmd"], list):
|
||||
for x in _data[key]["cmd"]:
|
||||
if isinstance(_data[key].cmd, list):
|
||||
for x in _data[key].cmd:
|
||||
cmd.append(f"开启{x}")
|
||||
cmd.append(f"关闭{x}")
|
||||
cmd.append(f"开启 {x}")
|
||||
@@ -37,6 +44,7 @@ def switch_rule(event: Event) -> bool:
|
||||
cmd.append(f"关闭 {key}")
|
||||
except KeyError:
|
||||
pass
|
||||
v = time.time()
|
||||
msg = get_message_text(event.json()).split()
|
||||
msg = msg[0] if msg else ""
|
||||
return msg in cmd
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, GROUP
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, GROUP, PrivateMessageEvent
|
||||
from nonebot import on_command, on_message, on_regex
|
||||
from nonebot.params import RegexGroup
|
||||
|
||||
from utils.message_builder import image
|
||||
from ._data_source import (
|
||||
change_group_switch,
|
||||
set_plugin_status,
|
||||
get_plugin_status,
|
||||
group_current_status,
|
||||
set_group_bot_status
|
||||
set_group_bot_status, change_global_task_status
|
||||
)
|
||||
from services.log import logger
|
||||
from configs.config import NICKNAME, Config
|
||||
@@ -31,11 +33,12 @@ usage:
|
||||
""".strip()
|
||||
__plugin_superuser_usage__ = """
|
||||
usage:
|
||||
功能总开关与指定群禁用
|
||||
(私聊)功能总开关与指定群禁用
|
||||
指令:
|
||||
功能状态
|
||||
开启/关闭[功能] [group]
|
||||
开启/关闭[功能] ['private'/'group']
|
||||
开启被动/关闭被动[被动名称] # 全局被动控制
|
||||
""".strip()
|
||||
__plugin_des__ = "群内功能开关"
|
||||
__plugin_cmd__ = [
|
||||
@@ -74,7 +77,9 @@ async def _(bot: Bot, event: MessageEvent):
|
||||
if str(event.user_id) in bot.config.superusers:
|
||||
block_type = " ".join(get_message_text(event.json()).split()[1:])
|
||||
block_type = block_type if block_type else "a"
|
||||
if is_number(block_type):
|
||||
if ("关闭被动" in _cmd or "开启被动" in _cmd) and isinstance(event, PrivateMessageEvent):
|
||||
await switch_rule_matcher.send(change_global_task_status(_cmd))
|
||||
elif is_number(block_type):
|
||||
if not int(block_type) in [
|
||||
g["group_id"]
|
||||
for g in await bot.get_group_list()
|
||||
@@ -85,7 +90,7 @@ async def _(bot: Bot, event: MessageEvent):
|
||||
"group_name"
|
||||
]
|
||||
await switch_rule_matcher.send(
|
||||
f"已禁用群聊 {group_name}({block_type}) 的 {_cmd[2:]} 功能"
|
||||
f"已{_cmd[:2]}群聊 {group_name}({block_type}) 的 {_cmd[2:]} 功能"
|
||||
)
|
||||
elif block_type in ["all", "private", "group", "a", "p", "g"]:
|
||||
block_type = "all" if block_type == "a" else block_type
|
||||
@@ -110,7 +115,7 @@ async def _():
|
||||
|
||||
@group_task_status.handle()
|
||||
async def _(event: GroupMessageEvent):
|
||||
await group_task_status.send(await group_current_status(event.group_id))
|
||||
await group_task_status.send(image(b64=await group_current_status(event.group_id)))
|
||||
|
||||
|
||||
@group_status.handle()
|
||||
|
||||
@@ -3,7 +3,7 @@ from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from utils.message_builder import image
|
||||
from .data_source import create_help_image, admin_help_image
|
||||
from .data_source import create_help_image, ADMIN_HELP_IMAGE
|
||||
|
||||
|
||||
__zx_plugin_name__ = '管理帮助 [Admin]'
|
||||
@@ -16,12 +16,12 @@ __plugin_settings__ = {
|
||||
|
||||
admin_help = on_command("管理员帮助", aliases={"管理帮助"}, priority=5, block=True)
|
||||
|
||||
if admin_help_image.exists():
|
||||
admin_help_image.unlink()
|
||||
if ADMIN_HELP_IMAGE.exists():
|
||||
ADMIN_HELP_IMAGE.unlink()
|
||||
|
||||
|
||||
@admin_help.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if not admin_help_image.exists():
|
||||
if not ADMIN_HELP_IMAGE.exists():
|
||||
await create_help_image()
|
||||
await admin_help.send(image('admin_help_img.png'))
|
||||
await admin_help.send(image(ADMIN_HELP_IMAGE))
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from services.log import logger
|
||||
from utils.utils import get_matchers
|
||||
from utils.manager import group_manager
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from nonebot import Driver
|
||||
import nonebot
|
||||
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from nonebot import Driver
|
||||
from services.log import logger
|
||||
from utils.image_template import help_template
|
||||
from utils.image_utils import (BuildImage, build_sort_image, group_image,
|
||||
text2image)
|
||||
from utils.manager import group_manager, plugin_data_manager
|
||||
from utils.manager.models import PluginType
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
background = IMAGE_PATH / "background" / "0.png"
|
||||
|
||||
admin_help_image = IMAGE_PATH / 'admin_help_img.png'
|
||||
ADMIN_HELP_IMAGE = IMAGE_PATH / "admin_help_img.png"
|
||||
|
||||
|
||||
@driver.on_bot_connect
|
||||
async def init_task(bot: Bot = None):
|
||||
async def init_task():
|
||||
if not group_manager.get_task_data():
|
||||
await group_manager.init_group_task()
|
||||
logger.info(f'已成功加载 {len(group_manager.get_task_data())} 个被动技能.')
|
||||
group_manager.load_task()
|
||||
logger.info(f"已成功加载 {len(group_manager.get_task_data())} 个被动技能.")
|
||||
|
||||
|
||||
async def create_help_image():
|
||||
@@ -33,58 +33,55 @@ async def _create_help_image():
|
||||
"""
|
||||
创建管理员帮助图片
|
||||
"""
|
||||
_matchers = get_matchers()
|
||||
_plugin_name_list = []
|
||||
width = 0
|
||||
_plugin_level = {}
|
||||
for matcher in _matchers:
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
_module = _plugin.module
|
||||
if ADMIN_HELP_IMAGE.exists():
|
||||
return
|
||||
plugin_data_ = plugin_data_manager.get_data()
|
||||
image_list = []
|
||||
task_list = []
|
||||
for plugin_data in [plugin_data_[x] for x in plugin_data_]:
|
||||
try:
|
||||
plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
except AttributeError:
|
||||
continue
|
||||
try:
|
||||
if (
|
||||
"[admin]" in plugin_name.lower()
|
||||
and plugin_name not in _plugin_name_list
|
||||
and plugin_name != "管理帮助 [Admin]"
|
||||
):
|
||||
_plugin_name_list.append(plugin_name)
|
||||
plugin_settings = _module.__getattribute__("__plugin_settings__")
|
||||
plugin_des = _module.__getattribute__("__plugin_des__")
|
||||
plugin_cmd = _module.__getattribute__("__plugin_cmd__")
|
||||
plugin_cmd = [x for x in plugin_cmd if "[_superuser]" not in x]
|
||||
admin_level = int(plugin_settings["admin_level"])
|
||||
if _plugin_level.get(admin_level):
|
||||
_plugin_level[admin_level].append(
|
||||
f"[{admin_level}] {plugin_des} -> " + " / ".join(plugin_cmd)
|
||||
)
|
||||
else:
|
||||
_plugin_level[admin_level] = [
|
||||
f"[{admin_level}] {plugin_des} -> " + " / ".join(plugin_cmd)
|
||||
]
|
||||
x = len(f"[{admin_level}] {plugin_des} -> " + " / ".join(plugin_cmd)) * 23
|
||||
width = width if width > x else x
|
||||
except AttributeError:
|
||||
logger.warning(f"获取管理插件 {matcher.plugin_name}: {plugin_name} 设置失败...")
|
||||
help_str = "* 注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数 *\n\n" \
|
||||
"[权限等级] 管理员帮助:\n\n"
|
||||
x = list(_plugin_level.keys())
|
||||
x.sort()
|
||||
for level in x:
|
||||
for help_ in _plugin_level[level]:
|
||||
help_str += f"\t{help_}\n\n"
|
||||
help_str += '-----[被动技能开关]-----\n\n'
|
||||
task_data = group_manager.get_task_data()
|
||||
for i, x in enumerate(task_data.keys()):
|
||||
help_str += f'{i+1}.开启/关闭{task_data[x]}\n\n'
|
||||
height = len(help_str.split("\n")) * 33
|
||||
A = BuildImage(width, height, font_size=24)
|
||||
_background = BuildImage(width, height, background=background)
|
||||
await A.apaste(_background, alpha=True)
|
||||
await A.atext((150, 110), help_str)
|
||||
await A.asave(admin_help_image)
|
||||
logger.info(f'已成功加载 {len(_plugin_name_list)} 条管理员命令')
|
||||
|
||||
|
||||
usage = None
|
||||
if plugin_data.plugin_type == PluginType.ADMIN and plugin_data.usage:
|
||||
usage = await text2image(
|
||||
plugin_data.usage, padding=5, color=(204, 196, 151)
|
||||
)
|
||||
if usage:
|
||||
await usage.acircle_corner()
|
||||
level = 5
|
||||
if plugin_data.plugin_setting:
|
||||
level = plugin_data.plugin_setting.level or level
|
||||
image = await help_template(plugin_data.name + f"[{level}]", usage)
|
||||
image_list.append(image)
|
||||
if plugin_data.task:
|
||||
for x in plugin_data.task.keys():
|
||||
task_list.append(plugin_data.task[x])
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"获取群管理员插件 {plugin_data.model}: {plugin_data.name} 设置失败... {type(e)}:{e}"
|
||||
)
|
||||
task_str = "\n".join(task_list)
|
||||
task_str = "通过 开启/关闭 来控制群被动\n----------\n" + task_str
|
||||
task_image = await text2image(task_str, padding=5, color=(204, 196, 151))
|
||||
task_image = await help_template("被动任务", task_image)
|
||||
image_list.append(task_image)
|
||||
image_group, _ = group_image(image_list)
|
||||
A = await build_sort_image(image_group, color="#f9f6f2", padding_top=180)
|
||||
await A.apaste(
|
||||
BuildImage(0, 0, font="CJGaoDeGuo.otf", plain_text="群管理员帮助", font_size=50),
|
||||
(50, 30),
|
||||
True,
|
||||
)
|
||||
await A.apaste(
|
||||
BuildImage(
|
||||
0,
|
||||
0,
|
||||
font="CJGaoDeGuo.otf",
|
||||
plain_text="注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数",
|
||||
font_size=30,
|
||||
font_color="red",
|
||||
),
|
||||
(50, 90),
|
||||
True,
|
||||
)
|
||||
await A.asave(ADMIN_HELP_IMAGE)
|
||||
logger.info(f"已成功加载 {len(image_list)} 条管理员命令")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Tuple
|
||||
from typing import Tuple, List
|
||||
|
||||
from configs.config import NICKNAME, Config
|
||||
from models.ban_user import BanUser
|
||||
@@ -9,6 +9,7 @@ from nonebot.adapters.onebot.v11 import (Bot, GroupMessageEvent, Message,
|
||||
from nonebot.params import Command, CommandArg
|
||||
from nonebot.permission import SUPERUSER
|
||||
from services.log import logger
|
||||
from utils.depends import AtList
|
||||
from utils.utils import get_message_at, is_number
|
||||
|
||||
from .data_source import a_ban, parse_ban_time
|
||||
@@ -69,10 +70,10 @@ async def _(
|
||||
event: GroupMessageEvent,
|
||||
cmd: Tuple[str, ...] = Command(),
|
||||
arg: Message = CommandArg(),
|
||||
qq: List[int] = AtList()
|
||||
):
|
||||
cmd = cmd[0]
|
||||
result = ""
|
||||
qq = get_message_at(event.json())
|
||||
if qq:
|
||||
qq = qq[0]
|
||||
user_name = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
|
||||
@@ -127,7 +128,6 @@ async def _(
|
||||
if str(event.user_id) in bot.config.superusers:
|
||||
msg_splt = msg.split()
|
||||
if is_number(msg_splt[0]):
|
||||
|
||||
qq = int(msg_splt[0])
|
||||
msg = msg_splt[1:]
|
||||
if cmd in [".ban", "/ban"]:
|
||||
|
||||
@@ -40,11 +40,10 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
rst = ""
|
||||
for img in img_list:
|
||||
rst += image(img)
|
||||
gl = await bot.get_group_list()
|
||||
gl = [
|
||||
g["group_id"]
|
||||
for g in gl
|
||||
if await group_manager.check_group_task_status(g["group_id"], "broadcast")
|
||||
for g in await bot.get_group_list()
|
||||
if group_manager.check_group_task_status(g["group_id"], "broadcast")
|
||||
]
|
||||
g_cnt = len(gl)
|
||||
cnt = 0
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import nonebot
|
||||
from pathlib import Path
|
||||
|
||||
nonebot.load_plugins("basic_plugins/chat_history")
|
||||
nonebot.load_plugins(str(Path(__file__).parent.resolve()))
|
||||
|
||||
@@ -2,7 +2,7 @@ from configs.config import Config
|
||||
from models.chat_history import ChatHistory
|
||||
from nonebot import on_message
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
|
||||
from utils.utils import get_message_text
|
||||
from utils.depends import PlaintText
|
||||
|
||||
from ._rule import rule
|
||||
|
||||
@@ -20,13 +20,13 @@ chat_history = on_message(rule=rule, priority=1, block=False)
|
||||
|
||||
|
||||
@chat_history.handle()
|
||||
async def _(event: MessageEvent):
|
||||
async def _(event: MessageEvent, msg: str = PlaintText()):
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
await ChatHistory.add_chat_msg(
|
||||
event.user_id, event.group_id, str(event.get_message()), get_message_text(event.json())
|
||||
event.user_id, event.group_id, str(event.get_message()), msg
|
||||
)
|
||||
else:
|
||||
await ChatHistory.add_chat_msg(event.user_id, None, str(event.get_message()), get_message_text(event.json()))
|
||||
await ChatHistory.add_chat_msg(event.user_id, None, str(event.get_message()), msg)
|
||||
|
||||
|
||||
# @test.handle()
|
||||
|
||||
@@ -19,11 +19,7 @@ from configs.config import Config
|
||||
from pathlib import Path
|
||||
import random
|
||||
import os
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
import ujson as json
|
||||
|
||||
|
||||
__zx_plugin_name__ = "群事件处理 [Hidden]"
|
||||
@@ -92,10 +88,10 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
|
||||
message=f"触发强制入群保护,退出群聊 {event.group_id} 失败..",
|
||||
)
|
||||
# 默认群功能开关
|
||||
elif event.group_id not in group_manager["group_manager"].keys():
|
||||
elif event.group_id not in group_manager.get_data().group_manager.keys():
|
||||
data = plugins2settings_manager.get_data()
|
||||
for plugin in data.keys():
|
||||
if not data[plugin]["default_status"]:
|
||||
if not data[plugin].default_status:
|
||||
group_manager.block_plugin(plugin, event.group_id)
|
||||
# 即刻刷新权限
|
||||
for user_info in await bot.get_group_member_list(group_id=event.group_id):
|
||||
|
||||
@@ -6,43 +6,28 @@ from nonebot.adapters.onebot.v11 import (
|
||||
Message
|
||||
)
|
||||
from nonebot.params import CommandArg
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.rule import to_me
|
||||
from configs.path_config import IMAGE_PATH, DATA_PATH
|
||||
from utils.message_builder import image
|
||||
from .data_source import create_help_img, get_plugin_help
|
||||
from ._data_source import create_help_img, get_plugin_help
|
||||
from ._utils import GROUP_HELP_PATH
|
||||
import os
|
||||
|
||||
|
||||
__zx_plugin_name__ = "帮助"
|
||||
|
||||
group_help_path = DATA_PATH / "group_help"
|
||||
help_image = IMAGE_PATH / "help.png"
|
||||
__plugin_configs__ = {
|
||||
"TYPE": {"value": "normal", "help": "帮助图片样式 ['normal', 'HTML']", "default_value": "normal"}
|
||||
}
|
||||
|
||||
simple_help_image = IMAGE_PATH / "simple_help.png"
|
||||
if help_image.exists():
|
||||
help_image.unlink()
|
||||
if simple_help_image.exists():
|
||||
simple_help_image.unlink()
|
||||
group_help_path.mkdir(exist_ok=True, parents=True)
|
||||
for x in os.listdir(group_help_path):
|
||||
group_help_image = group_help_path / x
|
||||
group_help_image.unlink()
|
||||
|
||||
_help = on_command("详细功能", rule=to_me(), aliases={"详细帮助"}, priority=1, block=True)
|
||||
|
||||
simple_help = on_command("功能", rule=to_me(), aliases={"help", "帮助"}, priority=1, block=True)
|
||||
|
||||
|
||||
@_help.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
if not help_image.exists():
|
||||
if help_image.exists():
|
||||
help_image.unlink()
|
||||
if simple_help_image.exists():
|
||||
simple_help_image.unlink()
|
||||
await create_help_img(None, help_image, simple_help_image)
|
||||
await _help.finish(image("help.png"))
|
||||
|
||||
|
||||
@simple_help.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
@@ -54,20 +39,18 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
msg = msg.replace('-super', '').strip()
|
||||
msg = get_plugin_help(msg, is_super)
|
||||
if msg:
|
||||
await _help.send(image(b64=msg))
|
||||
await simple_help.send(image(b64=msg))
|
||||
else:
|
||||
await _help.send("没有此功能的帮助信息...")
|
||||
await simple_help.send("没有此功能的帮助信息...")
|
||||
else:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
_image_path = group_help_path / f"{event.group_id}.png"
|
||||
_image_path = GROUP_HELP_PATH / f"{event.group_id}.png"
|
||||
if not _image_path.exists():
|
||||
await create_help_img(event.group_id, help_image, _image_path)
|
||||
await create_help_img(event.group_id)
|
||||
await simple_help.send(image(_image_path))
|
||||
else:
|
||||
if not simple_help_image.exists():
|
||||
if help_image.exists():
|
||||
help_image.unlink()
|
||||
if simple_help_image.exists():
|
||||
simple_help_image.unlink()
|
||||
await create_help_img(None, help_image, simple_help_image)
|
||||
await _help.finish(image("simple_help.png"))
|
||||
await create_help_img(None)
|
||||
await simple_help.finish(image("simple_help.png"))
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
from typing import Optional, List, Any, Union, Dict
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
plugin_name: str
|
||||
sta: int
|
||||
|
||||
|
||||
class PluginList(BaseModel):
|
||||
plugin_type: str
|
||||
icon: str
|
||||
logo: str
|
||||
items: List[Item]
|
||||
@@ -0,0 +1,71 @@
|
||||
|
||||
from ._utils import HelpImageBuild
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.manager import (
|
||||
plugins2settings_manager,
|
||||
admin_manager,
|
||||
)
|
||||
from typing import Optional
|
||||
import nonebot
|
||||
|
||||
|
||||
random_bk_path = IMAGE_PATH / "background" / "help" / "simple_help"
|
||||
|
||||
background = IMAGE_PATH / "background" / "0.png"
|
||||
|
||||
|
||||
async def create_help_img(group_id: Optional[int]):
|
||||
"""
|
||||
说明:
|
||||
生成帮助图片
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
await HelpImageBuild().build_image(group_id)
|
||||
|
||||
|
||||
def get_plugin_help(msg: str, is_super: bool = False) -> Optional[str]:
|
||||
"""
|
||||
说明:
|
||||
获取功能的帮助信息
|
||||
参数:
|
||||
:param msg: 功能cmd
|
||||
:param is_super: 是否为超级用户
|
||||
"""
|
||||
module = plugins2settings_manager.get_plugin_module(
|
||||
msg
|
||||
) or admin_manager.get_plugin_module(msg)
|
||||
if module:
|
||||
try:
|
||||
plugin = nonebot.plugin.get_plugin(module)
|
||||
metadata = plugin.metadata
|
||||
if plugin:
|
||||
if is_super:
|
||||
result = plugin.module.__getattribute__(
|
||||
"__plugin_superuser_usage__"
|
||||
)
|
||||
else:
|
||||
result = (
|
||||
metadata.usage
|
||||
if metadata
|
||||
else plugin.module.__getattribute__("__plugin_usage__")
|
||||
)
|
||||
if result:
|
||||
width = 0
|
||||
for x in result.split("\n"):
|
||||
_width = len(x) * 24
|
||||
width = width if width > _width else _width
|
||||
height = len(result.split("\n")) * 45
|
||||
A = BuildImage(width, height, font_size=24)
|
||||
bk = BuildImage(
|
||||
width,
|
||||
height,
|
||||
background=IMAGE_PATH / "background" / "1.png",
|
||||
)
|
||||
A.paste(bk, alpha=True)
|
||||
A.text((int(width * 0.048), int(height * 0.21)), result)
|
||||
return A.pic2bs4()
|
||||
except AttributeError:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,256 @@
|
||||
import os
|
||||
import random
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from configs.config import Config
|
||||
from configs.path_config import DATA_PATH, IMAGE_PATH, TEMPLATE_PATH
|
||||
from utils.decorator import Singleton
|
||||
from utils.image_utils import BuildImage, build_sort_image, group_image
|
||||
from utils.manager import group_manager, plugin_data_manager
|
||||
from utils.manager.models import PluginData, PluginType
|
||||
|
||||
from ._config import Item
|
||||
|
||||
GROUP_HELP_PATH = DATA_PATH / "group_help"
|
||||
GROUP_HELP_PATH.mkdir(exist_ok=True, parents=True)
|
||||
for x in os.listdir(GROUP_HELP_PATH):
|
||||
group_help_image = GROUP_HELP_PATH / x
|
||||
group_help_image.unlink()
|
||||
|
||||
BACKGROUND_PATH = IMAGE_PATH / "background" / "help" / "simple_help"
|
||||
|
||||
LOGO_PATH = TEMPLATE_PATH / "menu" / "res" / "logo"
|
||||
|
||||
|
||||
@Singleton
|
||||
class HelpImageBuild:
|
||||
def __init__(self):
|
||||
self._data: Dict[str, PluginData] = plugin_data_manager.get_data()
|
||||
self._sort_data: Dict[str, List[PluginData]] = {}
|
||||
self._image_list = []
|
||||
self.icon2str = {
|
||||
"normal": "fa fa-cog",
|
||||
"原神相关": "fa fa-circle-o",
|
||||
"常规插件": "fa fa-cubes",
|
||||
"联系管理员": "fa fa-envelope-o",
|
||||
"抽卡相关": "fa fa-credit-card-alt",
|
||||
"来点好康的": "fa fa-picture-o",
|
||||
"数据统计": "fa fa-bar-chart",
|
||||
"一些工具": "fa fa-shopping-cart",
|
||||
"商店": "fa fa-shopping-cart",
|
||||
"其它": "fa fa-tags",
|
||||
"群内小游戏": "fa fa-gamepad",
|
||||
}
|
||||
|
||||
def sort_type(self):
|
||||
"""
|
||||
说明:
|
||||
对插件按照菜单类型分类
|
||||
"""
|
||||
if not self._sort_data.keys():
|
||||
for key in self._data.keys():
|
||||
plugin_data = self._data[key]
|
||||
if plugin_data.plugin_type == PluginType.NORMAL:
|
||||
if not self._sort_data.get(plugin_data.menu_type[0]):
|
||||
self._sort_data[plugin_data.menu_type[0]] = []
|
||||
self._sort_data[plugin_data.menu_type[0]].append(self._data[key])
|
||||
|
||||
async def build_image(self, group_id: Optional[int]):
|
||||
if group_id:
|
||||
help_image = GROUP_HELP_PATH / f"{group_id}.png"
|
||||
else:
|
||||
help_image = IMAGE_PATH / f"simple_help.png"
|
||||
build_type = Config.get_config("help", "TYPE")
|
||||
if build_type == "HTML":
|
||||
byt = await self.build_html_image(group_id)
|
||||
with open(help_image, "wb") as f:
|
||||
f.write(byt)
|
||||
else:
|
||||
img = await self.build_pil_image(group_id)
|
||||
img.save(help_image)
|
||||
|
||||
async def build_html_image(self, group_id: Optional[int]) -> bytes:
|
||||
from nonebot_plugin_htmlrender import template_to_pic
|
||||
self.sort_type()
|
||||
classify = {}
|
||||
for menu in self._sort_data:
|
||||
for plugin in self._sort_data[menu]:
|
||||
sta = 0
|
||||
if not plugin.plugin_status.status:
|
||||
if group_id and plugin.plugin_status.block_type in ["all", "group"]:
|
||||
sta = 2
|
||||
if not group_id and plugin.plugin_status.block_type in [
|
||||
"all",
|
||||
"private",
|
||||
]:
|
||||
sta = 2
|
||||
if group_id and not group_manager.get_plugin_super_status(
|
||||
plugin.model, group_id
|
||||
):
|
||||
sta = 2
|
||||
if group_id and not group_manager.get_plugin_status(
|
||||
plugin.model, group_id
|
||||
):
|
||||
sta = 1
|
||||
if classify.get(menu):
|
||||
classify[menu].append(Item(plugin_name=plugin.name, sta=sta))
|
||||
else:
|
||||
classify[menu] = [Item(plugin_name=plugin.name, sta=sta)]
|
||||
max_len = 0
|
||||
flag_index = -1
|
||||
max_data = None
|
||||
plugin_list = []
|
||||
for index, plu in enumerate(classify.keys()):
|
||||
if plu in self.icon2str.keys():
|
||||
icon = self.icon2str[plu]
|
||||
else:
|
||||
icon = "fa fa-pencil-square-o"
|
||||
logo = LOGO_PATH / random.choice(os.listdir(LOGO_PATH))
|
||||
data = {
|
||||
"name": plu if plu != "normal" else "功能",
|
||||
"items": classify[plu],
|
||||
"icon": icon,
|
||||
"logo": str(logo.absolute()),
|
||||
}
|
||||
if len(classify[plu]) > max_len:
|
||||
max_len = len(classify[plu])
|
||||
flag_index = index
|
||||
max_data = data
|
||||
plugin_list.append(data)
|
||||
del plugin_list[flag_index]
|
||||
plugin_list.insert(0, max_data)
|
||||
pic = await template_to_pic(
|
||||
template_path=str((TEMPLATE_PATH / "menu").absolute()),
|
||||
template_name="zhenxun_menu.html",
|
||||
templates={"plugin_list": plugin_list},
|
||||
pages={
|
||||
"viewport": {"width": 1903, "height": 975},
|
||||
"base_url": f"file://{TEMPLATE_PATH}",
|
||||
},
|
||||
wait=2,
|
||||
)
|
||||
return pic
|
||||
|
||||
async def build_pil_image(self, group_id: Optional[int]) -> BuildImage:
|
||||
"""
|
||||
说明:
|
||||
构造帮助图片
|
||||
参数:
|
||||
:param group_id: 群号
|
||||
"""
|
||||
self._image_list = []
|
||||
self.sort_type()
|
||||
font_size = 24
|
||||
build_type = Config.get_config("help", "TYPE")
|
||||
_image = BuildImage(0, 0, plain_text="1", font_size=font_size)
|
||||
for idx, menu_type in enumerate(self._sort_data.keys()):
|
||||
plugin_list = self._sort_data[menu_type]
|
||||
wh_list = [_image.getsize(x.name) for x in plugin_list]
|
||||
wh_list.append(_image.getsize(menu_type))
|
||||
# sum_height = sum([x[1] for x in wh_list])
|
||||
if build_type == "VV":
|
||||
sum_height = 50 * len(plugin_list) + 10
|
||||
else:
|
||||
sum_height = (font_size + 6) * len(plugin_list) + 10
|
||||
max_width = max([x[0] for x in wh_list]) + 20
|
||||
bk = BuildImage(
|
||||
max_width + 40,
|
||||
sum_height + 50,
|
||||
font_size=30,
|
||||
color="#a7d1fc",
|
||||
font="CJGaoDeGuo.otf",
|
||||
)
|
||||
title_size = bk.getsize(menu_type)
|
||||
max_width = max_width if max_width > title_size[0] else title_size[0]
|
||||
B = BuildImage(
|
||||
max_width + 40,
|
||||
sum_height,
|
||||
font_size=font_size,
|
||||
color="white" if not idx % 2 else "black",
|
||||
)
|
||||
curr_h = 10
|
||||
for i, plugin_data in enumerate(plugin_list):
|
||||
text_color = (255, 255, 255) if idx % 2 else (0, 0, 0)
|
||||
if group_id and not group_manager.get_plugin_status(
|
||||
plugin_data.model, group_id
|
||||
):
|
||||
text_color = (252, 75, 13)
|
||||
pos = None
|
||||
# 禁用状态划线
|
||||
if (
|
||||
not plugin_data.plugin_status.status
|
||||
and plugin_data.plugin_status.block_type in ["group", "all"]
|
||||
) or (group_id and not group_manager.get_plugin_super_status(
|
||||
plugin_data.model, group_id
|
||||
)):
|
||||
w = curr_h + int(B.getsize(plugin_data.name)[1] / 2) + 2
|
||||
pos = (
|
||||
7,
|
||||
w,
|
||||
B.getsize(plugin_data.name)[0] + 35,
|
||||
w,
|
||||
)
|
||||
if build_type == "VV":
|
||||
name_image = await self.build_name_image(
|
||||
max_width,
|
||||
plugin_data.name,
|
||||
"black" if not idx % 2 else "white",
|
||||
text_color,
|
||||
pos,
|
||||
)
|
||||
await B.apaste(
|
||||
name_image, (0, curr_h), True, center_type="by_width"
|
||||
)
|
||||
curr_h += name_image.h + 5
|
||||
else:
|
||||
await B.atext(
|
||||
(10, curr_h), f"{i + 1}.{plugin_data.name}", text_color
|
||||
)
|
||||
if pos:
|
||||
await B.aline(pos, (236, 66, 7), 3)
|
||||
curr_h += font_size + 5
|
||||
if menu_type == "normal":
|
||||
menu_type = "功能"
|
||||
await bk.atext((0, 14), menu_type, center_type="by_width")
|
||||
await bk.apaste(B, (0, 50))
|
||||
await bk.atransparent(2)
|
||||
# await bk.acircle_corner(point_list=['lt', 'rt'])
|
||||
self._image_list.append(bk)
|
||||
image_group, h = group_image(self._image_list)
|
||||
B = await build_sort_image(
|
||||
image_group,
|
||||
h,
|
||||
background_path=BACKGROUND_PATH,
|
||||
background_handle=lambda image: image.filter("GaussianBlur", 5),
|
||||
)
|
||||
w = 10
|
||||
h = 10
|
||||
for msg in [
|
||||
"目前支持的功能列表:",
|
||||
"可以通过 ‘帮助[功能名称]’ 来获取对应功能的使用方法",
|
||||
"或者使用 ‘详细帮助’ 来获取所有功能方法",
|
||||
]:
|
||||
text = BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=msg,
|
||||
font_size=24,
|
||||
font="HYWenHei-85W.ttf",
|
||||
)
|
||||
B.paste(text, (w, h), True)
|
||||
h += 50
|
||||
if msg == "目前支持的功能列表:":
|
||||
w += 50
|
||||
await B.apaste(
|
||||
BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text="注: 红字代表功能被群管理员禁用,红线代表功能正在维护",
|
||||
font_size=24,
|
||||
font="HYWenHei-85W.ttf",
|
||||
font_color=(231, 74, 57),
|
||||
),
|
||||
(300, 10),
|
||||
True,
|
||||
)
|
||||
return B
|
||||
@@ -1,372 +0,0 @@
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.manager import (
|
||||
plugins2settings_manager,
|
||||
admin_manager,
|
||||
plugins_manager,
|
||||
group_manager,
|
||||
)
|
||||
from typing import Optional
|
||||
from services.log import logger
|
||||
from pathlib import Path
|
||||
from utils.utils import get_matchers
|
||||
import random
|
||||
import asyncio
|
||||
import nonebot
|
||||
import os
|
||||
|
||||
|
||||
random_bk_path = IMAGE_PATH / "background" / "help" / "simple_help"
|
||||
|
||||
background = IMAGE_PATH / "background" / "0.png"
|
||||
|
||||
|
||||
async def create_help_img(
|
||||
group_id: Optional[int], help_image: Path, simple_help_image: Path
|
||||
):
|
||||
"""
|
||||
生成帮助图片
|
||||
:param group_id: 群号
|
||||
:param help_image: 图片路径
|
||||
:param simple_help_image: 简易帮助图片路径
|
||||
"""
|
||||
return await asyncio.get_event_loop().run_in_executor(
|
||||
None, _create_help_img, group_id, help_image, simple_help_image
|
||||
)
|
||||
|
||||
|
||||
def _create_help_img(
|
||||
group_id: Optional[int], help_image: Path, simple_help_image: Path
|
||||
):
|
||||
"""
|
||||
生成帮助图片
|
||||
:param group_id: 群号
|
||||
:param help_image: 图片路径
|
||||
:param simple_help_image: 简易帮助图片路径
|
||||
"""
|
||||
_matchers = get_matchers(True)
|
||||
width = 0
|
||||
matchers_data = {}
|
||||
_des_tmp = {}
|
||||
_plugin_name_tmp = []
|
||||
_tmp = []
|
||||
tmp_img = BuildImage(0, 0, plain_text="1", font_size=24)
|
||||
font_height = tmp_img.h
|
||||
# 插件分类
|
||||
for matcher in _matchers:
|
||||
plugin_name = None
|
||||
_plugin = matcher.plugin
|
||||
metadata = _plugin.metadata
|
||||
if not _plugin:
|
||||
logger.warning(f"获取 功能:{matcher.plugin_name} 失败...")
|
||||
continue
|
||||
_module = _plugin.module
|
||||
try:
|
||||
plugin_name = metadata.name if metadata else _module.__getattribute__("__zx_plugin_name__")
|
||||
try:
|
||||
plugin_des = metadata.description if metadata else _module.__getattribute__("__plugin_des__")
|
||||
except AttributeError:
|
||||
plugin_des = "_"
|
||||
if (
|
||||
"[hidden]" in plugin_name.lower()
|
||||
or "[admin]" in plugin_name.lower()
|
||||
or "[superuser]" in plugin_name.lower()
|
||||
or plugin_name in _plugin_name_tmp
|
||||
or plugin_name == "帮助"
|
||||
):
|
||||
continue
|
||||
plugin_type = ("normal",)
|
||||
text_type = 0
|
||||
if plugins2settings_manager.get(
|
||||
matcher.plugin_name
|
||||
) and plugins2settings_manager[matcher.plugin_name].get("plugin_type"):
|
||||
plugin_type = tuple(
|
||||
plugins2settings_manager.get_plugin_data(matcher.plugin_name)[
|
||||
"plugin_type"
|
||||
]
|
||||
)
|
||||
else:
|
||||
try:
|
||||
plugin_type = _module.__getattribute__("__plugin_type__")
|
||||
except AttributeError:
|
||||
pass
|
||||
if len(plugin_type) > 1:
|
||||
try:
|
||||
text_type = int(plugin_type[1])
|
||||
except ValueError as e:
|
||||
logger.warning(f"生成列向帮助排列失败 {plugin_name}: {type(e)}: {e}")
|
||||
plugin_type = plugin_type[0]
|
||||
else:
|
||||
plugin_type = plugin_type[0]
|
||||
try:
|
||||
plugin_cmd = _module.__getattribute__("__plugin_cmd__")
|
||||
plugin_cmd = [x for x in plugin_cmd if "[_superuser]" not in x]
|
||||
except AttributeError:
|
||||
plugin_cmd = []
|
||||
if plugin_type not in matchers_data.keys():
|
||||
matchers_data[plugin_type] = {}
|
||||
if plugin_des in _des_tmp.keys():
|
||||
try:
|
||||
matchers_data[plugin_type][_des_tmp[plugin_des]]["cmd"] = (
|
||||
matchers_data[plugin_type][_des_tmp[plugin_des]]["cmd"]
|
||||
+ plugin_cmd
|
||||
)
|
||||
except KeyError as e:
|
||||
logger.warning(f"{type(e)}: {e}")
|
||||
else:
|
||||
matchers_data[plugin_type][plugin_name] = {
|
||||
"modules": matcher.plugin_name,
|
||||
"des": plugin_des,
|
||||
"cmd": plugin_cmd,
|
||||
"text_type": text_type,
|
||||
}
|
||||
try:
|
||||
if text_type == 0:
|
||||
x = tmp_img.getsize(
|
||||
f'{plugin_name}: {matchers_data[plugin_type][plugin_name]["des"]} ->'
|
||||
+ " / ".join(matchers_data[plugin_type][plugin_name]["cmd"])
|
||||
)[0]
|
||||
width = width if width > x else x
|
||||
except KeyError:
|
||||
pass
|
||||
if plugin_des not in _des_tmp:
|
||||
_des_tmp[plugin_des] = plugin_name
|
||||
except AttributeError as e:
|
||||
if plugin_name not in _plugin_name_tmp:
|
||||
logger.warning(f"获取功能 {matcher.plugin_name}: {plugin_name} 设置失败...e:{e}")
|
||||
if plugin_name not in _plugin_name_tmp:
|
||||
_plugin_name_tmp.append(plugin_name)
|
||||
help_img_list = []
|
||||
simple_help_img_list = []
|
||||
types = list(matchers_data.keys())
|
||||
types.sort()
|
||||
ix = 0
|
||||
# 详细帮助
|
||||
for type_ in types:
|
||||
keys = list(matchers_data[type_].keys())
|
||||
keys.sort()
|
||||
help_str = f"{type_ if type_ != 'normal' else '功能'}:\n\n"
|
||||
simple_help_str = f"{type_ if type_ != 'normal' else '功能'}:\n\n"
|
||||
for i, k in enumerate(keys):
|
||||
# 禁用flag
|
||||
flag = True
|
||||
if plugins_manager.get_plugin_status(
|
||||
matchers_data[type_][k]["modules"], "all"
|
||||
):
|
||||
flag = False
|
||||
if group_id:
|
||||
flag = flag and plugins_manager.get_plugin_status(
|
||||
matchers_data[type_][k]["modules"], "group"
|
||||
)
|
||||
simple_help_str += (
|
||||
f"{i+1}.{k}<|_|~|>"
|
||||
f"{group_manager.get_plugin_status(matchers_data[type_][k]['modules'], group_id) if group_id else '_'}|"
|
||||
f"{flag}\n"
|
||||
)
|
||||
if matchers_data[type_][k]["text_type"] == 1:
|
||||
_x = tmp_img.getsize(
|
||||
f"{i+1}".rjust(5)
|
||||
+ f'.{k}: {matchers_data[type_][k]["des"]} {"->" if matchers_data[type_][k]["cmd"] else ""} '
|
||||
)[0]
|
||||
_str = (
|
||||
f"{i+1}".rjust(5)
|
||||
+ f'.{k}: {matchers_data[type_][k]["des"]} {"->" if matchers_data[type_][k]["cmd"] else ""} '
|
||||
)
|
||||
_str += matchers_data[type_][k]["cmd"][0] + "\n"
|
||||
for c in matchers_data[type_][k]["cmd"][1:]:
|
||||
_str += "".rjust(int(_x * 0.125) + 1) + f"{c}\n"
|
||||
help_str += _str
|
||||
else:
|
||||
help_str += (
|
||||
f"{i+1}".rjust(5)
|
||||
+ f'.{k}: {matchers_data[type_][k]["des"]} {"->" if matchers_data[type_][k]["cmd"] else ""} '
|
||||
+ " / ".join(matchers_data[type_][k]["cmd"])
|
||||
+ "\n"
|
||||
)
|
||||
height = len(help_str.split("\n")) * (font_height + 5)
|
||||
simple_height = len(simple_help_str.split("\n")) * (font_height + 5)
|
||||
A = BuildImage(
|
||||
width + 150, height, font_size=24, color="white" if not ix % 2 else "black"
|
||||
)
|
||||
A.text((10, 10), help_str, (255, 255, 255) if ix % 2 else (0, 0, 0))
|
||||
# 生成各个分类的插件简易帮助图片
|
||||
simple_width = 0
|
||||
for x in [
|
||||
tmp_img.getsize(x.split("<|_|~|>")[0])[0]
|
||||
for x in simple_help_str.split("\n")
|
||||
]:
|
||||
simple_width = simple_width if simple_width > x else x
|
||||
bk = BuildImage(simple_width + 20, simple_height, font_size=24, color="#6495ED")
|
||||
B = BuildImage(
|
||||
simple_width + 20,
|
||||
simple_height,
|
||||
font_size=24,
|
||||
color="white" if not ix % 2 else "black",
|
||||
)
|
||||
# 切分,判断插件开关状态
|
||||
_s_height = 10
|
||||
for _s in simple_help_str.split("\n"):
|
||||
text_color = (255, 255, 255) if ix % 2 else (0, 0, 0)
|
||||
_line_flag = False
|
||||
if "<|_|~|>" in _s:
|
||||
_x = _s.split("<|_|~|>")
|
||||
_flag_sp = _x[-1].split("|")
|
||||
if group_id:
|
||||
if _flag_sp[0].lower() != "true":
|
||||
text_color = (252, 75, 13)
|
||||
if _flag_sp[1].lower() == "true":
|
||||
_line_flag = True
|
||||
_s = _x[0]
|
||||
B.text((10, _s_height), _s, text_color)
|
||||
if _line_flag:
|
||||
B.line(
|
||||
(
|
||||
7,
|
||||
_s_height + int(B.getsize(_s)[1] / 2) + 2,
|
||||
B.getsize(_s)[0] + 11,
|
||||
_s_height + int(B.getsize(_s)[1] / 2) + 2,
|
||||
),
|
||||
(236, 66, 7),
|
||||
3,
|
||||
)
|
||||
_s_height += B.getsize("1")[1] + 5
|
||||
# B.text((10, 10), simple_help_str, (255, 255, 255) if ix % 2 else (0, 0, 0))
|
||||
bk.paste(B, center_type="center")
|
||||
bk.transparent(2)
|
||||
ix += 1
|
||||
help_img_list.append(A)
|
||||
simple_help_img_list.append(bk)
|
||||
height = 0
|
||||
for img in help_img_list:
|
||||
height += img.h
|
||||
if not group_id:
|
||||
A = BuildImage(width + 150, height + 50, font_size=24)
|
||||
A.text(
|
||||
(10, 10), '* 注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数 *\n\n" "功能名: 功能简介 -> 指令\n\n'
|
||||
)
|
||||
current_height = 50
|
||||
for img in help_img_list:
|
||||
A.paste(img, (0, current_height))
|
||||
current_height += img.h
|
||||
A.save(help_image)
|
||||
# 详细帮助生成完毕
|
||||
# 简易帮助图片合成
|
||||
height = 0
|
||||
width = 0
|
||||
for img in simple_help_img_list:
|
||||
if img.h > height:
|
||||
height = img.h
|
||||
width += img.w + 10
|
||||
B = BuildImage(width + 100, height + 250, font_size=24)
|
||||
width, _ = get_max_width_or_paste(simple_help_img_list, B)
|
||||
bk = None
|
||||
random_bk = os.listdir(random_bk_path)
|
||||
if random_bk:
|
||||
bk = random.choice(random_bk)
|
||||
x = max(width + 50, height + 250)
|
||||
B = BuildImage(
|
||||
x,
|
||||
x,
|
||||
font_size=24,
|
||||
color="#FFEFD5",
|
||||
background=random_bk_path / bk,
|
||||
)
|
||||
B.filter("GaussianBlur", 10)
|
||||
_, B = get_max_width_or_paste(simple_help_img_list, B, True)
|
||||
w = 10
|
||||
h = 10
|
||||
for msg in ["目前支持的功能列表:", "可以通过 ‘帮助[功能名称]’ 来获取对应功能的使用方法", "或者使用 ‘详细帮助’ 来获取所有功能方法"]:
|
||||
text = BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text=msg,
|
||||
font_size=24,
|
||||
font="HYWenHei-85W.ttf",
|
||||
)
|
||||
B.paste(text, (w, h), True)
|
||||
h += 50
|
||||
if msg == "目前支持的功能列表:":
|
||||
w += 50
|
||||
B.paste(
|
||||
BuildImage(
|
||||
0,
|
||||
0,
|
||||
plain_text="注: 红字代表功能被群管理员禁用,红线代表功能正在维护",
|
||||
font_size=24,
|
||||
font="HYWenHei-85W.ttf",
|
||||
font_color=(231, 74, 57)
|
||||
),
|
||||
(300, 10),
|
||||
True,
|
||||
)
|
||||
B.save(simple_help_image)
|
||||
|
||||
|
||||
def get_max_width_or_paste(
|
||||
simple_help_img_list: list, B: BuildImage = None, is_paste: bool = False
|
||||
) -> "int, BuildImage":
|
||||
"""
|
||||
获取最大宽度,或直接贴图
|
||||
:param simple_help_img_list: 简单帮助图片列表
|
||||
:param B: 背景图
|
||||
:param is_paste: 是否直接贴图
|
||||
"""
|
||||
current_width = 50
|
||||
current_height = 180
|
||||
max_width = simple_help_img_list[0].w
|
||||
for i in range(len(simple_help_img_list)):
|
||||
try:
|
||||
if is_paste and B:
|
||||
B.paste(simple_help_img_list[i], (current_width, current_height), True)
|
||||
current_height += simple_help_img_list[i].h + 40
|
||||
if current_height + simple_help_img_list[i + 1].h > B.h - 10:
|
||||
current_height = 180
|
||||
current_width += max_width + 30
|
||||
max_width = 0
|
||||
elif simple_help_img_list[i].w > max_width:
|
||||
max_width = simple_help_img_list[i].w
|
||||
except IndexError:
|
||||
pass
|
||||
if current_width > simple_help_img_list[0].w + 50:
|
||||
current_width += simple_help_img_list[-1].w
|
||||
return current_width, B
|
||||
|
||||
|
||||
def get_plugin_help(msg: str, is_super: bool = False) -> Optional[str]:
|
||||
"""
|
||||
获取功能的帮助信息
|
||||
:param msg: 功能cmd
|
||||
:param is_super: 是否为超级用户
|
||||
"""
|
||||
module = plugins2settings_manager.get_plugin_module(msg)
|
||||
if not module:
|
||||
module = admin_manager.get_plugin_module(msg)
|
||||
if module:
|
||||
try:
|
||||
plugin = nonebot.plugin.get_plugin(module)
|
||||
metadata = plugin.metadata
|
||||
if plugin:
|
||||
if is_super:
|
||||
result = plugin.module.__getattribute__(
|
||||
"__plugin_superuser_usage__"
|
||||
)
|
||||
else:
|
||||
result = metadata.usage if metadata else plugin.module.__getattribute__("__plugin_usage__")
|
||||
if result:
|
||||
width = 0
|
||||
for x in result.split("\n"):
|
||||
_width = len(x) * 24
|
||||
width = width if width > _width else _width
|
||||
height = len(result.split("\n")) * 45
|
||||
A = BuildImage(width, height, font_size=24)
|
||||
bk = BuildImage(
|
||||
width,
|
||||
height,
|
||||
background=IMAGE_PATH / "background" / "1.png",
|
||||
)
|
||||
A.paste(bk, alpha=True)
|
||||
A.text((int(width * 0.048), int(height * 0.21)), result)
|
||||
return A.pic2bs4()
|
||||
except AttributeError:
|
||||
pass
|
||||
return None
|
||||
@@ -1,5 +1,38 @@
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent
|
||||
from utils.manager import plugins2block_manager, StaticData
|
||||
from typing import Optional
|
||||
|
||||
import nonebot
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
GroupMessageEvent,
|
||||
PrivateMessageEvent,
|
||||
Bot,
|
||||
Event,
|
||||
MessageEvent,
|
||||
Message,
|
||||
PokeNotifyEvent,
|
||||
)
|
||||
from nonebot.exception import ActionFailed, IgnoredException
|
||||
from nonebot.internal.matcher import Matcher
|
||||
|
||||
from models.bag_user import BagUser
|
||||
from models.ban_user import BanUser
|
||||
from models.friend_user import FriendUser
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from models.level_user import LevelUser
|
||||
from models.user_shop_gold_log import UserShopGoldLog
|
||||
from utils.decorator import Singleton
|
||||
from utils.manager import (
|
||||
plugins2block_manager,
|
||||
StaticData,
|
||||
plugins2settings_manager,
|
||||
group_manager,
|
||||
admin_manager,
|
||||
plugins_manager,
|
||||
plugins2cd_manager,
|
||||
plugins2count_manager,
|
||||
)
|
||||
from utils.message_builder import at
|
||||
from utils.utils import FreqLimiter
|
||||
from configs.config import Config
|
||||
import time
|
||||
|
||||
ignore_rst_module = ["ai", "poke", "dialogue"]
|
||||
@@ -8,7 +41,6 @@ other_limit_plugins = ["poke"]
|
||||
|
||||
|
||||
class StatusMessageManager(StaticData):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(None)
|
||||
|
||||
@@ -39,8 +71,8 @@ def set_block_limit_false(event, module):
|
||||
"""
|
||||
if plugins2block_manager.check_plugin_block_status(module):
|
||||
plugin_block_data = plugins2block_manager.get_plugin_block_data(module)
|
||||
check_type = plugin_block_data["check_type"]
|
||||
limit_type = plugin_block_data["limit_type"]
|
||||
check_type = plugin_block_data.check_type
|
||||
limit_type = plugin_block_data.limit_type
|
||||
if not (
|
||||
(isinstance(event, GroupMessageEvent) and check_type == "private")
|
||||
or (isinstance(event, PrivateMessageEvent) and check_type == "group")
|
||||
@@ -50,3 +82,430 @@ def set_block_limit_false(event, module):
|
||||
block_type_ = event.group_id
|
||||
plugins2block_manager.set_false(block_type_, module)
|
||||
|
||||
|
||||
async def send_msg(msg: str, bot: Bot, event: MessageEvent):
|
||||
"""
|
||||
说明:
|
||||
发送信息
|
||||
参数:
|
||||
:param msg: pass
|
||||
:param bot: pass
|
||||
:param event: pass
|
||||
"""
|
||||
if "[uname]" in msg:
|
||||
uname = event.sender.card or event.sender.nickname
|
||||
msg = msg.replace("[uname]", uname)
|
||||
if "[nickname]" in msg:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
nickname = await GroupInfoUser.get_group_member_nickname(
|
||||
event.user_id, event.group_id
|
||||
)
|
||||
else:
|
||||
nickname = await FriendUser.get_friend_nickname(event.user_id)
|
||||
msg = msg.replace("[nickname]", nickname)
|
||||
if "[at]" in msg and isinstance(event, GroupMessageEvent):
|
||||
msg = msg.replace("[at]", str(at(event.user_id)))
|
||||
try:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
status_message_manager.add(event.group_id)
|
||||
await bot.send_group_msg(group_id=event.group_id, message=Message(msg))
|
||||
else:
|
||||
status_message_manager.add(event.user_id)
|
||||
await bot.send_private_msg(user_id=event.user_id, message=Message(msg))
|
||||
except ActionFailed:
|
||||
pass
|
||||
|
||||
|
||||
class IsSuperuserException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@Singleton
|
||||
class AuthChecker:
|
||||
"""
|
||||
权限检查
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._flmt = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
self._flmt_g = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
self._flmt_s = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
self._flmt_c = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
|
||||
async def auth(self, matcher: Matcher, bot: Bot, event: Event):
|
||||
"""
|
||||
说明:
|
||||
权限检查
|
||||
参数:
|
||||
:param matcher: matcher
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
try:
|
||||
plugin_name = matcher.plugin_name
|
||||
cost_gold = await self.auth_cost(plugin_name, bot, event)
|
||||
if str(event.user_id) not in bot.config.superusers:
|
||||
await self.auth_basic(plugin_name, bot, event)
|
||||
self.auth_group(plugin_name, bot, event)
|
||||
await self.auth_admin(plugin_name, matcher, bot, event)
|
||||
await self.auth_plugin(plugin_name, matcher, bot, event)
|
||||
await self.auth_limit(plugin_name, bot, event)
|
||||
if cost_gold:
|
||||
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
|
||||
except IsSuperuserException:
|
||||
return
|
||||
|
||||
async def auth_limit(self, plugin_name: str, bot: Bot, event: Event):
|
||||
"""
|
||||
说明:
|
||||
插件限制
|
||||
参数:
|
||||
:param plugin_name: 模块名
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
if plugins2cd_manager.check_plugin_cd_status(plugin_name):
|
||||
plugin_cd_data = plugins2cd_manager.get_plugin_cd_data(plugin_name)
|
||||
check_type = plugin_cd_data.check_type
|
||||
limit_type = plugin_cd_data.limit_type
|
||||
msg = plugin_cd_data.rst
|
||||
if (
|
||||
(isinstance(event, PrivateMessageEvent) and check_type == "private")
|
||||
or (isinstance(event, GroupMessageEvent) and check_type == "group")
|
||||
or plugins2cd_manager.get_plugin_data(plugin_name).check_type == "all"
|
||||
):
|
||||
cd_type_ = event.user_id
|
||||
if limit_type == "group" and isinstance(event, GroupMessageEvent):
|
||||
cd_type_ = event.group_id
|
||||
if not plugins2cd_manager.check(plugin_name, cd_type_):
|
||||
if msg:
|
||||
await send_msg(msg, bot, event)
|
||||
raise IgnoredException(f"{plugin_name} 正在cd中...")
|
||||
else:
|
||||
plugins2cd_manager.start_cd(plugin_name, cd_type_)
|
||||
# Block
|
||||
if plugins2block_manager.check_plugin_block_status(plugin_name):
|
||||
plugin_block_data = plugins2block_manager.get_plugin_block_data(plugin_name)
|
||||
check_type = plugin_block_data.check_type
|
||||
limit_type = plugin_block_data.limit_type
|
||||
msg = plugin_block_data.rst
|
||||
if (
|
||||
(isinstance(event, PrivateMessageEvent) and check_type == "private")
|
||||
or (isinstance(event, GroupMessageEvent) and check_type == "group")
|
||||
or check_type == "all"
|
||||
):
|
||||
block_type_ = event.user_id
|
||||
if limit_type == "group" and isinstance(event, GroupMessageEvent):
|
||||
block_type_ = event.group_id
|
||||
if plugins2block_manager.check(block_type_, plugin_name):
|
||||
if msg:
|
||||
await send_msg(msg, bot, event)
|
||||
raise IgnoredException(f"{event.user_id}正在调用{plugin_name}....")
|
||||
else:
|
||||
plugins2block_manager.set_true(block_type_, plugin_name)
|
||||
# Count
|
||||
if (
|
||||
plugins2count_manager.check_plugin_count_status(plugin_name)
|
||||
and event.user_id not in bot.config.superusers
|
||||
):
|
||||
plugin_count_data = plugins2count_manager.get_plugin_count_data(plugin_name)
|
||||
limit_type = plugin_count_data.limit_type
|
||||
msg = plugin_count_data.rst
|
||||
count_type_ = event.user_id
|
||||
if limit_type == "group" and isinstance(event, GroupMessageEvent):
|
||||
count_type_ = event.group_id
|
||||
if not plugins2count_manager.check(plugin_name, count_type_):
|
||||
if msg:
|
||||
await send_msg(msg, bot, event)
|
||||
raise IgnoredException(f"{plugin_name} count次数限制...")
|
||||
else:
|
||||
plugins2count_manager.increase(plugin_name, count_type_)
|
||||
|
||||
async def auth_plugin(self, plugin_name: str, matcher: Matcher, bot: Bot, event: Event):
|
||||
"""
|
||||
说明:
|
||||
插件状态
|
||||
参数:
|
||||
:param plugin_name: 模块名
|
||||
:param matcher: matcher
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
if plugin_name in plugins2settings_manager.keys() and matcher.priority not in [
|
||||
1,
|
||||
999,
|
||||
]:
|
||||
# 戳一戳单独判断
|
||||
if (
|
||||
isinstance(event, GroupMessageEvent)
|
||||
or isinstance(event, PokeNotifyEvent)
|
||||
or matcher.plugin_name in other_limit_plugins
|
||||
):
|
||||
if status_message_manager.get(event.group_id) is None:
|
||||
status_message_manager.delete(event.group_id)
|
||||
if plugins2settings_manager[
|
||||
plugin_name
|
||||
].level > group_manager.get_group_level(event.group_id):
|
||||
try:
|
||||
if (
|
||||
self._flmt_g.check(event.user_id)
|
||||
and plugin_name not in ignore_rst_module
|
||||
):
|
||||
self._flmt_g.start_cd(event.user_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="群权限不足..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, plugin_name)
|
||||
raise IgnoredException("群权限不足")
|
||||
# 插件状态
|
||||
if not group_manager.get_plugin_status(plugin_name, event.group_id):
|
||||
try:
|
||||
if plugin_name not in ignore_rst_module and self._flmt_s.check(
|
||||
event.group_id
|
||||
):
|
||||
self._flmt_s.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="该群未开启此功能.."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, plugin_name)
|
||||
raise IgnoredException("未开启此功能...")
|
||||
# 管理员禁用
|
||||
if not group_manager.get_plugin_status(
|
||||
f"{plugin_name}:super", event.group_id
|
||||
):
|
||||
try:
|
||||
if (
|
||||
self._flmt_s.check(event.group_id)
|
||||
and plugin_name not in ignore_rst_module
|
||||
):
|
||||
self._flmt_s.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="管理员禁用了此群该功能..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, plugin_name)
|
||||
raise IgnoredException("管理员禁用了此群该功能...")
|
||||
# 群聊禁用
|
||||
if not plugins_manager.get_plugin_status(
|
||||
plugin_name, block_type="group"
|
||||
):
|
||||
try:
|
||||
if (
|
||||
self._flmt_c.check(event.group_id)
|
||||
and plugin_name not in ignore_rst_module
|
||||
):
|
||||
self._flmt_c.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="该功能在群聊中已被禁用..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, plugin_name)
|
||||
raise IgnoredException("该插件在群聊中已被禁用...")
|
||||
else:
|
||||
# 私聊禁用
|
||||
if not plugins_manager.get_plugin_status(
|
||||
plugin_name, block_type="private"
|
||||
):
|
||||
try:
|
||||
if self._flmt_c.check(event.user_id):
|
||||
self._flmt_c.start_cd(event.user_id)
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id, message="该功能在私聊中已被禁用..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.user_id)
|
||||
set_block_limit_false(event, plugin_name)
|
||||
raise IgnoredException("该插件在私聊中已被禁用...")
|
||||
# 维护
|
||||
if not plugins_manager.get_plugin_status(plugin_name, block_type="all"):
|
||||
if isinstance(
|
||||
event, GroupMessageEvent
|
||||
) and group_manager.check_group_is_white(event.group_id):
|
||||
raise IsSuperuserException()
|
||||
try:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
if (
|
||||
self._flmt_c.check(event.group_id)
|
||||
and plugin_name not in ignore_rst_module
|
||||
):
|
||||
self._flmt_c.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="此功能正在维护..."
|
||||
)
|
||||
else:
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id, message="此功能正在维护..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
id_ = (
|
||||
event.group_id
|
||||
if isinstance(event, GroupMessageEvent)
|
||||
else event.user_id
|
||||
)
|
||||
status_message_manager.add(id_)
|
||||
set_block_limit_false(event, plugin_name)
|
||||
raise IgnoredException("此功能正在维护...")
|
||||
|
||||
async def auth_admin(self, plugin_name: str, matcher: Matcher, bot: Bot, event: Event):
|
||||
"""
|
||||
说明:
|
||||
管理员命令 个人权限
|
||||
参数:
|
||||
:param plugin_name: 模块名
|
||||
:param matcher: matcher
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
if plugin_name in admin_manager.keys() and matcher.priority not in [1, 999]:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
# 个人权限
|
||||
if (
|
||||
not await LevelUser.check_level(
|
||||
event.user_id,
|
||||
event.group_id,
|
||||
admin_manager.get_plugin_level(plugin_name),
|
||||
)
|
||||
and admin_manager.get_plugin_level(plugin_name) > 0
|
||||
):
|
||||
try:
|
||||
if self._flmt.check(event.user_id):
|
||||
self._flmt.start_cd(event.user_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id,
|
||||
message=f"{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:"
|
||||
f"{admin_manager.get_plugin_level(plugin_name)}",
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
set_block_limit_false(event, plugin_name)
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
raise IgnoredException("权限不足")
|
||||
else:
|
||||
if not await LevelUser.check_level(
|
||||
event.user_id, 0, admin_manager.get_plugin_level(plugin_name)
|
||||
):
|
||||
try:
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id,
|
||||
message=f"你的权限不足喔,该功能需要的权限等级:{admin_manager.get_plugin_level(plugin_name)}",
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
set_block_limit_false(event, plugin_name)
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.user_id)
|
||||
raise IgnoredException("权限不足")
|
||||
|
||||
def auth_group(self, plugin_name: str, bot: Bot, event: Event):
|
||||
"""
|
||||
说明:
|
||||
群黑名单检测 群总开关检测
|
||||
参数:
|
||||
:param plugin_name: 模块名
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
if isinstance(event, GroupMessageEvent) or plugin_name in other_limit_plugins:
|
||||
try:
|
||||
if (
|
||||
group_manager.get_group_level(event.group_id) < 0
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
):
|
||||
raise IgnoredException("群黑名单")
|
||||
if not group_manager.check_group_bot_status(event.group_id):
|
||||
try:
|
||||
if str(event.get_message()) != "醒来":
|
||||
raise IgnoredException("功能总开关关闭状态")
|
||||
except ValueError:
|
||||
raise IgnoredException("功能总开关关闭状态")
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
async def auth_basic(self, plugin_name: str, bot: Bot, event: Event):
|
||||
"""
|
||||
说明:
|
||||
检测是否满足超级用户权限,是否被ban等
|
||||
参数:
|
||||
:param plugin_name: 模块名
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
try:
|
||||
if (
|
||||
(
|
||||
not isinstance(event, MessageEvent)
|
||||
and plugin_name not in other_limit_plugins
|
||||
)
|
||||
or await BanUser.is_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
) or (
|
||||
str(event.user_id) in bot.config.superusers
|
||||
and plugins2settings_manager.get_plugin_data(plugin_name)
|
||||
and not plugins2settings_manager.get_plugin_data(
|
||||
plugin_name
|
||||
).limit_superuser
|
||||
):
|
||||
raise IsSuperuserException()
|
||||
_plugin = nonebot.plugin.get_plugin(plugin_name)
|
||||
_module = _plugin.module
|
||||
_plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
if (
|
||||
"[superuser]" in _plugin_name.lower()
|
||||
and str(event.user_id) in bot.config.superusers
|
||||
):
|
||||
raise IsSuperuserException()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
async def auth_cost(self, plugin_name: str, bot: Bot, event: Event) -> int:
|
||||
"""
|
||||
说明:
|
||||
检测是否满足金币条件
|
||||
参数:
|
||||
:param plugin_name: 模块名
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
"""
|
||||
cost_gold = 0
|
||||
if isinstance(event, GroupMessageEvent) and (
|
||||
psm := plugins2settings_manager.get_plugin_data(plugin_name)
|
||||
):
|
||||
if psm.cost_gold > 0:
|
||||
if (
|
||||
await BagUser.get_gold(event.user_id, event.group_id)
|
||||
< psm.cost_gold
|
||||
):
|
||||
await send_msg(f"金币不足..该功能需要{psm.cost_gold}金币..", bot, event)
|
||||
raise IgnoredException(f"{plugin_name} 金币限制...")
|
||||
# 当插件不阻塞超级用户时,超级用户提前扣除金币
|
||||
if (
|
||||
str(event.user_id) in bot.config.superusers
|
||||
and not psm.limit_superuser
|
||||
):
|
||||
await BagUser.spend_gold(
|
||||
event.user_id, event.group_id, psm.cost_gold
|
||||
)
|
||||
await UserShopGoldLog.add_shop_log(
|
||||
event.user_id, event.group_id, 2, plugin_name, psm.cost_gold, 1
|
||||
)
|
||||
cost_gold = psm.cost_gold
|
||||
return cost_gold
|
||||
|
||||
@@ -1,393 +1,36 @@
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.message import run_preprocessor, run_postprocessor, IgnoredException
|
||||
from models.friend_user import FriendUser
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from models.bag_user import BagUser
|
||||
from utils.manager import (
|
||||
plugins2settings_manager,
|
||||
admin_manager,
|
||||
group_manager,
|
||||
plugins_manager,
|
||||
plugins2cd_manager,
|
||||
plugins2block_manager,
|
||||
plugins2count_manager,
|
||||
)
|
||||
from ._utils import (
|
||||
set_block_limit_false,
|
||||
status_message_manager,
|
||||
ignore_rst_module,
|
||||
other_limit_plugins,
|
||||
)
|
||||
from nonebot.typing import T_State
|
||||
from typing import Optional
|
||||
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
Bot,
|
||||
ActionFailed,
|
||||
MessageEvent,
|
||||
GroupMessageEvent,
|
||||
PokeNotifyEvent,
|
||||
PrivateMessageEvent,
|
||||
Message,
|
||||
Event,
|
||||
)
|
||||
from configs.config import Config
|
||||
from models.ban_user import BanUser
|
||||
from utils.utils import FreqLimiter
|
||||
from utils.message_builder import at
|
||||
from models.level_user import LevelUser
|
||||
import nonebot
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.message import run_preprocessor, run_postprocessor
|
||||
from nonebot.typing import T_State
|
||||
|
||||
_flmt = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
_flmt_g = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
_flmt_s = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
_flmt_c = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
from ._utils import (
|
||||
set_block_limit_false,
|
||||
AuthChecker,
|
||||
)
|
||||
|
||||
|
||||
# 权限检测
|
||||
# # 权限检测
|
||||
@run_preprocessor
|
||||
async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
|
||||
module = matcher.plugin_name
|
||||
plugins2info_dict = plugins2settings_manager.get_data()
|
||||
# 功能的金币检测 #######################################
|
||||
# 功能的金币检测 #######################################
|
||||
# 功能的金币检测 #######################################
|
||||
cost_gold = 0
|
||||
if isinstance(
|
||||
event, GroupMessageEvent
|
||||
) and plugins2settings_manager.get_plugin_data(module).get("cost_gold"):
|
||||
cost_gold = plugins2settings_manager.get_plugin_data(module).get("cost_gold")
|
||||
if await BagUser.get_gold(event.user_id, event.group_id) < cost_gold:
|
||||
await send_msg(f"金币不足..该功能需要{cost_gold}金币..", bot, event)
|
||||
raise IgnoredException(f"{module} 金币限制...")
|
||||
# 当插件不阻塞超级用户时,超级用户提前扣除金币
|
||||
if (
|
||||
str(event.user_id) in bot.config.superusers
|
||||
and not plugins2info_dict[module]["limit_superuser"]
|
||||
):
|
||||
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
|
||||
try:
|
||||
if (
|
||||
(not isinstance(event, MessageEvent) and module not in other_limit_plugins)
|
||||
or await BanUser.is_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
) or (
|
||||
str(event.user_id) in bot.config.superusers
|
||||
and plugins2info_dict.get(module)
|
||||
and not plugins2info_dict[module]["limit_superuser"]
|
||||
):
|
||||
return
|
||||
except AttributeError:
|
||||
pass
|
||||
# 超级用户命令
|
||||
try:
|
||||
_plugin = nonebot.plugin.get_plugin(module)
|
||||
_module = _plugin.module
|
||||
plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
if (
|
||||
"[superuser]" in plugin_name.lower()
|
||||
and str(event.user_id) in bot.config.superusers
|
||||
):
|
||||
return
|
||||
except AttributeError:
|
||||
pass
|
||||
# 群黑名单检测 群总开关检测
|
||||
if (
|
||||
isinstance(event, GroupMessageEvent)
|
||||
or matcher.plugin_name in other_limit_plugins
|
||||
):
|
||||
try:
|
||||
if (
|
||||
group_manager.get_group_level(event.group_id) < 0
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
):
|
||||
raise IgnoredException("群黑名单")
|
||||
if not group_manager.check_group_bot_status(event.group_id):
|
||||
try:
|
||||
if str(event.get_message()) != "醒来":
|
||||
raise IgnoredException("功能总开关关闭状态")
|
||||
except ValueError:
|
||||
raise IgnoredException("功能总开关关闭状态")
|
||||
except AttributeError:
|
||||
pass
|
||||
if module in admin_manager.keys() and matcher.priority not in [1, 999]:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
# 个人权限
|
||||
if (
|
||||
not await LevelUser.check_level(
|
||||
event.user_id,
|
||||
event.group_id,
|
||||
admin_manager.get_plugin_level(module),
|
||||
)
|
||||
and admin_manager.get_plugin_level(module) > 0
|
||||
):
|
||||
try:
|
||||
if _flmt.check(event.user_id):
|
||||
_flmt.start_cd(event.user_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id,
|
||||
message=f"{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:"
|
||||
f"{admin_manager.get_plugin_level(module)}",
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
set_block_limit_false(event, module)
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
raise IgnoredException("权限不足")
|
||||
else:
|
||||
if not await LevelUser.check_level(
|
||||
event.user_id, 0, admin_manager.get_plugin_level(module)
|
||||
):
|
||||
try:
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id,
|
||||
message=f"你的权限不足喔,该功能需要的权限等级:{admin_manager.get_plugin_level(module)}",
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
set_block_limit_false(event, module)
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.user_id)
|
||||
raise IgnoredException("权限不足")
|
||||
if module in plugins2info_dict.keys() and matcher.priority not in [1, 999]:
|
||||
# 戳一戳单独判断
|
||||
if (
|
||||
isinstance(event, GroupMessageEvent)
|
||||
or isinstance(event, PokeNotifyEvent)
|
||||
or matcher.plugin_name in other_limit_plugins
|
||||
):
|
||||
if status_message_manager.get(event.group_id) is None:
|
||||
status_message_manager.delete(event.group_id)
|
||||
if plugins2info_dict[module]["level"] > group_manager.get_group_level(
|
||||
event.group_id
|
||||
):
|
||||
try:
|
||||
if _flmt_g.check(event.user_id) and module not in ignore_rst_module:
|
||||
_flmt_g.start_cd(event.user_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="群权限不足..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, module)
|
||||
raise IgnoredException("群权限不足")
|
||||
# 插件状态
|
||||
if not group_manager.get_plugin_status(module, event.group_id):
|
||||
try:
|
||||
if module not in ignore_rst_module and _flmt_s.check(
|
||||
event.group_id
|
||||
):
|
||||
_flmt_s.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="该群未开启此功能.."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, module)
|
||||
raise IgnoredException("未开启此功能...")
|
||||
# 管理员禁用
|
||||
if not group_manager.get_plugin_status(f"{module}:super", event.group_id):
|
||||
try:
|
||||
if (
|
||||
_flmt_s.check(event.group_id)
|
||||
and module not in ignore_rst_module
|
||||
):
|
||||
_flmt_s.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="管理员禁用了此群该功能..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, module)
|
||||
raise IgnoredException("管理员禁用了此群该功能...")
|
||||
# 群聊禁用
|
||||
if not plugins_manager.get_plugin_status(module, block_type="group"):
|
||||
try:
|
||||
if (
|
||||
_flmt_c.check(event.group_id)
|
||||
and module not in ignore_rst_module
|
||||
):
|
||||
_flmt_c.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="该功能在群聊中已被禁用..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.group_id)
|
||||
set_block_limit_false(event, module)
|
||||
raise IgnoredException("该插件在群聊中已被禁用...")
|
||||
else:
|
||||
# 私聊禁用
|
||||
if not plugins_manager.get_plugin_status(module, block_type="private"):
|
||||
try:
|
||||
if _flmt_c.check(event.user_id):
|
||||
_flmt_c.start_cd(event.user_id)
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id, message="该功能在私聊中已被禁用..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.user_id)
|
||||
set_block_limit_false(event, module)
|
||||
raise IgnoredException("该插件在私聊中已被禁用...")
|
||||
# 维护
|
||||
if not plugins_manager.get_plugin_status(module, block_type="all"):
|
||||
if isinstance(
|
||||
event, GroupMessageEvent
|
||||
) and group_manager.check_group_is_white(event.group_id):
|
||||
return
|
||||
try:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
if (
|
||||
_flmt_c.check(event.group_id)
|
||||
and module not in ignore_rst_module
|
||||
):
|
||||
_flmt_c.start_cd(event.group_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id, message="此功能正在维护..."
|
||||
)
|
||||
else:
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id, message="此功能正在维护..."
|
||||
)
|
||||
except ActionFailed:
|
||||
pass
|
||||
if event.is_tome():
|
||||
id_ = (
|
||||
event.group_id
|
||||
if isinstance(event, GroupMessageEvent)
|
||||
else event.user_id
|
||||
)
|
||||
status_message_manager.add(id_)
|
||||
set_block_limit_false(event, module)
|
||||
raise IgnoredException("此功能正在维护...")
|
||||
|
||||
# 以下为限制检测 #######################################################
|
||||
# 以下为限制检测 #######################################################
|
||||
# 以下为限制检测 #######################################################
|
||||
# 以下为限制检测 #######################################################
|
||||
# 以下为限制检测 #######################################################
|
||||
# 以下为限制检测 #######################################################
|
||||
# Cd
|
||||
if plugins2cd_manager.check_plugin_cd_status(module):
|
||||
plugin_cd_data = plugins2cd_manager.get_plugin_cd_data(module)
|
||||
check_type = plugin_cd_data["check_type"]
|
||||
limit_type = plugin_cd_data["limit_type"]
|
||||
rst = plugin_cd_data["rst"]
|
||||
if (
|
||||
(isinstance(event, PrivateMessageEvent) and check_type == "private")
|
||||
or (isinstance(event, GroupMessageEvent) and check_type == "group")
|
||||
or plugins2cd_manager.get_plugin_data(module).get("check_type") == "all"
|
||||
):
|
||||
cd_type_ = event.user_id
|
||||
if limit_type == "group" and isinstance(event, GroupMessageEvent):
|
||||
cd_type_ = event.group_id
|
||||
if not plugins2cd_manager.check(module, cd_type_):
|
||||
if rst:
|
||||
rst = await init_rst(rst, event)
|
||||
await send_msg(rst, bot, event)
|
||||
raise IgnoredException(f"{module} 正在cd中...")
|
||||
else:
|
||||
plugins2cd_manager.start_cd(module, cd_type_)
|
||||
# Block
|
||||
if plugins2block_manager.check_plugin_block_status(module):
|
||||
plugin_block_data = plugins2block_manager.get_plugin_block_data(module)
|
||||
check_type = plugin_block_data["check_type"]
|
||||
limit_type = plugin_block_data["limit_type"]
|
||||
rst = plugin_block_data["rst"]
|
||||
if (
|
||||
(isinstance(event, PrivateMessageEvent) and check_type == "private")
|
||||
or (isinstance(event, GroupMessageEvent) and check_type == "group")
|
||||
or check_type == "all"
|
||||
):
|
||||
block_type_ = event.user_id
|
||||
if limit_type == "group" and isinstance(event, GroupMessageEvent):
|
||||
block_type_ = event.group_id
|
||||
if plugins2block_manager.check(block_type_, module):
|
||||
if rst:
|
||||
rst = await init_rst(rst, event)
|
||||
await send_msg(rst, bot, event)
|
||||
raise IgnoredException(f"{event.user_id}正在调用{module}....")
|
||||
else:
|
||||
plugins2block_manager.set_true(block_type_, module)
|
||||
# Count
|
||||
if (
|
||||
plugins2count_manager.check_plugin_count_status(module)
|
||||
and event.user_id not in bot.config.superusers
|
||||
):
|
||||
plugin_count_data = plugins2count_manager.get_plugin_count_data(module)
|
||||
limit_type = plugin_count_data["limit_type"]
|
||||
rst = plugin_count_data["rst"]
|
||||
count_type_ = event.user_id
|
||||
if limit_type == "group" and isinstance(event, GroupMessageEvent):
|
||||
count_type_ = event.group_id
|
||||
if not plugins2count_manager.check(module, count_type_):
|
||||
if rst:
|
||||
rst = await init_rst(rst, event)
|
||||
await send_msg(rst, bot, event)
|
||||
raise IgnoredException(f"{module} count次数限制...")
|
||||
else:
|
||||
plugins2count_manager.increase(module, count_type_)
|
||||
# 功能花费的金币 #######################################
|
||||
# 功能花费的金币 #######################################
|
||||
if cost_gold:
|
||||
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
|
||||
|
||||
|
||||
async def send_msg(rst: str, bot: Bot, event: MessageEvent):
|
||||
"""
|
||||
发送信息
|
||||
:param rst: pass
|
||||
:param bot: pass
|
||||
:param event: pass
|
||||
"""
|
||||
rst = await init_rst(rst, event)
|
||||
try:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
status_message_manager.add(event.group_id)
|
||||
await bot.send_group_msg(group_id=event.group_id, message=Message(rst))
|
||||
else:
|
||||
status_message_manager.add(event.user_id)
|
||||
await bot.send_private_msg(user_id=event.user_id, message=Message(rst))
|
||||
except ActionFailed:
|
||||
pass
|
||||
async def _(matcher: Matcher, bot: Bot, event: Event):
|
||||
await AuthChecker().auth(matcher, bot, event)
|
||||
|
||||
|
||||
# 解除命令block阻塞
|
||||
@run_postprocessor
|
||||
async def _(
|
||||
matcher: Matcher,
|
||||
exception: Optional[Exception],
|
||||
bot: Bot,
|
||||
event: Event,
|
||||
state: T_State,
|
||||
matcher: Matcher,
|
||||
exception: Optional[Exception],
|
||||
bot: Bot,
|
||||
event: Event,
|
||||
state: T_State,
|
||||
):
|
||||
if not isinstance(event, MessageEvent) and matcher.plugin_name != "poke":
|
||||
return
|
||||
module = matcher.plugin_name
|
||||
set_block_limit_false(event, module)
|
||||
|
||||
|
||||
async def init_rst(rst: str, event: MessageEvent):
|
||||
if "[uname]" in rst:
|
||||
uname = event.sender.card or event.sender.nickname
|
||||
rst = rst.replace("[uname]", uname)
|
||||
if "[nickname]" in rst:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
nickname = await GroupInfoUser.get_group_member_nickname(
|
||||
event.user_id, event.group_id
|
||||
)
|
||||
else:
|
||||
nickname = await FriendUser.get_friend_nickname(event.user_id)
|
||||
rst = rst.replace("[nickname]", nickname)
|
||||
if "[at]" in rst and isinstance(event, GroupMessageEvent):
|
||||
rst = rst.replace("[at]", str(at(event.user_id)))
|
||||
return rst
|
||||
|
||||
@@ -29,10 +29,13 @@ _flmt = FreqLimiter(300)
|
||||
# 检查是否被ban
|
||||
@run_preprocessor
|
||||
async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
|
||||
if (
|
||||
(isinstance(event, MessageEvent) or isinstance(event, PokeNotifyEvent))
|
||||
and matcher.priority not in [1, 999]
|
||||
) or matcher.plugin_name in other_limit_plugins:
|
||||
if hasattr(event, "user_id") and (
|
||||
(
|
||||
(isinstance(event, MessageEvent) or isinstance(event, PokeNotifyEvent))
|
||||
and matcher.priority not in [1, 999]
|
||||
)
|
||||
or matcher.plugin_name in other_limit_plugins
|
||||
):
|
||||
try:
|
||||
if (
|
||||
await BanUser.is_super_ban(event.user_id)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from nonebot.exception import MockApiException
|
||||
from nonebot.adapters.onebot.v11 import Bot, Message
|
||||
from utils.manager import group_manager
|
||||
from services.log import logger
|
||||
from typing import Dict, Any
|
||||
import re
|
||||
|
||||
@@ -8,40 +9,48 @@ import re
|
||||
@Bot.on_calling_api
|
||||
async def _(bot: Bot, api: str, data: Dict[str, Any]):
|
||||
r = None
|
||||
if (
|
||||
(
|
||||
(api == "send_msg" and data.get("message_type") == "group")
|
||||
or api == "send_group_msg"
|
||||
)
|
||||
and (
|
||||
task = None
|
||||
group_id = None
|
||||
try:
|
||||
if (
|
||||
(
|
||||
r := re.search(
|
||||
"^\[\[_task\|(.*)]]",
|
||||
data["message"].strip()
|
||||
if isinstance(data["message"], str)
|
||||
else str(data["message"]["text"]).strip(),
|
||||
(api == "send_msg" and data.get("message_type") == "group")
|
||||
or api == "send_group_msg"
|
||||
)
|
||||
and (
|
||||
(
|
||||
r := re.search(
|
||||
"^\[\[_task\|(.*)]]",
|
||||
data["message"].strip()
|
||||
if isinstance(data["message"], str)
|
||||
else str(data["message"]["text"]).strip(),
|
||||
)
|
||||
)
|
||||
or (
|
||||
r := re.search(
|
||||
"^[[_task\|(.*)]]",
|
||||
data["message"].strip()
|
||||
if isinstance(data["message"], str)
|
||||
else str(data["message"]["text"]).strip(),
|
||||
)
|
||||
)
|
||||
)
|
||||
or (
|
||||
r := re.search(
|
||||
"^[[_task\|(.*)]]",
|
||||
data["message"].strip()
|
||||
if isinstance(data["message"], str)
|
||||
else str(data["message"]["text"]).strip(),
|
||||
and r.group(1) in group_manager.get_task_data().keys()
|
||||
):
|
||||
task = r.group(1)
|
||||
group_id = data["group_id"]
|
||||
except Exception as e:
|
||||
logger.error(f"TaskHook ERROR {type(e)}:{e}")
|
||||
else:
|
||||
if task and group_id:
|
||||
if (
|
||||
group_manager.get_group_level(group_id) < 0
|
||||
or not group_manager.check_task_status(task, group_id)
|
||||
):
|
||||
raise MockApiException(f"被动技能 {task} 处于关闭状态...")
|
||||
else:
|
||||
msg = str(data["message"]).strip()
|
||||
msg = msg.replace(f"[[_task|{task}]]", "").replace(
|
||||
f"[[_task|{task}]]", ""
|
||||
)
|
||||
)
|
||||
)
|
||||
and r.group(1) in group_manager.get_task_data().keys()
|
||||
):
|
||||
task = r.group(1)
|
||||
group_id = data["group_id"]
|
||||
if group_manager.get_group_level(
|
||||
group_id
|
||||
) < 0 or not await group_manager.check_group_task_status(group_id, task):
|
||||
raise MockApiException(f"被动技能 {task} 处于关闭状态...")
|
||||
else:
|
||||
msg = str(data["message"]).strip()
|
||||
msg = msg.replace(f"[[_task|{task}]]", "").replace(
|
||||
f"[[_task|{task}]]", ""
|
||||
)
|
||||
data["message"] = Message(msg)
|
||||
data["message"] = Message(msg)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from configs.path_config import DATA_PATH
|
||||
from .init_group_manager import init_group_manager, group_manager
|
||||
from .init_plugins_config import init_plugins_config
|
||||
from .init_plugins_data import init_plugins_data, plugins_manager
|
||||
from .init_none_plugin_count_manager import init_none_plugin_count_manager
|
||||
from .init_plugins_resources import init_plugins_resources
|
||||
from .init_plugins_settings import init_plugins_settings
|
||||
from .init_plugin_info import init_plugin_info
|
||||
from .init_plugins_limit import (
|
||||
init_plugins_block_limit,
|
||||
init_plugins_count_limit,
|
||||
@@ -12,7 +14,6 @@ from .init_plugins_limit import (
|
||||
from .init import init
|
||||
from .check_plugin_status import check_plugin_status
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from configs.path_config import DATA_PATH
|
||||
from services.log import logger
|
||||
from nonebot import Driver
|
||||
import nonebot
|
||||
@@ -31,23 +32,22 @@ async def _():
|
||||
"""
|
||||
初始化数据
|
||||
"""
|
||||
_flag = False
|
||||
config_file = DATA_PATH / "configs" / "plugins2config.yaml"
|
||||
if not config_file.exists():
|
||||
_flag = True
|
||||
_flag = not config_file.exists()
|
||||
init()
|
||||
init_plugins_settings(DATA_PATH)
|
||||
init_plugins_cd_limit(DATA_PATH)
|
||||
init_plugins_block_limit(DATA_PATH)
|
||||
init_plugins_count_limit(DATA_PATH)
|
||||
init_plugins_data(DATA_PATH)
|
||||
init_plugins_config(DATA_PATH)
|
||||
init_plugin_info()
|
||||
init_plugins_settings()
|
||||
init_plugins_cd_limit()
|
||||
init_plugins_block_limit()
|
||||
init_plugins_count_limit()
|
||||
init_plugins_data()
|
||||
init_plugins_config()
|
||||
init_plugins_resources()
|
||||
init_none_plugin_count_manager()
|
||||
x = group_manager.get_super_old_data()
|
||||
if x:
|
||||
for key in x.keys():
|
||||
plugins_manager.block_plugin(key, block_type=x[key])
|
||||
# x = group_manager.get_super_old_data()
|
||||
# if x:
|
||||
# for key in x.keys():
|
||||
# plugins_manager.block_plugin(key, block_type=x[key])
|
||||
if _flag:
|
||||
raise Exception("首次运行,已在configs目录下生成配置文件config.yaml,修改后重启即可...")
|
||||
logger.info("初始化数据完成...")
|
||||
@@ -55,5 +55,5 @@ async def _():
|
||||
|
||||
@driver.on_bot_connect
|
||||
async def _(bot: Bot):
|
||||
await init_group_manager()
|
||||
# await init_group_manager()
|
||||
await check_plugin_status(bot)
|
||||
|
||||
@@ -6,13 +6,13 @@ async def check_plugin_status(bot: Bot):
|
||||
"""
|
||||
遍历查看插件加载情况
|
||||
"""
|
||||
rst = ""
|
||||
msg = ""
|
||||
for plugin in plugins_manager.keys():
|
||||
data = plugins_manager.get(plugin)
|
||||
if data.get("error") or data.get("error") is None:
|
||||
rst += f'{plugin}:{data["plugin_name"]}\n'
|
||||
if rst:
|
||||
rst = "以下插件加载失败..\n" + rst
|
||||
if data.error:
|
||||
msg += f'{plugin}:{data.plugin_name}\n'
|
||||
if msg and bot.config.superusers:
|
||||
msg = "以下插件加载失败..\n" + msg
|
||||
await bot.send_private_msg(
|
||||
user_id=int(list(bot.config.superusers)[0]), message=rst[:-1]
|
||||
user_id=int(list(bot.config.superusers)[0]), message=msg.strip()
|
||||
)
|
||||
|
||||
@@ -19,36 +19,44 @@ def init_none_plugin_count_manager():
|
||||
"""
|
||||
清除已删除插件数据
|
||||
"""
|
||||
modules = [x.plugin_name for x in get_matchers()]
|
||||
modules = [x.plugin_name for x in get_matchers(True)]
|
||||
plugins_manager_list = list(plugins_manager.keys())
|
||||
for module in plugins_manager_list:
|
||||
if module not in modules or none_plugin_count_manager.check(module):
|
||||
try:
|
||||
plugin_name = plugins_manager.get(module)["plugin_name"]
|
||||
except (AttributeError, KeyError):
|
||||
plugin_name = ""
|
||||
if none_plugin_count_manager.check(module):
|
||||
try:
|
||||
if module not in modules or none_plugin_count_manager.check(module):
|
||||
try:
|
||||
plugins2settings_manager.delete(module)
|
||||
plugins2settings_manager.save()
|
||||
plugins2count_manager.delete(module)
|
||||
plugins2count_manager.save()
|
||||
plugins2cd_manager.delete(module)
|
||||
plugins2cd_manager.save()
|
||||
plugins2block_manager.delete(module)
|
||||
plugins2block_manager.save()
|
||||
plugins_manager.delete(module)
|
||||
plugins_manager.save()
|
||||
# resources_manager.remove_resource(module)
|
||||
none_plugin_count_manager.delete(module)
|
||||
logger.info(f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据...")
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据失败...{type(e)}:{e}")
|
||||
plugin_name = plugins_manager.get(module).plugin_name
|
||||
except (AttributeError, KeyError):
|
||||
plugin_name = ""
|
||||
if none_plugin_count_manager.check(module):
|
||||
try:
|
||||
plugins2settings_manager.delete(module)
|
||||
plugins2count_manager.delete(module)
|
||||
plugins2cd_manager.delete(module)
|
||||
plugins2block_manager.delete(module)
|
||||
plugins_manager.delete(module)
|
||||
plugins_manager.save()
|
||||
# resources_manager.remove_resource(module)
|
||||
none_plugin_count_manager.delete(module)
|
||||
logger.info(f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据...")
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据失败...{type(e)}:{e}"
|
||||
)
|
||||
else:
|
||||
none_plugin_count_manager.add_count(module)
|
||||
logger.info(
|
||||
f"{module}:{plugin_name} 插件疑似已删除,"
|
||||
f"加载{none_plugin_count_manager._max_count}次失败后将清除对应插件数据,"
|
||||
f"当前次数:{none_plugin_count_manager.get(module)}"
|
||||
)
|
||||
else:
|
||||
none_plugin_count_manager.add_count(module)
|
||||
logger.info(
|
||||
f"{module}:{plugin_name} 插件疑似已删除,加载{none_plugin_count_manager._max_count}次失败后将清除对应插件数据,当前次数:{none_plugin_count_manager._data[module]}")
|
||||
else:
|
||||
none_plugin_count_manager.reset(module)
|
||||
none_plugin_count_manager.reset(module)
|
||||
except Exception as e:
|
||||
logger.error(f"清除插件数据错误 {type(e)}:{e}")
|
||||
plugins2settings_manager.save()
|
||||
plugins2count_manager.save()
|
||||
plugins2cd_manager.save()
|
||||
plugins2block_manager.save()
|
||||
plugins_manager.save()
|
||||
none_plugin_count_manager.save()
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import random
|
||||
from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
from configs.config import Config
|
||||
from services import logger
|
||||
from utils.manager import (plugin_data_manager, plugins2block_manager,
|
||||
plugins2cd_manager, plugins2count_manager,
|
||||
plugins2settings_manager, plugins_manager)
|
||||
from utils.manager.models import (Plugin, PluginBlock, PluginCd, PluginCount,
|
||||
PluginData, PluginSetting, PluginType)
|
||||
from utils.utils import get_matchers
|
||||
|
||||
|
||||
def get_attr(module: ModuleType, name: str, default: Any = None) -> Any:
|
||||
"""
|
||||
说明:
|
||||
获取属性
|
||||
参数:
|
||||
:param module: module
|
||||
:param name: name
|
||||
:param default: default
|
||||
"""
|
||||
return getattr(module, name) if hasattr(module, name) else default
|
||||
|
||||
|
||||
def init_plugin_info():
|
||||
|
||||
for matcher in [x for x in get_matchers(True) if x.plugin]:
|
||||
try:
|
||||
plugin = matcher.plugin
|
||||
metadata = plugin.metadata
|
||||
extra = metadata.extra if metadata else {}
|
||||
if hasattr(plugin, "module"):
|
||||
module = plugin.module
|
||||
plugin_model = matcher.plugin_name
|
||||
plugin_name = (
|
||||
metadata.name
|
||||
if metadata and metadata.name
|
||||
else get_attr(module, "__zx_plugin_name__", matcher.plugin_name)
|
||||
)
|
||||
if not plugin_name:
|
||||
logger.warning(f"配置文件 模块:{plugin_model} 获取 plugin_name 失败...")
|
||||
continue
|
||||
if "[Admin]" in plugin_name:
|
||||
plugin_type = PluginType.ADMIN
|
||||
plugin_name = plugin_name.replace("[Admin]", "").strip()
|
||||
elif "[Hidden]" in plugin_name:
|
||||
plugin_type = PluginType.HIDDEN
|
||||
plugin_name = plugin_name.replace("[Hidden]", "").strip()
|
||||
elif "[Superuser]" in plugin_name:
|
||||
plugin_type = PluginType.SUPERUSER
|
||||
plugin_name = plugin_name.replace("[Superuser]", "").strip()
|
||||
else:
|
||||
plugin_type = PluginType.NORMAL
|
||||
plugin_usage = (
|
||||
metadata.usage
|
||||
if metadata and metadata.usage
|
||||
else get_attr(module, "__plugin_usage__")
|
||||
)
|
||||
plugin_des = (
|
||||
metadata.description
|
||||
if metadata and metadata.description
|
||||
else get_attr(module, "__plugin_des__")
|
||||
)
|
||||
menu_type = get_attr(module, "__plugin_type__") or ("normal",)
|
||||
plugin_setting = get_attr(module, "__plugin_settings__")
|
||||
if plugin_setting:
|
||||
plugin_setting = PluginSetting(**plugin_setting)
|
||||
plugin_setting.plugin_type = menu_type
|
||||
plugin_superuser_usage = get_attr(module, "__plugin_super_usage__")
|
||||
plugin_task = get_attr(module, "__plugin_task__")
|
||||
plugin_version = extra.get("__plugin_version__") or get_attr(
|
||||
module, "__plugin_version__"
|
||||
)
|
||||
plugin_author = extra.get("__plugin_author__") or get_attr(
|
||||
module, "__plugin_author__"
|
||||
)
|
||||
plugin_cd = get_attr(module, "__plugin_cd_limit__")
|
||||
if plugin_cd:
|
||||
plugin_cd = PluginCd(**plugin_cd)
|
||||
plugin_block = get_attr(module, "__plugin_block_limit__")
|
||||
if plugin_block:
|
||||
plugin_block = PluginBlock(**plugin_block)
|
||||
plugin_count = get_attr(module, "__plugin_count_limit__")
|
||||
if plugin_count:
|
||||
plugin_count = PluginCount(**plugin_count)
|
||||
plugin_resources = get_attr(module, "__plugin_resources__")
|
||||
plugin_configs = get_attr(module, "__plugin_configs__")
|
||||
if settings := plugins2settings_manager.get(plugin_model):
|
||||
plugin_setting = settings
|
||||
if plugin_cd_limit := plugins2cd_manager.get(plugin_model):
|
||||
plugin_cd = plugin_cd_limit
|
||||
if plugin_block_limit := plugins2block_manager.get(plugin_model):
|
||||
plugin_block = plugin_block_limit
|
||||
if plugin_count_limit := plugins2count_manager.get(plugin_model):
|
||||
plugin_count = plugin_count_limit
|
||||
if plugin_cfg := Config.get(plugin_model):
|
||||
plugin_configs = plugin_cfg
|
||||
plugin_status = plugins_manager.get(plugin_model)
|
||||
if not plugin_status:
|
||||
plugin_status = Plugin(plugin_name=plugin_model)
|
||||
plugin_status.author = plugin_author
|
||||
plugin_status.version = plugin_version
|
||||
plugin_data = PluginData(
|
||||
model=plugin_model,
|
||||
name=plugin_name.strip(),
|
||||
plugin_type=plugin_type,
|
||||
usage=plugin_usage,
|
||||
superuser_usage=plugin_superuser_usage,
|
||||
des=plugin_des,
|
||||
task=plugin_task,
|
||||
menu_type=menu_type,
|
||||
plugin_setting=plugin_setting,
|
||||
plugin_cd=plugin_cd,
|
||||
plugin_block=plugin_block,
|
||||
plugin_count=plugin_count,
|
||||
plugin_resources=plugin_resources,
|
||||
plugin_configs=plugin_configs,
|
||||
plugin_status=plugin_status,
|
||||
)
|
||||
plugin_data_manager.add_plugin_info(plugin_data)
|
||||
except Exception as e:
|
||||
logger.error(f"构造插件数据失败 {matcher.plugin_name} - {type(e)}:{e}")
|
||||
@@ -1,125 +1,84 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import round_trip_load, round_trip_dump, YAML
|
||||
from utils.manager import admin_manager, plugins_manager
|
||||
from utils.manager import admin_manager, plugins_manager, plugin_data_manager
|
||||
from configs.config import Config
|
||||
from services.log import logger
|
||||
from utils.text_utils import prompt2cn
|
||||
from utils.utils import get_matchers
|
||||
from utils.utils import scheduler
|
||||
from configs.path_config import DATA_PATH
|
||||
from ruamel import yaml
|
||||
|
||||
|
||||
_yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
def init_plugins_config(data_path):
|
||||
def init_plugins_config():
|
||||
"""
|
||||
初始化插件数据配置
|
||||
"""
|
||||
plugins2config_file = data_path / "configs" / "plugins2config.yaml"
|
||||
plugins2config_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
_data = {}
|
||||
if plugins2config_file.exists():
|
||||
_data = _yaml.load(open(plugins2config_file, "r", encoding="utf8"))
|
||||
_matchers = get_matchers(True)
|
||||
plugins2config_file = DATA_PATH / "configs" / "plugins2config.yaml"
|
||||
_data = Config.get_data()
|
||||
# 优先使用 metadata 数据
|
||||
for matcher in _matchers:
|
||||
_plugin = matcher.plugin
|
||||
if not _plugin:
|
||||
continue
|
||||
metadata = _plugin.metadata
|
||||
try:
|
||||
_module = _plugin.module
|
||||
except AttributeError:
|
||||
continue
|
||||
plugin_version = None
|
||||
if metadata:
|
||||
plugin_version = metadata.extra.get("version")
|
||||
if not plugin_version:
|
||||
try:
|
||||
plugin_version = _module.__getattribute__("__plugin_version__")
|
||||
except AttributeError:
|
||||
pass
|
||||
if metadata and metadata.config:
|
||||
plugin_configs = {}
|
||||
for key, value in metadata.config.__fields__.items():
|
||||
plugin_configs[key.upper()] = {
|
||||
"value": value.default,
|
||||
"default_value": value.default
|
||||
}
|
||||
else:
|
||||
try:
|
||||
plugin_configs = _module.__getattribute__("__plugin_configs__")
|
||||
except AttributeError:
|
||||
continue
|
||||
# 插件配置版本更新或为Version为None或不在存储配置内,当使用metadata时,必定更新
|
||||
if isinstance(plugin_version, str) or (
|
||||
plugin_version is None
|
||||
or (
|
||||
_data.get(matcher.plugin_name)
|
||||
and _data[matcher.plugin_name].keys() != plugin_configs.keys()
|
||||
)
|
||||
or plugin_version > plugins_manager.get(matcher.plugin_name)["version"]
|
||||
or matcher.plugin_name not in _data.keys()
|
||||
):
|
||||
for key in plugin_configs:
|
||||
if isinstance(plugin_configs[key], dict):
|
||||
for matcher in get_matchers(True):
|
||||
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
|
||||
# 插件配置版本更新或为Version为None或不在存储配置内,当使用metadata时,必定更新
|
||||
if plugin_data.plugin_configs and (
|
||||
isinstance(plugin_data.plugin_status.version, str)
|
||||
or (
|
||||
plugin_data.plugin_status.version is None
|
||||
or (
|
||||
_data.get(matcher.plugin_name)
|
||||
and _data[matcher.plugin_name].keys()
|
||||
!= plugin_data.plugin_configs.keys()
|
||||
)
|
||||
or plugin_data.plugin_status.version
|
||||
> plugins_manager.get(matcher.plugin_name).version
|
||||
or matcher.plugin_name not in _data.keys()
|
||||
)
|
||||
):
|
||||
plugin_configs = plugin_data.plugin_configs
|
||||
for key in plugin_configs:
|
||||
if isinstance(plugin_data.plugin_configs[key], dict):
|
||||
Config.add_plugin_config(
|
||||
matcher.plugin_name,
|
||||
key,
|
||||
plugin_configs[key].get("value"),
|
||||
help_=plugin_configs[key].get("help"),
|
||||
default_value=plugin_configs[key].get("default_value"),
|
||||
_override=True,
|
||||
)
|
||||
else:
|
||||
Config.add_plugin_config(
|
||||
matcher.plugin_name, key, plugin_configs[key]
|
||||
)
|
||||
elif plugin_configs := _data.get(matcher.plugin_name):
|
||||
for key in plugin_configs:
|
||||
Config.add_plugin_config(
|
||||
matcher.plugin_name,
|
||||
key,
|
||||
plugin_configs[key].get("value"),
|
||||
help_=plugin_configs[key].get("help"),
|
||||
default_value=plugin_configs[key].get("default_value"),
|
||||
plugin_configs[key]["value"],
|
||||
help_=plugin_configs[key]["help"],
|
||||
default_value=plugin_configs[key]["default_value"],
|
||||
_override=True,
|
||||
)
|
||||
else:
|
||||
Config.add_plugin_config(
|
||||
matcher.plugin_name, key, plugin_configs[key]
|
||||
)
|
||||
else:
|
||||
plugin_configs = _data[matcher.plugin_name]
|
||||
for key in plugin_configs:
|
||||
Config.add_plugin_config(
|
||||
matcher.plugin_name,
|
||||
key,
|
||||
plugin_configs[key]["value"],
|
||||
help_=plugin_configs[key]["help"],
|
||||
default_value=plugin_configs[key]["default_value"],
|
||||
_override=True,
|
||||
)
|
||||
if not Config.is_empty():
|
||||
Config.save()
|
||||
_data = round_trip_load(open(plugins2config_file, encoding="utf8"))
|
||||
for plugin in _data.keys():
|
||||
try:
|
||||
plugin_name = plugins_manager.get(plugin)["plugin_name"]
|
||||
plugin_name = plugins_manager.get(plugin).plugin_name
|
||||
except (AttributeError, TypeError):
|
||||
plugin_name = plugin
|
||||
_data[plugin].yaml_set_start_comment(plugin_name, indent=2)
|
||||
# 初始化未设置的管理员权限等级
|
||||
for k, v in Config.get_admin_level_data():
|
||||
try:
|
||||
admin_manager.set_admin_level(k, v)
|
||||
except KeyError as e:
|
||||
raise KeyError(f"{e} ****** 请检查是否有插件加载失败 ******")
|
||||
admin_manager.set_admin_level(k, v)
|
||||
# 存完插件基本设置
|
||||
with open(plugins2config_file, "w", encoding="utf8") as wf:
|
||||
round_trip_dump(
|
||||
_data, wf, indent=2, Dumper=yaml.RoundTripDumper, allow_unicode=True
|
||||
)
|
||||
user_config_file = Path() / "configs" / "config.yaml"
|
||||
# if not user_config_file.exists():
|
||||
_replace_config()
|
||||
# else:
|
||||
# logger.info('五分钟后将进行配置数据替换,请注意...')
|
||||
# scheduler.add_job(
|
||||
# _replace_config,
|
||||
# "date",
|
||||
# run_date=datetime.now() + timedelta(minutes=5),
|
||||
# id=f"_replace_config"
|
||||
# )
|
||||
|
||||
|
||||
def _replace_config():
|
||||
@@ -159,9 +118,7 @@ def _replace_config():
|
||||
temp_file = Path() / "configs" / "temp_config.yaml"
|
||||
try:
|
||||
with open(temp_file, "w", encoding="utf8") as wf:
|
||||
yaml.dump(
|
||||
_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True
|
||||
)
|
||||
yaml.dump(_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
with open(temp_file, "r", encoding="utf8") as rf:
|
||||
_data = round_trip_load(rf)
|
||||
# 添加注释
|
||||
@@ -181,7 +138,7 @@ def _replace_config():
|
||||
plugin_name = None
|
||||
if not plugin_name:
|
||||
try:
|
||||
plugin_name = plugins_manager.get(plugin)["plugin_name"]
|
||||
plugin_name = plugins_manager.get(plugin).plugin_name
|
||||
except (AttributeError, TypeError):
|
||||
plugin_name = plugin
|
||||
plugin_name = (
|
||||
@@ -195,9 +152,7 @@ def _replace_config():
|
||||
rst += f'{k}: {Config[plugin][k]["help"]}' + "\n"
|
||||
_data[plugin].yaml_set_start_comment(rst[:-1], indent=2)
|
||||
with open(Path() / "configs" / "config.yaml", "w", encoding="utf8") as wf:
|
||||
round_trip_dump(
|
||||
_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True
|
||||
)
|
||||
round_trip_dump(_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
except Exception as e:
|
||||
logger.error(f"生成简易配置注释错误 {type(e)}:{e}")
|
||||
if temp_file.exists():
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from pathlib import Path
|
||||
|
||||
from ruamel.yaml import YAML
|
||||
from utils.manager import plugins_manager
|
||||
from utils.manager import plugins_manager, plugin_data_manager
|
||||
from utils.utils import get_matchers
|
||||
import nonebot
|
||||
from services.log import logger
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -13,84 +13,45 @@ except ModuleNotFoundError:
|
||||
_yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
def init_plugins_data(data_path):
|
||||
def init_plugins_data():
|
||||
"""
|
||||
初始化插件数据信息
|
||||
"""
|
||||
plugin2data_file = data_path / "manager" / "plugin_manager.json"
|
||||
plugin2data_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
_data = {}
|
||||
if plugin2data_file.exists():
|
||||
_data = json.load(open(plugin2data_file, "r", encoding="utf8"))
|
||||
_matchers = get_matchers(True)
|
||||
for matcher in _matchers:
|
||||
for matcher in get_matchers(True):
|
||||
_plugin = matcher.plugin
|
||||
if not _plugin:
|
||||
continue
|
||||
metadata = _plugin.metadata
|
||||
try:
|
||||
_module = _plugin.module
|
||||
except AttributeError:
|
||||
if matcher.plugin_name not in _data.keys():
|
||||
if matcher.plugin_name not in plugins_manager.keys():
|
||||
plugins_manager.add_plugin_data(
|
||||
matcher.plugin_name, matcher.plugin_name, error=True
|
||||
)
|
||||
else:
|
||||
plugins_manager.set_module_data(matcher.plugin_name, "error", True)
|
||||
plugin_data = plugins_manager.get(matcher.plugin_name)
|
||||
if plugin_data:
|
||||
plugins_manager.set_module_data(
|
||||
matcher.plugin_name, "version", plugin_data.get("version")
|
||||
)
|
||||
plugins_manager[matcher.plugin_name].error = True
|
||||
else:
|
||||
plugin_version = None
|
||||
if metadata:
|
||||
plugin_version = metadata.extra.get("version")
|
||||
if not plugin_version:
|
||||
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
|
||||
try:
|
||||
plugin_version = _module.__getattribute__("__plugin_version__")
|
||||
except AttributeError:
|
||||
pass
|
||||
if metadata:
|
||||
plugin_name = metadata.name
|
||||
else:
|
||||
try:
|
||||
plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
except AttributeError:
|
||||
plugin_name = matcher.plugin_name
|
||||
plugin_author = None
|
||||
if metadata:
|
||||
plugin_author = metadata.extra.get('author')
|
||||
try:
|
||||
plugin_author = _module.__getattribute__("__plugin_author__")
|
||||
except AttributeError:
|
||||
pass
|
||||
if matcher.plugin_name in plugins_manager.keys():
|
||||
plugins_manager.set_module_data(matcher.plugin_name, "error", False)
|
||||
if matcher.plugin_name not in plugins_manager.keys():
|
||||
plugins_manager.add_plugin_data(
|
||||
matcher.plugin_name,
|
||||
plugin_name=plugin_name,
|
||||
author=plugin_author,
|
||||
version=plugin_version,
|
||||
)
|
||||
# metadata不检测version
|
||||
elif isinstance(plugin_version, str) or plugins_manager[matcher.plugin_name]["version"] is None or (
|
||||
plugin_version is not None
|
||||
and plugin_version > plugins_manager[matcher.plugin_name]["version"]
|
||||
):
|
||||
plugins_manager.set_module_data(
|
||||
matcher.plugin_name, "plugin_name", plugin_name
|
||||
)
|
||||
plugins_manager.set_module_data(matcher.plugin_name, "author", plugin_author)
|
||||
plugins_manager.set_module_data(
|
||||
matcher.plugin_name, "version", plugin_version
|
||||
)
|
||||
if matcher.plugin_name in _data.keys():
|
||||
plugins_manager.set_module_data(
|
||||
matcher.plugin_name, "error", _data[matcher.plugin_name]["error"]
|
||||
)
|
||||
plugins_manager.set_module_data(
|
||||
matcher.plugin_name, "plugin_name", _data[matcher.plugin_name]["plugin_name"]
|
||||
)
|
||||
plugin_version = plugin_data.plugin_status.version
|
||||
plugin_name = plugin_data.name
|
||||
plugin_author = plugin_data.plugin_status.author
|
||||
if matcher.plugin_name in plugins_manager.keys():
|
||||
plugins_manager[matcher.plugin_name].error = False
|
||||
if matcher.plugin_name not in plugins_manager.keys():
|
||||
plugins_manager.add_plugin_data(
|
||||
matcher.plugin_name,
|
||||
plugin_name=plugin_name,
|
||||
author=plugin_author,
|
||||
version=plugin_version,
|
||||
)
|
||||
elif isinstance(plugin_version, str) or plugins_manager[matcher.plugin_name].version is None or (
|
||||
plugin_version is not None
|
||||
and plugin_version > float(plugins_manager[matcher.plugin_name].version)
|
||||
):
|
||||
plugins_manager[matcher.plugin_name].plugin_name = plugin_name
|
||||
plugins_manager[matcher.plugin_name].author = plugin_author
|
||||
plugins_manager[matcher.plugin_name].version = plugin_version
|
||||
except Exception as e:
|
||||
logger.error(f"插件数据 {matcher.plugin_name} 加载发生错误 {type(e)}:{e}")
|
||||
plugins_manager.save()
|
||||
|
||||
@@ -1,157 +1,64 @@
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import round_trip_load, round_trip_dump, YAML
|
||||
from utils.manager import (
|
||||
plugins2cd_manager,
|
||||
plugins2block_manager,
|
||||
plugins2count_manager,
|
||||
plugin_data_manager,
|
||||
)
|
||||
from utils.utils import get_matchers
|
||||
from ruamel import yaml
|
||||
import nonebot
|
||||
from configs.path_config import DATA_PATH
|
||||
|
||||
|
||||
_yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
def init_plugins_cd_limit(data_path):
|
||||
def init_plugins_cd_limit():
|
||||
"""
|
||||
加载 cd 限制
|
||||
"""
|
||||
plugins2cd_file = data_path / "configs" / "plugins2cd.yaml"
|
||||
plugins2cd_file = DATA_PATH / "configs" / "plugins2cd.yaml"
|
||||
plugins2cd_file.parent.mkdir(exist_ok=True, parents=True)
|
||||
_data = {}
|
||||
_matchers = get_matchers()
|
||||
for matcher in _matchers:
|
||||
if not plugins2cd_manager.get_plugin_cd_data(matcher.plugin_name):
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
try:
|
||||
_module = _plugin.module
|
||||
plugin_cd_limit = _module.__getattribute__("__plugin_cd_limit__")
|
||||
for matcher in get_matchers(True):
|
||||
if not plugins2cd_manager.get_plugin_cd_data(matcher.plugin_name) and (
|
||||
plugin_data := plugin_data_manager.get(matcher.plugin_name)
|
||||
):
|
||||
if plugin_data.plugin_cd:
|
||||
plugins2cd_manager.add_cd_limit(
|
||||
matcher.plugin_name, **plugin_cd_limit
|
||||
matcher.plugin_name, plugin_data.plugin_cd
|
||||
)
|
||||
except AttributeError:
|
||||
pass
|
||||
if not plugins2cd_manager.keys():
|
||||
plugins2cd_manager.add_cd_limit(
|
||||
"这是一个示例"
|
||||
)
|
||||
_tmp_data = {"PluginCdLimit": plugins2cd_manager.get_data()}
|
||||
with open(plugins2cd_file, "w", encoding="utf8") as wf:
|
||||
yaml.dump(_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
_data = round_trip_load(open(plugins2cd_file, encoding="utf8"))
|
||||
_data["PluginCdLimit"].yaml_set_start_comment(
|
||||
"""# 需要cd的功能
|
||||
# 自定义的功能需要cd也可以在此配置
|
||||
# key:模块名称
|
||||
# cd:cd 时长(秒)
|
||||
# status:此限制的开关状态
|
||||
# check_type:'private'/'group'/'all',限制私聊/群聊/全部
|
||||
# limit_type:监听对象,以user_id或group_id作为键来限制,'user':用户id,'group':群id
|
||||
# 示例:'user':用户N秒内触发1次,'group':群N秒内触发1次
|
||||
# rst:回复的话,可以添加[at],[uname],[nickname]来对应艾特,用户群名称,昵称系统昵称
|
||||
# rst 为 "" 或 None 时则不回复
|
||||
# rst示例:"[uname]你冲的太快了,[nickname]先生,请稍后再冲[at]"
|
||||
# rst回复:"老色批你冲的太快了,欧尼酱先生,请稍后再冲@老色批"
|
||||
# 用户昵称↑ 昵称系统的昵称↑ 艾特用户↑""",
|
||||
indent=2,
|
||||
)
|
||||
with open(plugins2cd_file, "w", encoding="utf8") as wf:
|
||||
round_trip_dump(_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
plugins2cd_manager.add_cd_limit("这是一个示例")
|
||||
plugins2cd_manager.save()
|
||||
plugins2cd_manager.reload_cd_limit()
|
||||
|
||||
|
||||
def init_plugins_block_limit(data_path):
|
||||
def init_plugins_block_limit():
|
||||
"""
|
||||
加载阻塞限制
|
||||
"""
|
||||
plugins2block_file = data_path / "configs" / "plugins2block.yaml"
|
||||
plugins2block_file.parent.mkdir(exist_ok=True, parents=True)
|
||||
_data = {}
|
||||
_matchers = get_matchers()
|
||||
for matcher in _matchers:
|
||||
if not plugins2block_manager.get_plugin_block_data(matcher.plugin_name):
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
try:
|
||||
_module = _plugin.module
|
||||
plugin_block_limit = _module.__getattribute__("__plugin_block_limit__")
|
||||
for matcher in get_matchers(True):
|
||||
if not plugins2block_manager.get_plugin_block_data(matcher.plugin_name) and (
|
||||
plugin_data := plugin_data_manager.get(matcher.plugin_name)
|
||||
):
|
||||
if plugin_data.plugin_block:
|
||||
plugins2block_manager.add_block_limit(
|
||||
matcher.plugin_name, **plugin_block_limit
|
||||
matcher.plugin_name, plugin_data.plugin_block
|
||||
)
|
||||
except AttributeError:
|
||||
pass
|
||||
if not plugins2block_manager.keys():
|
||||
plugins2block_manager.add_block_limit(
|
||||
"这是一个示例"
|
||||
)
|
||||
_tmp_data = {"PluginBlockLimit": plugins2block_manager.get_data()}
|
||||
with open(plugins2block_file, "w", encoding="utf8") as wf:
|
||||
yaml.dump(_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
_data = round_trip_load(open(plugins2block_file, encoding="utf8"))
|
||||
_data["PluginBlockLimit"].yaml_set_start_comment(
|
||||
"""# 用户调用阻塞
|
||||
# 即 当用户调用此功能还未结束时
|
||||
# 用发送消息阻止用户重复调用此命令直到该命令结束
|
||||
# key:模块名称
|
||||
# status:此限制的开关状态
|
||||
# check_type:'private'/'group'/'all',限制私聊/群聊/全部
|
||||
# limit_type:监听对象,以user_id或group_id作为键来限制,'user':用户id,'group':群id
|
||||
# 示例:'user':阻塞用户,'group':阻塞群聊
|
||||
# rst:回复的话,可以添加[at],[uname],[nickname]来对应艾特,用户群名称,昵称系统昵称
|
||||
# rst 为 "" 或 None 时则不回复
|
||||
# rst示例:"[uname]你冲的太快了,[nickname]先生,请稍后再冲[at]"
|
||||
# rst回复:"老色批你冲的太快了,欧尼酱先生,请稍后再冲@老色批"
|
||||
# 用户昵称↑ 昵称系统的昵称↑ 艾特用户↑""",
|
||||
indent=2,
|
||||
)
|
||||
with open(plugins2block_file, "w", encoding="utf8") as wf:
|
||||
round_trip_dump(_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
plugins2block_manager.add_block_limit("这是一个示例")
|
||||
plugins2block_manager.save()
|
||||
plugins2block_manager.reload_block_limit()
|
||||
|
||||
|
||||
def init_plugins_count_limit(data_path):
|
||||
def init_plugins_count_limit():
|
||||
"""
|
||||
加载次数限制
|
||||
"""
|
||||
plugins2count_file = data_path / "configs" / "plugins2count.yaml"
|
||||
plugins2count_file.parent.mkdir(exist_ok=True, parents=True)
|
||||
_data = {}
|
||||
_matchers = get_matchers()
|
||||
for matcher in _matchers:
|
||||
if not plugins2count_manager.get_plugin_count_data(matcher.plugin_name):
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
try:
|
||||
_module = _plugin.module
|
||||
plugin_count_limit = _module.__getattribute__("__plugin_count_limit__")
|
||||
for matcher in get_matchers(True):
|
||||
if not plugins2count_manager.get_plugin_count_data(matcher.plugin_name) and (
|
||||
plugin_data := plugin_data_manager.get(matcher.plugin_name)
|
||||
):
|
||||
if plugin_data.plugin_count:
|
||||
plugins2count_manager.add_count_limit(
|
||||
matcher.plugin_name, **plugin_count_limit
|
||||
matcher.plugin_name, plugin_data.plugin_count
|
||||
)
|
||||
except AttributeError:
|
||||
pass
|
||||
if not plugins2count_manager.keys():
|
||||
plugins2count_manager.add_count_limit(
|
||||
"这是一个示例"
|
||||
)
|
||||
_tmp_data = {"PluginCountLimit": plugins2count_manager.get_data()}
|
||||
with open(plugins2count_file, "w", encoding="utf8") as wf:
|
||||
yaml.dump(_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
_data = round_trip_load(open(plugins2count_file, encoding="utf8"))
|
||||
_data["PluginCountLimit"].yaml_set_start_comment(
|
||||
"""# 命令每日次数限制
|
||||
# 即 用户/群聊 每日可调用命令的次数 [数据内存存储,重启将会重置]
|
||||
# 每日调用直到 00:00 刷新
|
||||
# key:模块名称
|
||||
# max_count: 每日调用上限
|
||||
# status:此限制的开关状态
|
||||
# limit_type:监听对象,以user_id或group_id作为键来限制,'user':用户id,'group':群id
|
||||
# 示例:'user':用户上限,'group':群聊上限
|
||||
# rst:回复的话,可以添加[at],[uname],[nickname]来对应艾特,用户群名称,昵称系统昵称
|
||||
# rst 为 "" 或 None 时则不回复
|
||||
# rst示例:"[uname]你冲的太快了,[nickname]先生,请稍后再冲[at]"
|
||||
# rst回复:"老色批你冲的太快了,欧尼酱先生,请稍后再冲@老色批"
|
||||
# 用户昵称↑ 昵称系统的昵称↑ 艾特用户↑""",
|
||||
indent=2,
|
||||
)
|
||||
with open(plugins2count_file, "w", encoding="utf8") as wf:
|
||||
round_trip_dump(_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
plugins2count_manager.add_count_limit("这是一个示例")
|
||||
plugins2count_manager.save()
|
||||
plugins2count_manager.reload_count_limit()
|
||||
|
||||
@@ -1,29 +1,21 @@
|
||||
from utils.manager import resources_manager
|
||||
from utils.manager import resources_manager, plugin_data_manager
|
||||
from utils.utils import get_matchers
|
||||
from services.log import logger
|
||||
from pathlib import Path
|
||||
import nonebot
|
||||
|
||||
|
||||
def init_plugins_resources():
|
||||
"""
|
||||
资源文件路径的移动
|
||||
"""
|
||||
_tmp = []
|
||||
for matcher in get_matchers():
|
||||
if matcher.plugin_name not in _tmp:
|
||||
_tmp.append(matcher.plugin_name)
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
for matcher in get_matchers(True):
|
||||
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
|
||||
try:
|
||||
_module = _plugin.module
|
||||
_module = matcher.plugin.module
|
||||
except AttributeError:
|
||||
logger.warning(f"插件 {matcher.plugin_name} 加载失败...,资源控制未加载...")
|
||||
else:
|
||||
try:
|
||||
resources = _module.__getattribute__("__plugin_resources__")
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
if resources := plugin_data.plugin_resources:
|
||||
path = Path(_module.__getattribute__("__file__")).parent
|
||||
for resource in resources.keys():
|
||||
resources_manager.add_resource(
|
||||
|
||||
@@ -1,140 +1,42 @@
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import round_trip_load, round_trip_dump, YAML
|
||||
from utils.manager import plugins2settings_manager, admin_manager
|
||||
from utils.manager import plugins2settings_manager, admin_manager, plugin_data_manager
|
||||
from services.log import logger
|
||||
from utils.manager.models import PluginType
|
||||
from utils.utils import get_matchers
|
||||
from ruamel import yaml
|
||||
import nonebot
|
||||
|
||||
|
||||
_yaml = YAML(typ="safe")
|
||||
|
||||
|
||||
def init_plugins_settings(data_path: str):
|
||||
def init_plugins_settings():
|
||||
"""
|
||||
初始化插件设置,从插件中获取 __zx_plugin_name__,__plugin_cmd__,__plugin_settings__
|
||||
"""
|
||||
plugins2settings_file = data_path / "configs" / "plugins2settings.yaml"
|
||||
plugins2settings_file.parent.mkdir(exist_ok=True, parents=True)
|
||||
_matchers = get_matchers(True)
|
||||
_tmp_module = {}
|
||||
_tmp = []
|
||||
for x in plugins2settings_manager.keys():
|
||||
try:
|
||||
_plugin = nonebot.plugin.get_plugin(x)
|
||||
_module = _plugin.module
|
||||
metadata = _plugin.metadata
|
||||
plugin_name = (
|
||||
metadata.name
|
||||
if metadata
|
||||
else _module.__getattribute__("__zx_plugin_name__")
|
||||
)
|
||||
_tmp_module[x] = plugin_name
|
||||
_module.__getattribute__("__zx_plugin_name__")
|
||||
except (KeyError, AttributeError) as e:
|
||||
logger.warning(f"配置文件 模块:{x} 获取 plugin_name 失败...{e}")
|
||||
_tmp_module[x] = ""
|
||||
for matcher in _matchers:
|
||||
for matcher in get_matchers(True):
|
||||
try:
|
||||
if matcher.plugin_name not in plugins2settings_manager.keys():
|
||||
_plugin = matcher.plugin
|
||||
if not _plugin:
|
||||
continue
|
||||
metadata = _plugin.metadata
|
||||
try:
|
||||
_module = _plugin.module
|
||||
except AttributeError:
|
||||
logger.warning(f"插件 {matcher.plugin_name} 加载失败...,插件控制未加载.")
|
||||
else:
|
||||
try:
|
||||
if metadata:
|
||||
plugin_name = metadata.name
|
||||
else:
|
||||
plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
if "[admin]" in plugin_name.lower():
|
||||
try:
|
||||
admin_settings = _module.__getattribute__(
|
||||
"__plugin_settings__"
|
||||
if plugin_data := plugin_data_manager.get(matcher.plugin_name):
|
||||
if plugin_settings := plugin_data.plugin_setting:
|
||||
# 管理员命令
|
||||
if plugin_data.plugin_type == PluginType.ADMIN:
|
||||
admin_manager.add_admin_plugin_settings(
|
||||
matcher.plugin_name, plugin_settings.cmd, plugin_settings.level
|
||||
)
|
||||
else:
|
||||
plugins2settings_manager.add_plugin_settings(
|
||||
matcher.plugin_name, plugin_settings
|
||||
)
|
||||
level = admin_settings["admin_level"]
|
||||
cmd = admin_settings.get("cmd")
|
||||
except (AttributeError, KeyError):
|
||||
level = 5
|
||||
cmd = None
|
||||
if level is None:
|
||||
level = 5
|
||||
admin_manager.add_admin_plugin_settings(
|
||||
matcher.plugin_name, cmd, level
|
||||
)
|
||||
if (
|
||||
"[hidden]" in plugin_name.lower()
|
||||
or "[admin]" in plugin_name.lower()
|
||||
or "[superuser]" in plugin_name.lower()
|
||||
or matcher.plugin_name in plugins2settings_manager.keys()
|
||||
):
|
||||
continue
|
||||
except AttributeError:
|
||||
if matcher.plugin_name not in _tmp:
|
||||
logger.warning(
|
||||
f"获取插件 {matcher.plugin_name} __zx_plugin_name__ 失败...,插件控制未加载."
|
||||
)
|
||||
else:
|
||||
_tmp_module[matcher.plugin_name] = plugin_name
|
||||
try:
|
||||
plugin_settings = _module.__getattribute__(
|
||||
"__plugin_settings__"
|
||||
)
|
||||
except AttributeError:
|
||||
plugin_settings = {"cmd": [matcher.plugin_name, plugin_name]}
|
||||
if not plugin_settings.get("cost_gold"):
|
||||
plugin_settings["cost_gold"] = 0
|
||||
if (
|
||||
plugin_settings.get("cmd") is not None
|
||||
and plugin_name not in plugin_settings["cmd"]
|
||||
):
|
||||
plugin_settings["cmd"].append(plugin_name)
|
||||
if plugins2settings_manager.get(
|
||||
matcher.plugin_name
|
||||
) and plugins2settings_manager[matcher.plugin_name].get(
|
||||
"plugin_type"
|
||||
):
|
||||
plugin_type = tuple(
|
||||
plugins2settings_manager.get_plugin_data(
|
||||
matcher.plugin_name
|
||||
)["plugin_type"]
|
||||
)
|
||||
else:
|
||||
try:
|
||||
plugin_type = _module.__getattribute__("__plugin_type__")
|
||||
except AttributeError:
|
||||
plugin_type = ("normal",)
|
||||
if plugin_settings and matcher.plugin_name:
|
||||
plugins2settings_manager.add_plugin_settings(
|
||||
matcher.plugin_name,
|
||||
plugin_type=plugin_type,
|
||||
**plugin_settings,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f'{matcher.plugin_name} 初始化 plugin_settings 发生错误 {type(e)}:{e}')
|
||||
_tmp.append(matcher.plugin_name)
|
||||
_tmp_data = {"PluginSettings": plugins2settings_manager.get_data()}
|
||||
with open(plugins2settings_file, "w", encoding="utf8") as wf:
|
||||
yaml.dump(_tmp_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
_data = round_trip_load(open(plugins2settings_file, encoding="utf8"))
|
||||
_data["PluginSettings"].yaml_set_start_comment(
|
||||
"""# 模块与对应命令和对应群权限
|
||||
# 用于生成帮助图片 和 开关功能
|
||||
# key:模块名称
|
||||
# level:需要的群等级
|
||||
# default_status:加入群时功能的默认开关状态
|
||||
# limit_superuser: 功能状态是否限制超级用户
|
||||
# cmd: 关闭[cmd] 都会触发命令 关闭对应功能,cmd列表第一个词为统计的功能名称
|
||||
# plugin_type: 帮助类别 示例:('原神相关',) 或 ('原神相关', 1),1代表帮助命令列向排列,否则为横向排列""",
|
||||
indent=2,
|
||||
)
|
||||
for plugin in _data["PluginSettings"].keys():
|
||||
_data["PluginSettings"][plugin].yaml_set_start_comment(
|
||||
f"{plugin}:{_tmp_module[plugin]}", indent=2
|
||||
)
|
||||
with open(plugins2settings_file, "w", encoding="utf8") as wf:
|
||||
round_trip_dump(_data, wf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
|
||||
plugins2settings_manager.save()
|
||||
logger.info(f"已成功加载 {len(plugins2settings_manager.get_data())} 个非限制插件.")
|
||||
|
||||
@@ -116,7 +116,8 @@ async def show_plugin_repo() -> Union[int, str]:
|
||||
if code != 200:
|
||||
return code
|
||||
plugin_info = json.load(open(plugin_json, "r", encoding="utf8"))
|
||||
load_plugin_list = plugins_manager.get_data().keys()
|
||||
plugins_data = plugins_manager.get_data()
|
||||
load_plugin_list = plugins_data.keys()
|
||||
image_list = []
|
||||
w, h = 0, 0
|
||||
line_height = 10
|
||||
@@ -134,7 +135,7 @@ async def show_plugin_repo() -> Union[int, str]:
|
||||
version = ""
|
||||
if key in load_plugin_list:
|
||||
status = "<f font_color=#1a7e30>[已安装]</f>"
|
||||
version = f"<f font_color=#1a7e30>[{plugins_manager.get_data()[key]['version']}]</f>"
|
||||
version = f"<f font_color=#1a7e30>[{plugins_data[key].version}]</f>"
|
||||
s = (
|
||||
f'id:{i+1}\n名称:{plugin_info[key]["plugin_name"]}'
|
||||
f' \t\t{status}\n'
|
||||
|
||||
@@ -15,7 +15,7 @@ from configs.path_config import TEXT_PATH
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from typing import List
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from utils.manager import GDict
|
||||
from utils.utils import GDict
|
||||
from utils.utils import scheduler
|
||||
import nonebot
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import nonebot
|
||||
from configs.config import Config
|
||||
from nonebot import Driver
|
||||
from utils.decorator.shop import shop_register
|
||||
import nonebot
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
@@ -12,3 +16,8 @@ Config.add_plugin_config(
|
||||
|
||||
|
||||
nonebot.load_plugins("basic_plugins/shop")
|
||||
|
||||
|
||||
@driver.on_bot_connect
|
||||
async def _():
|
||||
await shop_register.load_register()
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from nonebot import on_command
|
||||
|
||||
from models.user_shop_gold_log import UserShopGoldLog
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
|
||||
from nonebot.params import CommandArg
|
||||
@@ -46,10 +48,7 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
for x in await GoodsInfo.get_all_goods()
|
||||
if x.goods_limit_time > time.time() or x.goods_limit_time == 0
|
||||
]
|
||||
goods_name_list = [
|
||||
x.goods_name
|
||||
for x in goods_list
|
||||
]
|
||||
goods_name_list = [x.goods_name for x in goods_list]
|
||||
msg = arg.extract_plain_text().strip().split()
|
||||
num = 1
|
||||
if len(msg) > 1:
|
||||
@@ -77,11 +76,15 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
await BagUser.get_gold(event.user_id, event.group_id)
|
||||
) < goods.goods_price * num * goods.goods_discount:
|
||||
await buy.finish("您的金币好像不太够哦", at_sender=True)
|
||||
flag, n = await GoodsInfo.check_user_daily_purchase(goods, event.user_id, event.group_id, num)
|
||||
flag, n = await GoodsInfo.check_user_daily_purchase(
|
||||
goods, event.user_id, event.group_id, num
|
||||
)
|
||||
if flag:
|
||||
await buy.finish(f"该次购买将超过每日次数限制,目前该道具还可以购买{n}次哦", at_sender=True)
|
||||
if await BagUser.buy_property(event.user_id, event.group_id, goods, num):
|
||||
await GoodsInfo.add_user_daily_purchase(goods, event.user_id, event.group_id, num)
|
||||
await GoodsInfo.add_user_daily_purchase(
|
||||
goods, event.user_id, event.group_id, num
|
||||
)
|
||||
await buy.send(
|
||||
f"花费 {goods.goods_price * num * goods.goods_discount} 金币购买 {goods.goods_name} ×{num} 成功!",
|
||||
at_sender=True,
|
||||
@@ -90,6 +93,14 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
f"USER {event.user_id} GROUP {event.group_id} "
|
||||
f"花费 {goods.goods_price*num} 金币购买 {goods.goods_name} ×{num} 成功!"
|
||||
)
|
||||
await UserShopGoldLog.add_shop_log(
|
||||
event.user_id,
|
||||
event.group_id,
|
||||
0,
|
||||
goods.goods_name,
|
||||
num,
|
||||
goods.goods_price * num * goods.goods_discount,
|
||||
)
|
||||
else:
|
||||
await buy.send(f"{goods.goods_name} 购买失败!", at_sender=True)
|
||||
logger.info(
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
from nonebot import on_command
|
||||
|
||||
from utils.message_builder import image
|
||||
from ._data_source import create_bag_image
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from models.bag_user import BagUser
|
||||
@@ -32,10 +35,11 @@ my_props = on_command("我的道具", priority=5, block=True, permission=GROUP)
|
||||
async def _(event: GroupMessageEvent):
|
||||
props = await BagUser.get_property(event.user_id, event.group_id)
|
||||
if props:
|
||||
rst = ""
|
||||
for i, p in enumerate(props.keys()):
|
||||
rst += f"{i+1}.{p}\t×{props[p]}\n"
|
||||
await my_props.send("\n" + rst[:-1], at_sender=True)
|
||||
await my_props.send(image(b64=await create_bag_image(props)))
|
||||
# rst = ""
|
||||
# for i, p in enumerate(props.keys()):
|
||||
# rst += f"{i+1}.{p}\t×{props[p]}\n"
|
||||
# await my_props.send("\n" + rst[:-1], at_sender=True)
|
||||
logger.info(f"USER {event.user_id} GROUP {event.group_id} 查看我的道具")
|
||||
else:
|
||||
await my_props.finish("您的背包里没有任何的道具噢~", at_sender=True)
|
||||
@@ -0,0 +1,121 @@
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from models.bag_user import BagUser
|
||||
from models.goods_info import GoodsInfo
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
|
||||
|
||||
icon_path = IMAGE_PATH / "shop_icon"
|
||||
|
||||
|
||||
async def create_bag_image(props: Dict[str, int]):
|
||||
"""
|
||||
说明:
|
||||
创建背包道具图片
|
||||
参数:
|
||||
:param props: 道具仓库字典
|
||||
"""
|
||||
goods_list = await GoodsInfo.get_all_goods()
|
||||
active_props = await _init_prop(props, [x for x in goods_list if not x.is_passive])
|
||||
passive_props = await _init_prop(props, [x for x in goods_list if x.is_passive])
|
||||
active_w = 0
|
||||
active_h = 0
|
||||
passive_w = 0
|
||||
passive_h = 0
|
||||
if active_props:
|
||||
img = BuildImage(
|
||||
active_props.w,
|
||||
active_props.h + 70,
|
||||
font="CJGaoDeGuo.otf",
|
||||
font_size=30,
|
||||
color="#f9f6f2",
|
||||
)
|
||||
await img.apaste(active_props, (0, 70))
|
||||
await img.atext((0, 30), "主动道具")
|
||||
active_props = img
|
||||
active_w = img.w
|
||||
active_h = img.h
|
||||
if passive_props:
|
||||
img = BuildImage(
|
||||
passive_props.w,
|
||||
passive_props.h + 70,
|
||||
font="CJGaoDeGuo.otf",
|
||||
font_size=30,
|
||||
color="#f9f6f2",
|
||||
)
|
||||
await img.apaste(passive_props, (0, 70))
|
||||
await img.atext((0, 30), "被动道具")
|
||||
passive_props = img
|
||||
passive_w = img.w
|
||||
passive_h = img.h
|
||||
A = BuildImage(
|
||||
active_w + passive_w + 100,
|
||||
max(active_h, passive_h) + 60,
|
||||
font="CJGaoDeGuo.otf",
|
||||
font_size=30,
|
||||
color="#f9f6f2",
|
||||
)
|
||||
curr_w = 50
|
||||
if active_props:
|
||||
await A.apaste(active_props, (curr_w, 0))
|
||||
curr_w += active_props.w + 10
|
||||
if passive_props:
|
||||
await A.apaste(passive_props, (curr_w, 0))
|
||||
if active_props and passive_props:
|
||||
await A.aline(
|
||||
(active_props.w + 45, 70, active_props.w + 45, A.h - 20), fill=(0, 0, 0)
|
||||
)
|
||||
return A.pic2bs4()
|
||||
|
||||
|
||||
async def _init_prop(
|
||||
props: Dict[str, int], _props: List[GoodsInfo]
|
||||
) -> Optional[BuildImage]:
|
||||
"""
|
||||
说明:
|
||||
构造道具列表图片
|
||||
参数:
|
||||
:param props: 道具仓库字典
|
||||
:param _props: 道具列表
|
||||
"""
|
||||
active_name = [x.goods_name for x in _props]
|
||||
name_list = [x for x in props.keys() if x in active_name]
|
||||
if not name_list:
|
||||
return None
|
||||
temp_img = BuildImage(0, 0, font_size=20)
|
||||
image_list = []
|
||||
num_list = []
|
||||
for i, name in enumerate(name_list):
|
||||
img = BuildImage(
|
||||
temp_img.getsize(name)[0] + 50,
|
||||
30,
|
||||
font="msyh.ttf",
|
||||
font_size=20,
|
||||
color="#f9f6f2",
|
||||
)
|
||||
await img.atext((30, 5), f"{i + 1}.{name}")
|
||||
goods = [x for x in _props if x.goods_name == name][0]
|
||||
if goods.icon and (icon_path / goods.icon).exists():
|
||||
icon = BuildImage(30, 30, background=icon_path / goods.icon)
|
||||
await img.apaste(icon, alpha=True)
|
||||
image_list.append(img)
|
||||
num_list.append(
|
||||
BuildImage(
|
||||
30, 30, font_size=20, font="msyh.ttf", plain_text=f"×{props[name]}"
|
||||
)
|
||||
)
|
||||
max_w = 0
|
||||
num_max_w = 0
|
||||
h = 0
|
||||
for img, num in zip(image_list, num_list):
|
||||
h += img.h
|
||||
max_w = max_w if max_w > img.w else img.w
|
||||
num_max_w = num_max_w if num_max_w > num.w else num.w
|
||||
A = BuildImage(max_w + num_max_w + 30, h, color="#f9f6f2")
|
||||
curr_h = 0
|
||||
for img, num in zip(image_list, num_list):
|
||||
await A.apaste(img, (0, curr_h))
|
||||
await A.apaste(num, (max_w + 20, curr_h + 5), True)
|
||||
curr_h += img.h
|
||||
return A
|
||||
@@ -6,7 +6,6 @@ from utils.message_builder import image
|
||||
from nonebot.permission import SUPERUSER
|
||||
from utils.utils import is_number, scheduler
|
||||
from nonebot.params import CommandArg
|
||||
from nonebot.plugin import export
|
||||
from services.log import logger
|
||||
import os
|
||||
|
||||
@@ -51,11 +50,6 @@ __plugin_block_limit__ = {
|
||||
"limit_type": "group"
|
||||
}
|
||||
|
||||
# 导出方法供其他插件使用
|
||||
export = export()
|
||||
export.register_goods = register_goods
|
||||
export.delete_goods = delete_goods
|
||||
export.update_goods = update_goods
|
||||
|
||||
shop_help = on_command("商店", priority=5, block=True)
|
||||
|
||||
|
||||
@@ -1,50 +1,18 @@
|
||||
from PIL import Image
|
||||
|
||||
from models.goods_info import GoodsInfo
|
||||
from utils.image_utils import BuildImage
|
||||
from models.sign_group_user import SignGroupUser
|
||||
from utils.image_utils import BuildImage, text2image
|
||||
from utils.utils import is_number
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from typing import Optional, Union, Tuple
|
||||
from configs.config import Config
|
||||
from nonebot import Driver
|
||||
from nonebot.plugin import require
|
||||
from utils.decorator.shop import shop_register
|
||||
import nonebot
|
||||
from utils.utils import GDict
|
||||
import time
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
icon_path = IMAGE_PATH / 'shop_icon'
|
||||
|
||||
|
||||
use = require("use")
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def init_default_shop_goods():
|
||||
"""
|
||||
导入内置的三个商品
|
||||
"""
|
||||
|
||||
@shop_register(
|
||||
name=("好感度双倍加持卡Ⅰ", "好感度双倍加持卡Ⅱ", "好感度双倍加持卡Ⅲ"),
|
||||
price=(30, 150, 250),
|
||||
des=(
|
||||
"下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)",
|
||||
"下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)",
|
||||
"下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)",
|
||||
),
|
||||
load_status=Config.get_config("shop", "IMPORT_DEFAULT_SHOP_GOODS"),
|
||||
daily_limit=(10, 20, 30),
|
||||
** {"好感度双倍加持卡Ⅰ_prob": 0.1, "好感度双倍加持卡Ⅱ_prob": 0.2, "好感度双倍加持卡Ⅲ_prob": 0.3},
|
||||
)
|
||||
async def sign_card(user_id: int, group_id: int, prob: float):
|
||||
user = await SignGroupUser.ensure(user_id, group_id)
|
||||
await user.update(add_probability=prob).apply()
|
||||
|
||||
|
||||
@driver.on_bot_connect
|
||||
async def _():
|
||||
await shop_register.load_register()
|
||||
GDict['run_sql'].append("ALTER TABLE goods_info ADD is_passive boolean DEFAULT False;")
|
||||
GDict['run_sql'].append("ALTER TABLE goods_info ADD icon VARCHAR(255);")
|
||||
|
||||
|
||||
# 创建商店界面
|
||||
@@ -54,28 +22,22 @@ async def create_shop_help() -> str:
|
||||
:return: 图片base64
|
||||
"""
|
||||
goods_lst = await GoodsInfo.get_all_goods()
|
||||
idx = 1
|
||||
_dc = {}
|
||||
font_h = BuildImage(0, 0).getsize("正")[1]
|
||||
h = 10
|
||||
_list = []
|
||||
for goods in goods_lst:
|
||||
if goods.goods_limit_time == 0 or time.time() < goods.goods_limit_time:
|
||||
h += len(goods.goods_description.strip().split("\n")) * font_h + 80
|
||||
_list.append(goods)
|
||||
A = BuildImage(1000, h, color="#f9f6f2")
|
||||
current_h = 0
|
||||
# A = BuildImage(1100, h, color="#f9f6f2")
|
||||
total_n = 0
|
||||
for goods in _list:
|
||||
bk = BuildImage(1180, 80, font_size=15, color="#f9f6f2", font="CJGaoDeGuo.otf")
|
||||
goods_image = BuildImage(
|
||||
600, 80, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
|
||||
)
|
||||
image_list = []
|
||||
for idx, goods in enumerate(_list):
|
||||
name_image = BuildImage(
|
||||
580, 40, font_size=25, color="#e67b6b", font="CJGaoDeGuo.otf"
|
||||
)
|
||||
await name_image.atext(
|
||||
(15, 0), f"{idx}.{goods.goods_name}", center_type="by_height"
|
||||
(15, 0), f"{idx + 1}.{goods.goods_name}", center_type="by_height"
|
||||
)
|
||||
await name_image.aline((380, -5, 280, 45), "#a29ad6", 5)
|
||||
await name_image.atext((390, 0), "售价:", center_type="by_height")
|
||||
@@ -102,13 +64,48 @@ async def create_shop_help() -> str:
|
||||
f" 金币",
|
||||
center_type="by_height",
|
||||
)
|
||||
des_image = None
|
||||
font_img = BuildImage(
|
||||
600, 80, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
|
||||
)
|
||||
p = font_img.getsize('简介:')[0] + 20
|
||||
if goods.goods_description:
|
||||
des_list = goods.goods_description.split('\n')
|
||||
desc = ''
|
||||
for des in des_list:
|
||||
if font_img.getsize(des)[0] > font_img.w - p - 20:
|
||||
msg = ''
|
||||
tmp = ''
|
||||
for i in range(len(des)):
|
||||
if font_img.getsize(tmp)[0] < font_img.w - p - 20:
|
||||
tmp += des[i]
|
||||
else:
|
||||
msg += tmp + '\n'
|
||||
tmp = des[i]
|
||||
desc += msg
|
||||
if tmp:
|
||||
desc += tmp
|
||||
else:
|
||||
desc += des + '\n'
|
||||
if desc[-1] == '\n':
|
||||
desc = desc[:-1]
|
||||
des_image = await text2image(desc, color="#a29ad6")
|
||||
goods_image = BuildImage(
|
||||
600, (50 + des_image.h) if des_image else 50, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
|
||||
)
|
||||
if des_image:
|
||||
await goods_image.atext((15, 50), '简介:')
|
||||
await goods_image.apaste(des_image, (p, 50))
|
||||
await name_image.acircle_corner(5)
|
||||
await goods_image.apaste(name_image, (0, 5), True, center_type="by_width")
|
||||
await goods_image.atext((15, 50), f"简介:{goods.goods_description}")
|
||||
await goods_image.acircle_corner(20)
|
||||
await bk.apaste(goods_image, alpha=True)
|
||||
bk = BuildImage(1180, (50 + des_image.h) if des_image else 50, font_size=15, color="#f9f6f2", font="CJGaoDeGuo.otf")
|
||||
if goods.icon and (icon_path / goods.icon).exists():
|
||||
icon = BuildImage(70, 70, background=icon_path / goods.icon)
|
||||
await bk.apaste(icon)
|
||||
await bk.apaste(goods_image, (70, 0), alpha=True)
|
||||
n = 0
|
||||
_w = 550
|
||||
_w = 650
|
||||
# 添加限时图标和时间
|
||||
if goods.goods_limit_time > 0:
|
||||
n += 140
|
||||
@@ -162,14 +159,22 @@ async def create_shop_help() -> str:
|
||||
if total_n < n:
|
||||
total_n = n
|
||||
if n:
|
||||
await bk.aline((550, -1, 550 + n, -1), "#a29ad6", 5)
|
||||
await bk.aline((550, 80, 550 + n, 80), "#a29ad6", 5)
|
||||
await bk.aline((650, -1, 650 + n, -1), "#a29ad6", 5)
|
||||
# await bk.aline((650, 80, 650 + n, 80), "#a29ad6", 5)
|
||||
|
||||
# 添加限时图标和时间
|
||||
idx += 1
|
||||
await A.apaste(bk, (0, current_h), True)
|
||||
current_h += 90
|
||||
w = 850
|
||||
image_list.append(bk)
|
||||
# await A.apaste(bk, (0, current_h), True)
|
||||
# current_h += 90
|
||||
h = 0
|
||||
current_h = 0
|
||||
for img in image_list:
|
||||
h += img.h + 10
|
||||
A = BuildImage(1100, h, color="#f9f6f2")
|
||||
for img in image_list:
|
||||
await A.apaste(img, (0, current_h), True)
|
||||
current_h += img.h + 10
|
||||
w = 950
|
||||
if total_n:
|
||||
w += total_n
|
||||
h = A.h + 230 + 100
|
||||
@@ -197,6 +202,8 @@ async def register_goods(
|
||||
discount: Optional[float] = 1,
|
||||
limit_time: Optional[int] = 0,
|
||||
daily_limit: Optional[int] = 0,
|
||||
is_passive: Optional[bool] = False,
|
||||
icon: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
添加商品
|
||||
@@ -209,6 +216,8 @@ async def register_goods(
|
||||
:param discount: 商品折扣
|
||||
:param limit_time: 商品限时销售时间,单位为小时
|
||||
:param daily_limit: 每日购买次数限制
|
||||
:param is_passive: 是否为被动
|
||||
:param icon: 图标
|
||||
:return: 是否添加成功
|
||||
"""
|
||||
if not await GoodsInfo.get_goods_info(name):
|
||||
@@ -220,7 +229,7 @@ async def register_goods(
|
||||
else 0
|
||||
)
|
||||
return await GoodsInfo.add_goods(
|
||||
name, int(price), des, float(discount), limit_time, daily_limit
|
||||
name, int(price), des, float(discount), limit_time, daily_limit, is_passive, icon
|
||||
)
|
||||
return False
|
||||
|
||||
@@ -272,6 +281,7 @@ async def update_goods(**kwargs) -> Tuple[bool, str, str]:
|
||||
discount = goods.goods_discount
|
||||
limit_time = goods.goods_limit_time
|
||||
daily_limit = goods.daily_limit
|
||||
is_passive = goods.is_passive
|
||||
new_time = 0
|
||||
tmp = ""
|
||||
if kwargs.get("price"):
|
||||
@@ -294,6 +304,9 @@ async def update_goods(**kwargs) -> Tuple[bool, str, str]:
|
||||
if kwargs.get("daily_limit"):
|
||||
tmp += f'每日购买限制:{daily_limit} --> {kwargs["daily_limit"]}\n' if daily_limit else "取消了购买限制\n"
|
||||
daily_limit = int(kwargs["daily_limit"])
|
||||
if kwargs.get("is_passive"):
|
||||
tmp += f'被动道具:{is_passive} --> {kwargs["is_passive"]}\n'
|
||||
des = kwargs["is_passive"]
|
||||
await GoodsInfo.update_goods(
|
||||
name,
|
||||
int(price),
|
||||
@@ -304,7 +317,8 @@ async def update_goods(**kwargs) -> Tuple[bool, str, str]:
|
||||
if limit_time != 0 and new_time
|
||||
else 0
|
||||
),
|
||||
daily_limit
|
||||
daily_limit,
|
||||
is_passive
|
||||
)
|
||||
return True, name, tmp[:-1],
|
||||
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
from nonebot import on_command
|
||||
from typing import Any, Tuple
|
||||
|
||||
from nonebot import on_command, on_regex
|
||||
|
||||
from models.user_shop_gold_log import UserShopGoldLog
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message
|
||||
from nonebot.params import CommandArg
|
||||
from nonebot.params import CommandArg, RegexGroup
|
||||
|
||||
from utils.decorator.shop import NotMeetUseConditionsException
|
||||
from utils.utils import is_number
|
||||
from models.bag_user import BagUser
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from services.db_context import db
|
||||
from nonebot.plugin import export
|
||||
from .data_source import effect, register_use, func_manager
|
||||
from .data_source import effect, register_use, func_manager, build_params
|
||||
|
||||
|
||||
__zx_plugin_name__ = "商店 - 使用道具"
|
||||
@@ -15,12 +20,16 @@ __plugin_usage__ = """
|
||||
usage:
|
||||
普通的使用道具
|
||||
指令:
|
||||
使用道具 [序号或道具名称] ?[数量]=1
|
||||
使用道具 [序号或道具名称] ?[数量]=1 ?[其他信息]
|
||||
示例:使用道具好感度双倍加持卡 使用道具好感度双倍加持卡
|
||||
示例:使用道具1 使用第一个道具
|
||||
示例:使用道具1 10 使用10个第一个道具
|
||||
示例:使用道具1 1 来点色图 使用第一个道具并附带信息
|
||||
* 序号以 ”我的道具“ 为准 *
|
||||
""".strip()
|
||||
__plugin_des__ = "商店 - 使用道具"
|
||||
__plugin_cmd__ = ["使用道具 [序号或道具名称]"]
|
||||
__plugin_type__ = ('商店',)
|
||||
__plugin_type__ = ("商店",)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
@@ -30,52 +39,69 @@ __plugin_settings__ = {
|
||||
"cmd": ["商店", "使用道具"],
|
||||
}
|
||||
|
||||
# 导出方法供其他插件使用
|
||||
export = export()
|
||||
export.register_use = register_use
|
||||
|
||||
use_props = on_command("使用道具", priority=5, block=True, permission=GROUP)
|
||||
use_props = on_command(r"使用道具", priority=5, block=True, permission=GROUP)
|
||||
|
||||
|
||||
@use_props.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
msg = arg.extract_plain_text()
|
||||
num = 1
|
||||
msg_sp = msg.split()
|
||||
if len(msg_sp) > 1 and is_number(msg_sp[-1]) and int(msg_sp[-1]) > 0:
|
||||
num = int(msg.split()[-1])
|
||||
msg = " ".join(msg.split()[:-1])
|
||||
property_ = await BagUser.get_property(event.user_id, event.group_id)
|
||||
text = ""
|
||||
prop_n = None
|
||||
index = None
|
||||
split = msg.split()
|
||||
if size := len(split):
|
||||
if size == 1:
|
||||
prop_n = split[0].strip()
|
||||
index = 1
|
||||
if size > 1 and is_number(split[1].strip()):
|
||||
prop_n = split[0].strip()
|
||||
num = int(split[1].strip())
|
||||
index = 2
|
||||
else:
|
||||
await use_props.finish("缺少参数,请查看帮助", at_sender=True)
|
||||
if index:
|
||||
text = " ".join(split[index:])
|
||||
property_ = await BagUser.get_property(event.user_id, event.group_id, True)
|
||||
if property_:
|
||||
async with db.transaction():
|
||||
if is_number(msg):
|
||||
if 0 < int(msg) <= len(property_):
|
||||
name = list(property_.keys())[int(msg) - 1]
|
||||
else:
|
||||
await use_props.finish("仔细看看自己的道具仓库有没有这个道具?", at_sender=True)
|
||||
name = None
|
||||
if prop_n and is_number(prop_n):
|
||||
if 0 < int(prop_n) <= len(property_):
|
||||
name = list(property_.keys())[int(prop_n) - 1]
|
||||
else:
|
||||
if msg not in property_.keys():
|
||||
await use_props.finish("道具名称错误!", at_sender=True)
|
||||
name = msg
|
||||
_user_prop_count = property_[name]
|
||||
if num > _user_prop_count:
|
||||
await use_props.finish(f"道具数量不足,无法使用{num}次!")
|
||||
if num > (n := func_manager.get_max_num_limit(name)):
|
||||
await use_props.finish(f"该道具单次只能使用 {n} 个!")
|
||||
if await BagUser.delete_property(
|
||||
event.user_id, event.group_id, name, num
|
||||
):
|
||||
await use_props.finish("仔细看看自己的道具仓库有没有这个道具?", at_sender=True)
|
||||
else:
|
||||
if prop_n not in property_.keys():
|
||||
await use_props.finish("道具名称错误!", at_sender=True)
|
||||
name = prop_n
|
||||
_user_prop_count = property_[name]
|
||||
if num > _user_prop_count:
|
||||
await use_props.finish(f"道具数量不足,无法使用{num}次!")
|
||||
if num > (n := func_manager.get_max_num_limit(name)):
|
||||
await use_props.finish(f"该道具单次只能使用 {n} 个!")
|
||||
model, kwargs = build_params(bot, event, name, num, text)
|
||||
try:
|
||||
await func_manager.run_handle(type_="before_handle", param=model, **kwargs)
|
||||
except NotMeetUseConditionsException as e:
|
||||
await use_props.finish(e.get_info(), at_sender=True)
|
||||
async with db.transaction():
|
||||
if await BagUser.delete_property(event.user_id, event.group_id, name, num):
|
||||
if func_manager.check_send_success_message(name):
|
||||
await use_props.send(f"使用道具 {name} {num} 次成功!", at_sender=True)
|
||||
if msg := await effect(bot, event, name, num):
|
||||
if msg := await effect(bot, event, name, num, text, event.message):
|
||||
await use_props.send(msg, at_sender=True)
|
||||
logger.info(
|
||||
f"USER {event.user_id} GROUP {event.group_id} 使用道具 {name} {num} 次成功"
|
||||
)
|
||||
await UserShopGoldLog.add_shop_log(
|
||||
event.user_id, event.group_id, 1, name, num
|
||||
)
|
||||
else:
|
||||
await use_props.send(f"使用道具 {name} {num} 次失败!", at_sender=True)
|
||||
logger.info(
|
||||
f"USER {event.user_id} GROUP {event.group_id} 使用道具 {name} {num} 次失败"
|
||||
)
|
||||
await func_manager.run_handle(type_="after_handle", param=model, **kwargs)
|
||||
else:
|
||||
await use_props.send("您的背包里没有任何的道具噢", at_sender=True)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment, Message
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from pydantic import create_model
|
||||
from utils.models import ShopParam
|
||||
from typing import Optional, Union
|
||||
from typing import Optional, Union, Callable, List, Tuple, Dict, Any
|
||||
from types import MappingProxyType
|
||||
import inspect
|
||||
import asyncio
|
||||
@@ -13,6 +13,30 @@ class GoodsUseFuncManager:
|
||||
def __init__(self):
|
||||
self._data = {}
|
||||
|
||||
def register_use_before_handle(self, goods_name: str, fun_list: List[Callable]):
|
||||
"""
|
||||
说明:
|
||||
注册商品使用前函数
|
||||
参数:
|
||||
:param goods_name: 商品名称
|
||||
:param fun_list: 函数列表
|
||||
"""
|
||||
if fun_list:
|
||||
self._data[goods_name]["before_handle"] = fun_list
|
||||
logger.info(f"register_use_before_handle 成功注册商品:{goods_name} 的{len(fun_list)}个使用前函数")
|
||||
|
||||
def register_use_after_handle(self, goods_name: str, fun_list: List[Callable]):
|
||||
"""
|
||||
说明:
|
||||
注册商品使用后函数
|
||||
参数:
|
||||
:param goods_name: 商品名称
|
||||
:param fun_list: 函数列表
|
||||
"""
|
||||
if fun_list:
|
||||
self._data[goods_name]["after_handle"] = fun_list
|
||||
logger.info(f"register_use_after_handle 成功注册商品:{goods_name} 的{len(fun_list)}个使用后函数")
|
||||
|
||||
def register_use(self, goods_name: str, **kwargs):
|
||||
"""
|
||||
注册商品使用方法
|
||||
@@ -26,7 +50,7 @@ class GoodsUseFuncManager:
|
||||
判断商品使用方法是否被注册
|
||||
:param goods_name: 商品名称
|
||||
"""
|
||||
return bool(self ._data.get(goods_name))
|
||||
return bool(self._data.get(goods_name))
|
||||
|
||||
def get_max_num_limit(self, goods_name: str) -> int:
|
||||
"""
|
||||
@@ -37,6 +61,21 @@ class GoodsUseFuncManager:
|
||||
return self._data[goods_name]["kwargs"]["max_num_limit"]
|
||||
return 1
|
||||
|
||||
def _parse_args(self, args_: MappingProxyType, param: ShopParam, **kwargs):
|
||||
param_list_ = []
|
||||
_bot = param.bot
|
||||
param.bot = None
|
||||
param_json = param.dict()
|
||||
param_json["bot"] = _bot
|
||||
for par in args_.keys():
|
||||
if par in ["shop_param"]:
|
||||
param_list_.append(param)
|
||||
elif par not in ["args", "kwargs"]:
|
||||
param_list_.append(param_json.get(par))
|
||||
if kwargs.get(par) is not None:
|
||||
del kwargs[par]
|
||||
return param_list_
|
||||
|
||||
async def use(
|
||||
self, param: ShopParam, **kwargs
|
||||
) -> Optional[Union[str, MessageSegment]]:
|
||||
@@ -45,31 +84,18 @@ class GoodsUseFuncManager:
|
||||
:param param: BaseModel
|
||||
:param kwargs: kwargs
|
||||
"""
|
||||
def parse_args(args_: MappingProxyType):
|
||||
param_list_ = []
|
||||
_bot = param.bot
|
||||
param.bot = None
|
||||
param_json = param.dict()
|
||||
param_json["bot"] = _bot
|
||||
for par in args_.keys():
|
||||
if par in ["shop_param"]:
|
||||
param_list_.append(param)
|
||||
elif par not in ["args", "kwargs"]:
|
||||
param_list_.append(param_json.get(par))
|
||||
if kwargs.get(par) is not None:
|
||||
del kwargs[par]
|
||||
return param_list_
|
||||
goods_name = param.goods_name
|
||||
if self.exists(goods_name):
|
||||
# 使用方法
|
||||
args = inspect.signature(self._data[goods_name]["func"]).parameters
|
||||
if args and list(args.keys())[0] != "kwargs":
|
||||
if asyncio.iscoroutinefunction(self._data[goods_name]["func"]):
|
||||
return await self._data[goods_name]["func"](
|
||||
*parse_args(args)
|
||||
*self._parse_args(args, param, **kwargs)
|
||||
)
|
||||
else:
|
||||
return self._data[goods_name]["func"](
|
||||
*parse_args(args)
|
||||
*self._parse_args(args, param, **kwargs)
|
||||
)
|
||||
else:
|
||||
if asyncio.iscoroutinefunction(self._data[goods_name]["func"]):
|
||||
@@ -81,6 +107,21 @@ class GoodsUseFuncManager:
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
async def run_handle(self, goods_name: str, type_: str, param: ShopParam, **kwargs):
|
||||
if self._data[goods_name].get(type_):
|
||||
for func in self._data[goods_name].get(type_):
|
||||
args = inspect.signature(func).parameters
|
||||
if args and list(args.keys())[0] != "kwargs":
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
await func(*self._parse_args(args, param, **kwargs))
|
||||
else:
|
||||
func(*self._parse_args(args, param, **kwargs))
|
||||
else:
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
await func(**kwargs)
|
||||
else:
|
||||
func(**kwargs)
|
||||
|
||||
def check_send_success_message(self, goods_name: str) -> bool:
|
||||
"""
|
||||
检查是否发送使用成功信息
|
||||
@@ -99,7 +140,7 @@ class GoodsUseFuncManager:
|
||||
return self._data[goods_name]["kwargs"]
|
||||
return {}
|
||||
|
||||
def init_model(self, goods_name: str, bot: Bot, event: GroupMessageEvent, num: int):
|
||||
def init_model(self, goods_name: str, bot: Bot, event: GroupMessageEvent, num: int, text: str):
|
||||
return self._data[goods_name]["model"](
|
||||
**{
|
||||
"goods_name": goods_name,
|
||||
@@ -108,6 +149,8 @@ class GoodsUseFuncManager:
|
||||
"user_id": event.user_id,
|
||||
"group_id": event.group_id,
|
||||
"num": num,
|
||||
"message": event.message,
|
||||
"text": text
|
||||
}
|
||||
)
|
||||
|
||||
@@ -115,8 +158,39 @@ class GoodsUseFuncManager:
|
||||
func_manager = GoodsUseFuncManager()
|
||||
|
||||
|
||||
def build_params(
|
||||
bot: Bot, event: GroupMessageEvent, goods_name: str, num: int, text: str
|
||||
) -> Tuple[ShopParam, Dict[str, Any]]:
|
||||
"""
|
||||
说明:
|
||||
构造参数
|
||||
参数:
|
||||
:param bot: bot
|
||||
:param event: event
|
||||
:param goods_name: 商品名称
|
||||
:param num: 数量
|
||||
:param text: 其他信息
|
||||
:return:
|
||||
"""
|
||||
_kwargs = func_manager.get_kwargs(goods_name)
|
||||
return (
|
||||
func_manager.init_model(goods_name, bot, event, num, text),
|
||||
{
|
||||
**_kwargs,
|
||||
"_bot": bot,
|
||||
"event": event,
|
||||
"group_id": event.group_id,
|
||||
"user_id": event.user_id,
|
||||
"num": num,
|
||||
"text": text,
|
||||
"message": event.message,
|
||||
"goods_name": goods_name,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def effect(
|
||||
bot: Bot, event: GroupMessageEvent, goods_name: str, num: int
|
||||
bot: Bot, event: GroupMessageEvent, goods_name: str, num: int, text: str, message: Message
|
||||
) -> Optional[Union[str, MessageSegment]]:
|
||||
"""
|
||||
商品生效
|
||||
@@ -124,30 +198,22 @@ async def effect(
|
||||
:param event: GroupMessageEvent
|
||||
:param goods_name: 商品名称
|
||||
:param num: 使用数量
|
||||
:param text: 其他信息
|
||||
:param message: Message
|
||||
:return: 使用是否成功
|
||||
"""
|
||||
# 优先使用注册的商品插件
|
||||
# try:
|
||||
if func_manager.exists(goods_name):
|
||||
_kwargs = func_manager.get_kwargs(goods_name)
|
||||
return await func_manager.use(
|
||||
func_manager.init_model(goods_name, bot, event, num),
|
||||
**{
|
||||
**_kwargs,
|
||||
"_bot": bot,
|
||||
"event": event,
|
||||
"group_id": event.group_id,
|
||||
"user_id": event.user_id,
|
||||
"num": num,
|
||||
"goods_name": goods_name,
|
||||
},
|
||||
)
|
||||
model, kwargs = build_params(bot, event, goods_name, num, text)
|
||||
return await func_manager.use(model, **kwargs)
|
||||
# except Exception as e:
|
||||
# logger.error(f"use 商品生效函数effect 发生错误 {type(e)}:{e}")
|
||||
return None
|
||||
|
||||
|
||||
def register_use(goods_name: str, func, **kwargs):
|
||||
def register_use(goods_name: str, func: Callable, **kwargs):
|
||||
"""
|
||||
注册商品使用方法
|
||||
:param goods_name: 商品名称
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import nonebot
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
nonebot.load_plugins('basic_plugins/super_cmd')
|
||||
nonebot.load_plugins(str(Path(__file__).parent.resolve()))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,37 +1,86 @@
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from nonebot.adapters.onebot.v11 import Message, Bot, MessageEvent
|
||||
from nonebot import on_command
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.rule import to_me
|
||||
from utils.message_builder import custom_forward_msg
|
||||
from services.db_context import db
|
||||
from nonebot.params import CommandArg
|
||||
from services.log import logger
|
||||
|
||||
import asyncio
|
||||
|
||||
__zx_plugin_name__ = "执行sql [Superuser]"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
执行一段sql语句
|
||||
指令:
|
||||
exec [sql语句]
|
||||
exec [sql语句] ([查询页数,19条/页])
|
||||
查看所有表
|
||||
""".strip()
|
||||
__plugin_des__ = "执行一段sql语句"
|
||||
__plugin_cmd__ = [
|
||||
"exec [sql语句]",
|
||||
]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_version__ = 0.2
|
||||
__plugin_author__ = "HibiKier"
|
||||
|
||||
|
||||
exec_ = on_command("exec", rule=to_me(), permission=SUPERUSER, priority=1, block=True)
|
||||
tables = on_command("查看所有表", rule=to_me(), permission=SUPERUSER, priority=1, block=True)
|
||||
|
||||
|
||||
@exec_.handle()
|
||||
async def _(arg: Message = CommandArg()):
|
||||
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
sql = arg.extract_plain_text().strip()
|
||||
async with db.transaction():
|
||||
try:
|
||||
# 判断是否为SELECT语句
|
||||
if sql.lower().startswith("select"):
|
||||
# 分割语句
|
||||
try:
|
||||
page = int(sql.split(" ")[-1]) - 1
|
||||
sql_list = sql.split(" ")[:-1]
|
||||
except ValueError:
|
||||
page = 0
|
||||
sql_list = sql.split(" ")
|
||||
# 拼接语句
|
||||
sql = " ".join(sql_list)
|
||||
query = db.text(sql)
|
||||
res = await db.all(query)
|
||||
msg_list = [f"第{page+1}页查询结果:"]
|
||||
# logger.info(res)
|
||||
# 获取所有字段
|
||||
keys = res[0].keys()
|
||||
# 每页10条
|
||||
for i in res[page * 10 : (page + 1) * 10]:
|
||||
msg = ""
|
||||
for key in keys:
|
||||
msg += f"{key}: {i[key]}\n"
|
||||
msg += f"第{page+1}页第{res.index(i)+1}条"
|
||||
msg_list.append(msg)
|
||||
# 检查是私聊还是群聊
|
||||
try:
|
||||
forward_msg_list = custom_forward_msg(msg_list, bot.self_id)
|
||||
await bot.send_group_forward_msg(group_id=event.group_id, messages=forward_msg_list)
|
||||
except:
|
||||
for msg in msg_list:
|
||||
await exec_.send(msg)
|
||||
await asyncio.sleep(0.2)
|
||||
return
|
||||
query = db.text(sql)
|
||||
await db.first(query)
|
||||
await exec_.send("执行 sql 语句成功.")
|
||||
except Exception as e:
|
||||
await exec_.send(f"执行 sql 语句失败 {type(e)}:{e}")
|
||||
logger.error(f"执行 sql 语句失败 {type(e)}:{e}")
|
||||
|
||||
|
||||
@tables.handle()
|
||||
async def _(bot: Bot, event: MessageEvent):
|
||||
# 获取所有表
|
||||
query = db.text("select tablename from pg_tables where schemaname = 'public'")
|
||||
res = await db.all(query)
|
||||
msg = "数据库中的所有表名:\n"
|
||||
for tablename in res:
|
||||
msg += str(tablename["tablename"]) + "\n"
|
||||
await tables.finish(msg)
|
||||
|
||||
@@ -122,8 +122,8 @@ async def _(event: GroupMessageEvent):
|
||||
tmp = ""
|
||||
data = plugins2settings_manager.get_data()
|
||||
for module in data:
|
||||
if data[module]["level"] > level:
|
||||
plugin_name = data[module]["cmd"][0]
|
||||
if data[module].level > level:
|
||||
plugin_name = data[module].cmd[0]
|
||||
if plugin_name == "pixiv":
|
||||
plugin_name = "搜图 p站排行"
|
||||
tmp += f"{plugin_name}\n"
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.rule import to_me
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.message_builder import image
|
||||
from .data_source import create_help_image
|
||||
from .data_source import create_help_image, SUPERUSER_HELP_IMAGE
|
||||
|
||||
|
||||
__zx_plugin_name__ = '超级用户帮助 [Superuser]'
|
||||
|
||||
|
||||
superuser_help_image = IMAGE_PATH / 'superuser_help.png'
|
||||
|
||||
if superuser_help_image.exists():
|
||||
superuser_help_image.unlink()
|
||||
if SUPERUSER_HELP_IMAGE.exists():
|
||||
SUPERUSER_HELP_IMAGE.unlink()
|
||||
|
||||
super_help = on_command(
|
||||
"超级用户帮助", rule=to_me(), priority=1, permission=SUPERUSER, block=True
|
||||
@@ -21,7 +18,7 @@ super_help = on_command(
|
||||
|
||||
@super_help.handle()
|
||||
async def _():
|
||||
if not superuser_help_image.exists():
|
||||
if not SUPERUSER_HELP_IMAGE.exists():
|
||||
await create_help_image()
|
||||
x = image(superuser_help_image)
|
||||
x = image(SUPERUSER_HELP_IMAGE)
|
||||
await super_help.finish(x)
|
||||
|
||||
@@ -1,79 +1,84 @@
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from services.log import logger
|
||||
from utils.utils import get_matchers
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from nonebot import Driver
|
||||
import asyncio
|
||||
import nonebot
|
||||
|
||||
import nonebot
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from nonebot import Driver
|
||||
from services.log import logger
|
||||
from utils.image_template import help_template
|
||||
from utils.image_utils import (BuildImage, build_sort_image, group_image,
|
||||
text2image)
|
||||
from utils.manager import plugin_data_manager
|
||||
from utils.manager.models import PluginType
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
background = IMAGE_PATH / "background" / "0.png"
|
||||
|
||||
superuser_help_image = IMAGE_PATH / "superuser_help.png"
|
||||
SUPERUSER_HELP_IMAGE = IMAGE_PATH / "superuser_help.png"
|
||||
|
||||
|
||||
@driver.on_bot_connect
|
||||
async def create_help_image(bot: Bot = None):
|
||||
async def create_help_image():
|
||||
"""
|
||||
创建超级用户帮助图片
|
||||
"""
|
||||
await asyncio.get_event_loop().run_in_executor(None, _create_help_image)
|
||||
|
||||
|
||||
def _create_help_image():
|
||||
"""
|
||||
创建管理员帮助图片
|
||||
"""
|
||||
_matchers = get_matchers()
|
||||
_plugin_name_list = []
|
||||
width = 0
|
||||
help_str = "超级用户帮助\n\n* 注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数 *\n\n"
|
||||
tmp_img = BuildImage(0, 0, plain_text='1', font_size=24)
|
||||
for matcher in _matchers:
|
||||
plugin_name = ""
|
||||
if SUPERUSER_HELP_IMAGE.exists():
|
||||
return
|
||||
plugin_data_ = plugin_data_manager.get_data()
|
||||
image_list = []
|
||||
task_list = []
|
||||
for plugin_data in [
|
||||
plugin_data_[x]
|
||||
for x in plugin_data_
|
||||
if plugin_data_[x].name != "超级用户帮助 [Superuser]"
|
||||
]:
|
||||
try:
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
_module = _plugin.module
|
||||
try:
|
||||
plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
except AttributeError:
|
||||
continue
|
||||
is_superuser_usage = False
|
||||
try:
|
||||
_ = _module.__getattribute__("__plugin_superuser_usage__")
|
||||
is_superuser_usage = True
|
||||
except AttributeError:
|
||||
pass
|
||||
if (
|
||||
("[superuser]" in plugin_name.lower() or is_superuser_usage)
|
||||
and plugin_name != "超级用户帮助 [Superuser]"
|
||||
and plugin_name not in _plugin_name_list
|
||||
and "[hidden]" not in plugin_name.lower()
|
||||
):
|
||||
_plugin_name_list.append(plugin_name)
|
||||
try:
|
||||
plugin_des = _module.__getattribute__("__plugin_des__")
|
||||
except AttributeError:
|
||||
plugin_des = '_'
|
||||
plugin_cmd = _module.__getattribute__("__plugin_cmd__")
|
||||
if is_superuser_usage:
|
||||
plugin_cmd = [x for x in plugin_cmd if "[_superuser]" in x]
|
||||
plugin_cmd = " / ".join(plugin_cmd).replace('[_superuser]', '').strip()
|
||||
help_str += f"{plugin_des} -> {plugin_cmd}\n\n"
|
||||
x = tmp_img.getsize(f"{plugin_des} -> {plugin_cmd}")[0]
|
||||
width = width if width > x else x
|
||||
if plugin_data.plugin_type in [PluginType.SUPERUSER, PluginType.ADMIN]:
|
||||
usage = None
|
||||
if (
|
||||
plugin_data.plugin_type == PluginType.SUPERUSER
|
||||
and plugin_data.usage
|
||||
):
|
||||
usage = await text2image(
|
||||
plugin_data.usage, padding=5, color=(204, 196, 151)
|
||||
)
|
||||
if plugin_data.superuser_usage:
|
||||
usage = await text2image(
|
||||
plugin_data.superuser_usage, padding=5, color=(204, 196, 151)
|
||||
)
|
||||
if usage:
|
||||
await usage.acircle_corner()
|
||||
image = await help_template(plugin_data.name, usage)
|
||||
image_list.append(image)
|
||||
if plugin_data.task:
|
||||
for x in plugin_data.task.keys():
|
||||
task_list.append(plugin_data.task[x])
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"获取超级用户插件 {matcher.plugin_name}: {plugin_name} 设置失败... {type(e)}:{e}"
|
||||
f"获取超级用户插件 {plugin_data.model}: {plugin_data.name} 设置失败... {type(e)}:{e}"
|
||||
)
|
||||
height = len(help_str.split("\n")) * 33
|
||||
width += 500
|
||||
A = BuildImage(width, height, font_size=24)
|
||||
_background = BuildImage(width, height, background=background)
|
||||
A.text((300, 140), help_str)
|
||||
A.paste(_background, alpha=True)
|
||||
A.save(superuser_help_image)
|
||||
logger.info(f"已成功加载 {len(_plugin_name_list)} 条超级用户命令")
|
||||
task_str = "\n".join(task_list)
|
||||
task_str = "通过私聊 开启被动/关闭被动 + [被动名称] 来控制全局被动\n----------\n" + task_str
|
||||
task_image = await text2image(
|
||||
task_str, padding=5, color=(204, 196, 151)
|
||||
)
|
||||
task_image = await help_template("被动任务", task_image)
|
||||
image_list.append(task_image)
|
||||
image_group, _ = group_image(image_list)
|
||||
A = await build_sort_image(image_group, color="#f9f6f2", padding_top=180)
|
||||
await A.apaste(
|
||||
BuildImage(0, 0, font="CJGaoDeGuo.otf", plain_text="超级用户帮助", font_size=50),
|
||||
(50, 30),
|
||||
True,
|
||||
)
|
||||
await A.apaste(
|
||||
BuildImage(
|
||||
0,
|
||||
0,
|
||||
font="CJGaoDeGuo.otf",
|
||||
plain_text="注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数",
|
||||
font_size=30,
|
||||
font_color="red",
|
||||
),
|
||||
(50, 90),
|
||||
True,
|
||||
)
|
||||
await A.asave(SUPERUSER_HELP_IMAGE)
|
||||
logger.info(f"已成功加载 {len(image_list)} 条超级用户命令")
|
||||
|
||||
@@ -15,6 +15,8 @@ FONT_PATH = Path() / "resources" / "font"
|
||||
DATA_PATH = Path() / "data"
|
||||
# 临时数据路径
|
||||
TEMP_PATH = Path() / "resources" / "temp"
|
||||
# 网页模板路径
|
||||
TEMPLATE_PATH = Path() / "resources" / "template"
|
||||
|
||||
|
||||
def load_path():
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import copy
|
||||
from typing import Optional, Any, Union
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import YAML
|
||||
@@ -216,6 +217,9 @@ class ConfigsManager:
|
||||
"""
|
||||
return self._admin_level_data
|
||||
|
||||
def get_data(self):
|
||||
return copy.deepcopy(self._data)
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return not bool(self._data)
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 772 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 799 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.3 MiB |
+9
-1
@@ -2,6 +2,7 @@ from services.db_context import db
|
||||
from typing import Dict
|
||||
from typing import Optional, List
|
||||
from services.log import logger
|
||||
from .goods_info import GoodsInfo
|
||||
|
||||
|
||||
class BagUser(db.Model):
|
||||
@@ -62,17 +63,24 @@ class BagUser(db.Model):
|
||||
return 100
|
||||
|
||||
@classmethod
|
||||
async def get_property(cls, user_qq: int, group_id: int) -> Dict[str, int]:
|
||||
async def get_property(cls, user_qq: int, group_id: int, only_active: bool = False) -> Dict[str, int]:
|
||||
"""
|
||||
说明:
|
||||
获取当前道具
|
||||
参数:
|
||||
:param user_qq: qq号
|
||||
:param group_id: 所在群号
|
||||
:param only_active: 仅仅获取主动使用的道具
|
||||
"""
|
||||
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
|
||||
user = await query.gino.first()
|
||||
if user:
|
||||
if only_active and user.property:
|
||||
data = {}
|
||||
name_list = [x.goods_name for x in await GoodsInfo.get_all_goods() if not x.is_passive]
|
||||
for key in [x for x in user.property.keys() if x in name_list]:
|
||||
data[key] = user.property[key]
|
||||
return data
|
||||
return user.property
|
||||
else:
|
||||
await cls.create(
|
||||
|
||||
+16
-2
@@ -16,6 +16,8 @@ class GoodsInfo(db.Model):
|
||||
daily_purchase_limit = db.Column(
|
||||
db.JSON(), nullable=False, default={}
|
||||
) # 每日购买限制数据存储
|
||||
is_passive = db.Column(db.Boolean(), nullable=False, default=0) # 是否为被动
|
||||
icon = db.Column(db.String(), default=0) # 图标
|
||||
|
||||
_idx1 = db.Index("goods_group_users_idx1", "goods_name", unique=True)
|
||||
|
||||
@@ -28,6 +30,8 @@ class GoodsInfo(db.Model):
|
||||
goods_discount: float = 1,
|
||||
goods_limit_time: int = 0,
|
||||
daily_limit: int = 0,
|
||||
is_passive: bool = False,
|
||||
icon: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
说明:
|
||||
@@ -39,6 +43,8 @@ class GoodsInfo(db.Model):
|
||||
:param goods_discount: 商品折扣
|
||||
:param goods_limit_time: 商品限时
|
||||
:param daily_limit: 每日购买限制
|
||||
:param is_passive: 是否为被动道具
|
||||
:param icon: 图标
|
||||
"""
|
||||
try:
|
||||
if not await cls.get_goods_info(goods_name):
|
||||
@@ -49,10 +55,12 @@ class GoodsInfo(db.Model):
|
||||
goods_discount=goods_discount,
|
||||
goods_limit_time=goods_limit_time,
|
||||
daily_limit=daily_limit,
|
||||
is_passive=is_passive,
|
||||
icon=icon
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"GoodsInfo add_goods 发生错误 {type(e)}:{e}")
|
||||
logger.error(f"GoodsInfo add_goods {goods_name} 发生错误 {type(e)}:{e}")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
@@ -81,7 +89,9 @@ class GoodsInfo(db.Model):
|
||||
goods_description: Optional[str] = None,
|
||||
goods_discount: Optional[float] = None,
|
||||
goods_limit_time: Optional[int] = None,
|
||||
daily_limit: Optional[int] = None
|
||||
daily_limit: Optional[int] = None,
|
||||
is_passive: Optional[bool] = None,
|
||||
icon: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
说明:
|
||||
@@ -93,6 +103,8 @@ class GoodsInfo(db.Model):
|
||||
:param goods_discount: 商品折扣
|
||||
:param goods_limit_time: 商品限时时间
|
||||
:param daily_limit: 每日次数限制
|
||||
:param is_passive: 是否为被动
|
||||
:param icon: 图标
|
||||
"""
|
||||
try:
|
||||
query = (
|
||||
@@ -108,6 +120,8 @@ class GoodsInfo(db.Model):
|
||||
goods_discount=goods_discount or query.goods_discount,
|
||||
goods_limit_time=goods_limit_time if goods_limit_time is not None else query.goods_limit_time,
|
||||
daily_limit=daily_limit if daily_limit is not None else query.daily_limit,
|
||||
is_passive=is_passive if is_passive is not None else query.is_passive,
|
||||
icon=icon or query.icon
|
||||
).apply()
|
||||
return True
|
||||
except Exception as e:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
from datetime import datetime
|
||||
|
||||
from services.db_context import db
|
||||
|
||||
|
||||
class UserShopGoldLog(db.Model):
|
||||
__tablename__ = "user_shop_gold_log"
|
||||
id = db.Column(db.Integer(), primary_key=True)
|
||||
user_qq = db.Column(db.BigInteger(), nullable=False)
|
||||
group_id = db.Column(db.BigInteger(), nullable=False)
|
||||
type = db.Column(db.Integer(), nullable=False) # 0: 购买,1: 使用,2: 插件
|
||||
name = db.Column(db.String())
|
||||
spend_gold = db.Column(db.Integer(), nullable=False)
|
||||
num = db.Column(db.Integer(), nullable=False)
|
||||
create_time = db.Column(db.DateTime(timezone=True), nullable=False)
|
||||
|
||||
@classmethod
|
||||
async def add_shop_log(
|
||||
cls,
|
||||
user_qq: int,
|
||||
group_id: int,
|
||||
type_: int,
|
||||
name: str,
|
||||
num: int,
|
||||
spend_gold: int = 0,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
添加商店购买或使用日志
|
||||
参数:
|
||||
:param user_qq: qq号
|
||||
:param group_id: 所在群号
|
||||
:param type_: 类型
|
||||
:param name: 商品名称
|
||||
:param num: 数量
|
||||
:param spend_gold: 花费金币
|
||||
"""
|
||||
await cls.create(
|
||||
user_qq=user_qq,
|
||||
group_id=group_id,
|
||||
type=type_,
|
||||
name=name,
|
||||
num=num,
|
||||
spend_gold=spend_gold,
|
||||
create_time=datetime.now(),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def get_user_log(cls, user_qq: int, group_id: int) -> "UserShopGoldLog":
|
||||
"""
|
||||
说明:
|
||||
获取用户日志
|
||||
参数:
|
||||
:param user_qq: qq号
|
||||
:param group_id: 所在群号
|
||||
"""
|
||||
return await cls.query.where(
|
||||
(cls.user_qq == user_qq) & (cls.group_qq == group_id)
|
||||
).first()
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
from nonebot import on_message
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
Bot,
|
||||
|
||||
@@ -31,16 +31,16 @@ usage:
|
||||
主播订阅相当于 直播间订阅 + UP订阅
|
||||
指令:[示例Id乱打的,仅做示例]
|
||||
添加订阅 ['主播'/'UP'/'番剧'] [id/链接/番名]
|
||||
删除订阅 [id]
|
||||
删除订阅 ['主播'/'UP'/'id'] [id]
|
||||
查看订阅
|
||||
示例:添加订阅主播 2345344 <-(直播房间id)
|
||||
示例:添加订阅UP 2355543 <-(个人主页id)
|
||||
示例:添加订阅番剧 史莱姆 <-(支持模糊搜索)
|
||||
示例:添加订阅番剧 125344 <-(番剧id)
|
||||
示例:删除订阅 2324344 <-(任意id,通过查看订阅获取)
|
||||
示例:删除订阅id 2324344 <-(任意id,通过查看订阅获取)
|
||||
""".strip()
|
||||
__plugin_des__ = "非常便利的B站订阅通知"
|
||||
__plugin_cmd__ = ["添加订阅 [主播/UP/番剧] [id/链接/番名]", "删除订阅 [id]", "查看订阅"]
|
||||
__plugin_cmd__ = ["添加订阅 [主播/UP/番剧] [id/链接/番名]", "删除订阅 ['主播'/'UP'/'id'] [id]", "查看订阅"]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier & NumberSir"
|
||||
__plugin_settings__ = {
|
||||
@@ -68,7 +68,7 @@ __plugin_configs__ = {
|
||||
}
|
||||
|
||||
add_sub = on_command("添加订阅", priority=5, block=True)
|
||||
del_sub = on_regex(r"^删除订阅(\d+)$", priority=5, block=True)
|
||||
del_sub = on_command("删除订阅", priority=5, block=True)
|
||||
show_sub_info = on_regex("^查看订阅$", priority=5, block=True)
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
@@ -84,6 +84,7 @@ async def _():
|
||||
|
||||
|
||||
@add_sub.handle()
|
||||
@del_sub.handle()
|
||||
async def _(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip().split()
|
||||
if len(msg) < 2:
|
||||
@@ -157,23 +158,30 @@ async def _(
|
||||
)
|
||||
|
||||
|
||||
@del_sub.handle()
|
||||
async def _(event: MessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
msg = reg_group[0]
|
||||
id_ = (
|
||||
f"{event.group_id}"
|
||||
if isinstance(event, GroupMessageEvent)
|
||||
else f"{event.user_id}"
|
||||
)
|
||||
if await BilibiliSub.delete_bilibili_sub(int(msg), id_):
|
||||
await del_sub.send(f"删除订阅id:{msg} 成功...")
|
||||
@del_sub.got("sub_type")
|
||||
@del_sub.got("sub_user")
|
||||
@del_sub.got("id")
|
||||
async def _(
|
||||
event: MessageEvent,
|
||||
id_: str = ArgStr("id"),
|
||||
sub_type: str = ArgStr("sub_type"),
|
||||
sub_user: str = ArgStr("sub_user"),
|
||||
):
|
||||
if sub_type in ["主播", "直播"]:
|
||||
result = await BilibiliSub.delete_bilibili_sub(int(id_),sub_user,"live")
|
||||
elif sub_type.lower() in ["up", "用户"]:
|
||||
result = await BilibiliSub.delete_bilibili_sub(int(id_),sub_user,"up")
|
||||
else: result = await BilibiliSub.delete_bilibili_sub(int(id_),sub_user)
|
||||
if result:
|
||||
await del_sub.send(f"删除订阅id:{id_} 成功...")
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP "
|
||||
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 删除订阅 {id_}"
|
||||
)
|
||||
f"(USER {event.user_id}, GROUP "
|
||||
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 删除订阅 {id_}"
|
||||
)
|
||||
else:
|
||||
await del_sub.send(f"删除订阅id:{msg} 失败...")
|
||||
await del_sub.send(f"删除订阅id:{id_} 失败...")
|
||||
|
||||
|
||||
|
||||
@show_sub_info.handle()
|
||||
|
||||
@@ -7,11 +7,11 @@ from asyncio.exceptions import TimeoutError
|
||||
from utils.utils import get_bot
|
||||
from .model import BilibiliSub
|
||||
from bilireq.live import get_room_info_by_id
|
||||
from .utils import get_meta
|
||||
from .utils import get_meta, get_user_card
|
||||
from utils.message_builder import image
|
||||
from bilireq.user import get_user_info
|
||||
from bilireq.user import get_videos
|
||||
# from .utils import get_videos
|
||||
from bilireq import dynamic
|
||||
from .utils import get_videos
|
||||
from typing import Optional, Tuple
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from datetime import datetime
|
||||
@@ -83,7 +83,7 @@ async def add_up_sub(uid: int, sub_user: str) -> str:
|
||||
async with db.transaction():
|
||||
try:
|
||||
"""bilibili_api.user库中User类的get_user_info改为bilireq.user库的get_user_info方法"""
|
||||
user_info = await get_user_info(uid)
|
||||
user_info = await get_user_card(uid)
|
||||
except ResponseCodeError:
|
||||
return f"未找到UpId:{uid} 的信息,请检查Id是否正确"
|
||||
uname = user_info["name"]
|
||||
@@ -207,8 +207,8 @@ async def get_sub_status(id_: int, sub_type: str) -> Optional[str]:
|
||||
return await _get_up_status(id_)
|
||||
elif sub_type == "season":
|
||||
return await _get_season_status(id_)
|
||||
except ResponseCodeError:
|
||||
logger.error(f"Id:{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试...")
|
||||
except ResponseCodeError as msg:
|
||||
logger.info(f"Id:{id_} 获取信息失败...{msg}")
|
||||
return None
|
||||
# return f"Id:{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试..."
|
||||
# except Exception as e:
|
||||
@@ -230,7 +230,7 @@ async def _get_live_status(id_: int) -> Optional[str]:
|
||||
sub = await BilibiliSub.get_sub(id_)
|
||||
if sub.live_status != live_status:
|
||||
await BilibiliSub.update_sub_info(id_, live_status=live_status)
|
||||
if sub.live_status == 0 and live_status == 1:
|
||||
if sub.live_status in [0, 2] and live_status == 1:
|
||||
return (
|
||||
f""
|
||||
f"{image(cover)}\n"
|
||||
@@ -249,7 +249,7 @@ async def _get_up_status(id_: int) -> Optional[str]:
|
||||
"""
|
||||
_user = await BilibiliSub.get_sub(id_)
|
||||
"""bilibili_api.user库中User类的get_user_info改为bilireq.user库的get_user_info方法"""
|
||||
user_info = await get_user_info(_user.uid)
|
||||
user_info = await get_user_card(_user.uid)
|
||||
uname = user_info["name"]
|
||||
"""bilibili_api.user库中User类的get_videos改为bilireq.user库的get_videos方法"""
|
||||
video_info = await get_videos(_user.uid)
|
||||
@@ -349,16 +349,8 @@ async def get_user_dynamic(
|
||||
await page.set_viewport_size(
|
||||
{"width": 2560, "height": 1080, "timeout": 10000 * 20}
|
||||
)
|
||||
await page.wait_for_selector(".panel-area")
|
||||
await page.evaluate(
|
||||
"""
|
||||
xs = document.getElementById('internationalHeader');
|
||||
xs.remove();
|
||||
xs = document.getElementsByClassName('panel-area')
|
||||
xs[0].remove();
|
||||
"""
|
||||
)
|
||||
card = page.locator(".detail-card")
|
||||
await page.wait_for_selector(".bili-dyn-item__main")
|
||||
card = page.locator(".bili-dyn-item__main")
|
||||
await card.wait_for()
|
||||
await card.screenshot(
|
||||
path=dynamic_path / f"{local_user.sub_id}_{dynamic_upload_time}.jpg",
|
||||
|
||||
@@ -66,7 +66,7 @@ class BilibiliSub(db.Model):
|
||||
"""
|
||||
try:
|
||||
query = (
|
||||
await cls.query.where(cls.sub_id == sub_id)
|
||||
await cls.query.where( (cls.sub_id == sub_id) & (cls.sub_type == sub_type) )
|
||||
.with_for_update()
|
||||
.gino.first()
|
||||
)
|
||||
@@ -107,7 +107,7 @@ class BilibiliSub(db.Model):
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
async def delete_bilibili_sub(cls, sub_id: int, sub_user: str) -> bool:
|
||||
async def delete_bilibili_sub(cls, sub_id: int, sub_user: str,sub_type: Optional[str] = None) -> bool:
|
||||
"""
|
||||
说明:
|
||||
删除订阅
|
||||
@@ -117,13 +117,22 @@ class BilibiliSub(db.Model):
|
||||
"""
|
||||
try:
|
||||
async with db.transaction():
|
||||
query = (
|
||||
await cls.query.where(
|
||||
(cls.sub_id == sub_id) & (cls.sub_users.contains(sub_user))
|
||||
if sub_type:
|
||||
query = (
|
||||
await cls.query.where(
|
||||
(cls.sub_id == sub_id) & (cls.sub_users.contains(sub_user) & (cls.sub_type == sub_type))
|
||||
)
|
||||
.with_for_update()
|
||||
.gino.first()
|
||||
)
|
||||
else:
|
||||
query = (
|
||||
await cls.query.where(
|
||||
(cls.sub_id == sub_id) & (cls.sub_users.contains(sub_user))
|
||||
)
|
||||
.with_for_update()
|
||||
.gino.first()
|
||||
)
|
||||
.with_for_update()
|
||||
.gino.first()
|
||||
)
|
||||
if not query:
|
||||
return False
|
||||
await query.update(
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from utils.http_utils import AsyncHttpx, get_user_agent
|
||||
# from bilibili_api import user
|
||||
from bilireq.user import get_user_info
|
||||
from httpx import AsyncClient
|
||||
from io import BytesIO
|
||||
|
||||
|
||||
BORDER_PATH = IMAGE_PATH / "border"
|
||||
BORDER_PATH.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
BASE_URL = "https://api.bilibili.com"
|
||||
|
||||
async def get_pic(url: str) -> bytes:
|
||||
"""
|
||||
@@ -78,7 +79,6 @@ async def get_meta(media_id: int, auth=None, reqtype="both", **kwargs):
|
||||
"""
|
||||
from bilireq.utils import get
|
||||
|
||||
BASE_URL = "https://api.bilibili.com"
|
||||
url = f"{BASE_URL}/pgc/review/user"
|
||||
params = {"media_id": media_id}
|
||||
raw_json = await get(url, raw=True, params=params, auth=auth, reqtype=reqtype, **kwargs)
|
||||
@@ -86,8 +86,7 @@ async def get_meta(media_id: int, auth=None, reqtype="both", **kwargs):
|
||||
|
||||
|
||||
async def get_videos(
|
||||
uid: int, tid: int = 0, pn: int = 1, keyword: str = "", order: str = "pubdate",
|
||||
*, auth=None, reqtype="both", **kwargs
|
||||
uid: int, tid: int = 0, pn: int = 1, keyword: str = "", order: str = "pubdate"
|
||||
):
|
||||
"""
|
||||
获取用户投该视频信息
|
||||
@@ -100,15 +99,45 @@ async def get_videos(
|
||||
:param keyword: 搜索关键词
|
||||
:param order: 排序方式,可以为 “pubdate(上传日期从新到旧), stow(收藏从多到少), click(播放量从多到少)”
|
||||
"""
|
||||
from bilireq.utils import get
|
||||
BASE_URL = "https://api.bilibili.com"
|
||||
from bilireq.utils import ResponseCodeError
|
||||
|
||||
url = f"{BASE_URL}/x/space/arc/search"
|
||||
params = {
|
||||
"mid": uid,
|
||||
"ps": 30,
|
||||
"tid": tid,
|
||||
"pn": pn,
|
||||
"keyword": keyword,
|
||||
"order": order
|
||||
}
|
||||
return await get(url, params=params, auth=auth, reqtype=reqtype, **kwargs)
|
||||
headers = get_user_agent()
|
||||
headers["Referer"] = f"https://space.bilibili.com/{uid}/video"
|
||||
async with AsyncClient() as client:
|
||||
r = await client.head(
|
||||
"https://space.bilibili.com",
|
||||
headers=headers,
|
||||
)
|
||||
params = {
|
||||
"mid": uid,
|
||||
"ps": 30,
|
||||
"tid": tid,
|
||||
"pn": pn,
|
||||
"keyword": keyword,
|
||||
"order": order,
|
||||
}
|
||||
raw_json = (
|
||||
await client.get(url, params=params, headers=headers, cookies=r.cookies)
|
||||
).json()
|
||||
if raw_json["code"] != 0:
|
||||
raise ResponseCodeError(
|
||||
code=raw_json["code"],
|
||||
msg=raw_json["message"],
|
||||
data=raw_json.get("data", None),
|
||||
)
|
||||
return raw_json["data"]
|
||||
|
||||
async def get_user_card(mid, photo: bool = False, auth=None, reqtype="both", **kwargs):
|
||||
from bilireq.utils import get
|
||||
|
||||
url = f"{BASE_URL}/x/web-interface/card"
|
||||
return (
|
||||
await get(
|
||||
url,
|
||||
params={"mid": mid, "photo": photo},
|
||||
auth=auth,
|
||||
reqtype=reqtype,
|
||||
**kwargs,
|
||||
)
|
||||
)["card"]
|
||||
|
||||
@@ -9,7 +9,7 @@ import platform
|
||||
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
|
||||
|
||||
url = "http://www.eclzz.cool"
|
||||
url = "http://www.eclzz.love"
|
||||
|
||||
|
||||
async def get_bt_info(keyword: str, page: int):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from nonebot.adapters.onebot.v11 import Bot, MessageEvent
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot import on_command
|
||||
from .data_source import check_update, get_latest_version_data
|
||||
@@ -50,24 +50,24 @@ restart = on_command(
|
||||
|
||||
|
||||
@update_zhenxun.handle()
|
||||
async def _(bot: Bot):
|
||||
async def _(bot: Bot, event: MessageEvent):
|
||||
try:
|
||||
code, error = await check_update(bot)
|
||||
if error:
|
||||
logger.error(f"更新真寻未知错误 {error}")
|
||||
await bot.send_private_msg(
|
||||
user_id=int(list(bot.config.superusers)[0]), message=f"更新真寻未知错误 {error}"
|
||||
user_id=event.user_id, message=f"更新真寻未知错误 {error}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"更新真寻未知错误 {type(e)}:{e}")
|
||||
await bot.send_private_msg(
|
||||
user_id=int(list(bot.config.superusers)[0]),
|
||||
user_id=event.user_id,
|
||||
message=f"更新真寻未知错误 {type(e)}:{e}",
|
||||
)
|
||||
else:
|
||||
if code == 200:
|
||||
await bot.send_private_msg(
|
||||
user_id=int(list(bot.config.superusers)[0]), message=f"更新完毕,请重启真寻...."
|
||||
user_id=event.user_id, message=f"更新完毕,请重启真寻...."
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import asyncio
|
||||
import traceback
|
||||
from cn2an import cn2an
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Set, Tuple
|
||||
from typing import Any, Optional, Set, Tuple
|
||||
|
||||
import nonebot
|
||||
from nonebot import on_regex, on_keyword
|
||||
from cn2an import cn2an
|
||||
from configs.config import Config
|
||||
from nonebot import on_keyword, on_message, on_regex
|
||||
from nonebot.adapters.onebot.v11 import MessageEvent
|
||||
from nonebot.log import logger
|
||||
from nonebot.matcher import Matcher
|
||||
@@ -14,8 +15,9 @@ from nonebot.permission import SUPERUSER
|
||||
from nonebot.typing import T_Handler
|
||||
from nonebot_plugin_apscheduler import scheduler
|
||||
|
||||
from .handles.base_handle import BaseHandle
|
||||
from .handles.azur_handle import AzurHandle
|
||||
from .handles.ba_handle import BaHandle
|
||||
from .handles.base_handle import BaseHandle
|
||||
from .handles.fgo_handle import FgoHandle
|
||||
from .handles.genshin_handle import GenshinHandle
|
||||
from .handles.guardian_handle import GuardianHandle
|
||||
@@ -23,10 +25,7 @@ from .handles.onmyoji_handle import OnmyojiHandle
|
||||
from .handles.pcr_handle import PcrHandle
|
||||
from .handles.pretty_handle import PrettyHandle
|
||||
from .handles.prts_handle import PrtsHandle
|
||||
from .handles.ba_handle import BaHandle
|
||||
|
||||
from .config import draw_config
|
||||
|
||||
from .rule import rule
|
||||
|
||||
__zx_plugin_name__ = "游戏抽卡"
|
||||
__plugin_usage__ = """
|
||||
@@ -35,6 +34,7 @@ usage:
|
||||
指令:
|
||||
原神[1-180]抽: 原神常驻池
|
||||
原神角色[1-180]抽: 原神角色UP池子
|
||||
原神角色2池[1-180]抽: 原神角色UP池子
|
||||
原神武器[1-180]抽: 原神武器UP池子
|
||||
重置原神抽卡: 清空当前卡池的抽卡次数[即从0开始计算UP概率]
|
||||
方舟[1-300]抽: 方舟卡池,当有当期UP时指向UP池
|
||||
@@ -99,45 +99,81 @@ __plugin_settings__ = {
|
||||
}
|
||||
|
||||
|
||||
x = on_message(rule=lambda: False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Game:
|
||||
keywords: Set[str]
|
||||
handle: BaseHandle
|
||||
flag: bool
|
||||
config_name: str
|
||||
max_count: int = 300 # 一次最大抽卡数
|
||||
reload_time: Optional[int] = None # 重载UP池时间(小时)
|
||||
has_other_pool: bool = False
|
||||
|
||||
|
||||
games = (
|
||||
Game({"azur", "碧蓝航线"}, AzurHandle(), draw_config.AZUR_FLAG),
|
||||
Game({"fgo", "命运冠位指定"}, FgoHandle(), draw_config.FGO_FLAG),
|
||||
Game(
|
||||
{"azur", "碧蓝航线"},
|
||||
AzurHandle(),
|
||||
Config.get_config("draw_card", "AZUR_FLAG", True),
|
||||
"AZUR_FLAG",
|
||||
),
|
||||
Game(
|
||||
{"fgo", "命运冠位指定"},
|
||||
FgoHandle(),
|
||||
Config.get_config("draw_card", "FGO_FLAG", True),
|
||||
"FGO_FLAG",
|
||||
),
|
||||
Game(
|
||||
{"genshin", "原神"},
|
||||
GenshinHandle(),
|
||||
draw_config.GENSHIN_FLAG,
|
||||
Config.get_config("draw_card", "GENSHIN_FLAG", True),
|
||||
"GENSHIN_FLAG",
|
||||
max_count=180,
|
||||
reload_time=18,
|
||||
has_other_pool=True,
|
||||
),
|
||||
Game(
|
||||
{"guardian", "坎公骑冠剑"},
|
||||
GuardianHandle(),
|
||||
draw_config.GUARDIAN_FLAG,
|
||||
Config.get_config("draw_card", "GUARDIAN_FLAG", True),
|
||||
"GUARDIAN_FLAG",
|
||||
reload_time=4,
|
||||
),
|
||||
Game({"onmyoji", "阴阳师"}, OnmyojiHandle(), draw_config.ONMYOJI_FLAG),
|
||||
Game({"pcr", "公主连结", "公主连接", "公主链接", "公主焊接"}, PcrHandle(), draw_config.PCR_FLAG),
|
||||
Game(
|
||||
{"onmyoji", "阴阳师"},
|
||||
OnmyojiHandle(),
|
||||
Config.get_config("draw_card", "ONMYOJI_FLAG", True),
|
||||
"ONMYOJI_FLAG",
|
||||
),
|
||||
Game(
|
||||
{"pcr", "公主连结", "公主连接", "公主链接", "公主焊接"},
|
||||
PcrHandle(),
|
||||
Config.get_config("draw_card", "PCR_FLAG", True),
|
||||
"PCR_FLAG",
|
||||
),
|
||||
Game(
|
||||
{"pretty", "马娘", "赛马娘"},
|
||||
PrettyHandle(),
|
||||
draw_config.PRETTY_FLAG,
|
||||
Config.get_config("draw_card", "PRETTY_FLAG", True),
|
||||
"PRETTY_FLAG",
|
||||
max_count=200,
|
||||
reload_time=4,
|
||||
),
|
||||
Game({"prts", "方舟", "明日方舟"}, PrtsHandle(), draw_config.PRTS_FLAG, reload_time=4),
|
||||
Game(
|
||||
{"ba","碧蓝档案"},BaHandle(),
|
||||
draw_config.BA_FLAG,
|
||||
max_count=200,
|
||||
{"prts", "方舟", "明日方舟"},
|
||||
PrtsHandle(),
|
||||
Config.get_config("draw_card", "PRTS_FLAG", True),
|
||||
"PRTS_FLAG",
|
||||
reload_time=4,
|
||||
),
|
||||
Game(
|
||||
{"ba", "碧蓝档案"},
|
||||
BaHandle(),
|
||||
Config.get_config("draw_card", "BA_FLAG", True),
|
||||
"BA_FLAG",
|
||||
),
|
||||
)
|
||||
|
||||
@@ -145,9 +181,9 @@ games = (
|
||||
def create_matchers():
|
||||
def draw_handler(game: Game) -> T_Handler:
|
||||
async def handler(
|
||||
matcher: Matcher, event: MessageEvent, args: Tuple[str, ...] = RegexGroup()
|
||||
matcher: Matcher, event: MessageEvent, args: Tuple[Any, ...] = RegexGroup()
|
||||
):
|
||||
pool_name, num, unit = args
|
||||
pool_name, pool_type_, num, unit = args
|
||||
if num == "单":
|
||||
num = 1
|
||||
else:
|
||||
@@ -169,7 +205,9 @@ def create_matchers():
|
||||
.replace("卡", "card")
|
||||
)
|
||||
try:
|
||||
res = await game.handle.draw(num, pool_name=pool_name, user_id=event.user_id)
|
||||
if pool_type_ in ["2池", "二池"]:
|
||||
pool_name = pool_name + "1"
|
||||
res = game.handle.draw(num, pool_name=pool_name, user_id=event.user_id)
|
||||
except:
|
||||
logger.warning(traceback.format_exc())
|
||||
await matcher.finish("出错了...")
|
||||
@@ -209,29 +247,31 @@ def create_matchers():
|
||||
pool_pattern = r"([^\s单0-9零一二三四五六七八九百十]{0,3})"
|
||||
num_pattern = r"(单|[0-9零一二三四五六七八九百十]{1,3})"
|
||||
unit_pattern = r"([抽|井|连])"
|
||||
draw_regex = r".*?(?:{})\s*{}\s*{}\s*{}".format(
|
||||
"|".join(game.keywords), pool_pattern, num_pattern, unit_pattern
|
||||
pool_type = "()"
|
||||
if game.has_other_pool:
|
||||
pool_type = r"([2二]池)?"
|
||||
draw_regex = r".*?(?:{})\s*{}\s*{}\s*{}\s*{}".format(
|
||||
"|".join(game.keywords), pool_pattern, pool_type, num_pattern, unit_pattern
|
||||
)
|
||||
update_keywords = {f"更新{keyword}信息" for keyword in game.keywords}
|
||||
reload_keywords = {f"重载{keyword}卡池" for keyword in game.keywords}
|
||||
reset_keywords = {f"重置{keyword}抽卡" for keyword in game.keywords}
|
||||
if game.flag:
|
||||
on_regex(draw_regex, priority=5, block=True).append_handler(
|
||||
draw_handler(game)
|
||||
on_regex(draw_regex, priority=5, block=True, rule=rule(game)).append_handler(
|
||||
draw_handler(game)
|
||||
)
|
||||
on_keyword(
|
||||
update_keywords, priority=1, block=True, permission=SUPERUSER
|
||||
).append_handler(update_handler(game))
|
||||
on_keyword(
|
||||
reload_keywords, priority=1, block=True, permission=SUPERUSER
|
||||
).append_handler(reload_handler(game))
|
||||
on_keyword(reset_keywords, priority=5, block=True).append_handler(
|
||||
reset_handler(game)
|
||||
)
|
||||
if game.reload_time:
|
||||
scheduler.add_job(
|
||||
scheduled_job(game), trigger="cron", hour=game.reload_time, minute=1
|
||||
)
|
||||
on_keyword(
|
||||
update_keywords, permission=SUPERUSER, priority=1, block=True
|
||||
).append_handler(update_handler(game))
|
||||
on_keyword(reload_keywords, priority=1, block=True).append_handler(
|
||||
reload_handler(game)
|
||||
)
|
||||
on_keyword(reset_keywords, priority=1, block=True).append_handler(
|
||||
reset_handler(game)
|
||||
)
|
||||
if game.reload_time:
|
||||
scheduler.add_job(
|
||||
scheduled_job(game), trigger="cron", hour=game.reload_time, minute=1
|
||||
)
|
||||
|
||||
|
||||
create_matchers()
|
||||
|
||||
+33
-19
@@ -1,9 +1,9 @@
|
||||
import nonebot
|
||||
from pathlib import Path
|
||||
from nonebot.log import logger
|
||||
from pydantic import BaseModel, Extra
|
||||
from pydantic import BaseModel, Extra, ValidationError
|
||||
from configs.config import Config as AConfig
|
||||
from configs.path_config import DATA_PATH
|
||||
from configs.path_config import IMAGE_PATH, DATA_PATH
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -87,28 +87,30 @@ class OnmyojiConfig(BaseModel, extra=Extra.ignore):
|
||||
ONMYOJI_SR: float = 0.2
|
||||
ONMYOJI_R: float = 0.7875
|
||||
|
||||
#碧蓝档案
|
||||
|
||||
# 碧蓝档案
|
||||
class BaConfig(BaseModel, extra=Extra.ignore):
|
||||
BA_THREE_P: float = 0.025
|
||||
BA_TWO_P: float = 0.185
|
||||
BA_ONE_P: float = 0.79
|
||||
BA_G_TWO_P: float = 0.975
|
||||
|
||||
|
||||
class Config(BaseModel, extra=Extra.ignore):
|
||||
# 开关
|
||||
PRTS_FLAG: bool = AConfig.get_config("draw_card", "PRTS_FLAG")
|
||||
GENSHIN_FLAG: bool = AConfig.get_config("draw_card", "GENSHIN_FLAG")
|
||||
PRETTY_FLAG: bool = AConfig.get_config("draw_card", "PRETTY_FLAG")
|
||||
GUARDIAN_FLAG: bool = AConfig.get_config("draw_card", "GUARDIAN_FLAG")
|
||||
PCR_FLAG: bool = AConfig.get_config("draw_card", "PCR_FLAG")
|
||||
AZUR_FLAG: bool = AConfig.get_config("draw_card", "AZUR_FLAG")
|
||||
FGO_FLAG: bool = AConfig.get_config("draw_card", "FGO_FLAG")
|
||||
ONMYOJI_FLAG: bool = AConfig.get_config("draw_card", "ONMYOJI_FLAG")
|
||||
BA_FLAG: bool = AConfig.get_config("draw_card", "BA_FLAG")
|
||||
PRTS_FLAG: bool = True
|
||||
GENSHIN_FLAG: bool = True
|
||||
PRETTY_FLAG: bool = True
|
||||
GUARDIAN_FLAG: bool = True
|
||||
PCR_FLAG: bool = True
|
||||
AZUR_FLAG: bool = True
|
||||
FGO_FLAG: bool = True
|
||||
ONMYOJI_FLAG: bool = True
|
||||
BA_FLAG: bool = True
|
||||
|
||||
# 其他配置
|
||||
PCR_TAI: bool = AConfig.get_config("draw_card", "PCR_TAI")
|
||||
SEMAPHORE: int = AConfig.get_config("draw_card", "SEMAPHORE")
|
||||
PCR_TAI: bool = True
|
||||
SEMAPHORE: int = 5
|
||||
|
||||
# 抽卡概率
|
||||
prts: PrtsConfig = PrtsConfig()
|
||||
@@ -124,12 +126,16 @@ class Config(BaseModel, extra=Extra.ignore):
|
||||
|
||||
driver = nonebot.get_driver()
|
||||
|
||||
DRAW_PATH = DATA_PATH / "draw_card"
|
||||
config_path = DRAW_PATH / "draw_card_config" / "draw_card_config.json"
|
||||
# DRAW_PATH = Path("data/draw_card").absolute()
|
||||
DRAW_PATH = IMAGE_PATH / "draw_card"
|
||||
# try:
|
||||
# DRAW_PATH = Path(global_config.draw_path).absolute()
|
||||
# except:
|
||||
# pass
|
||||
config_path = DATA_PATH / "draw_card" / "draw_card_config" / "draw_card_config.json"
|
||||
|
||||
draw_config: Config = Config()
|
||||
|
||||
|
||||
for game_flag, game_name in zip(
|
||||
[
|
||||
"PRTS_FLAG",
|
||||
@@ -143,7 +149,7 @@ for game_flag, game_name in zip(
|
||||
"PCR_TAI",
|
||||
"BA_FLAG"
|
||||
],
|
||||
["明日方舟", "原神", "赛马娘", "坎公骑冠剑", "公主连结", "碧蓝航线", "命运-冠位指定(FGO)", "阴阳师", "pcr台服卡池","碧蓝档案"],
|
||||
["明日方舟", "原神", "赛马娘", "坎公骑冠剑", "公主连结", "碧蓝航线", "命运-冠位指定(FGO)", "阴阳师", "pcr台服卡池", "碧蓝档案"],
|
||||
):
|
||||
AConfig.add_plugin_config(
|
||||
"draw_card",
|
||||
@@ -161,11 +167,19 @@ AConfig.add_plugin_config(
|
||||
@driver.on_startup
|
||||
def check_config():
|
||||
global draw_config
|
||||
draw_config = Config()
|
||||
|
||||
if not config_path.exists():
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
draw_config = Config()
|
||||
logger.warning("draw_card:配置文件不存在,已重新生成配置文件.....")
|
||||
else:
|
||||
with config_path.open("r", encoding="utf8") as fp:
|
||||
data = json.load(fp)
|
||||
try:
|
||||
draw_config = Config.parse_obj({**data})
|
||||
except ValidationError:
|
||||
draw_config = Config()
|
||||
logger.warning("draw_card:配置文件格式错误,已重新生成配置文件.....")
|
||||
|
||||
with config_path.open("w", encoding="utf8") as fp:
|
||||
json.dump(
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
from typing import Optional
|
||||
from typing import Optional, TypeVar, Generic
|
||||
from pydantic import BaseModel
|
||||
import time
|
||||
from cachetools import TTLCache
|
||||
|
||||
|
||||
class BaseUserCount(BaseModel):
|
||||
count: int = 1 # 当前抽卡次数
|
||||
time_: int = time.time() # 抽卡时间,当超过一定时间时将重置抽卡次数
|
||||
timeout: int = 60 # 超时时间60秒
|
||||
count: int = 0 # 当前抽卡次数
|
||||
|
||||
|
||||
class DrawCountManager:
|
||||
TCount = TypeVar("TCount", bound="BaseUserCount")
|
||||
|
||||
|
||||
class DrawCountManager(Generic[TCount]):
|
||||
"""
|
||||
抽卡统计保底
|
||||
"""
|
||||
@@ -30,19 +31,28 @@ class DrawCountManager:
|
||||
|
||||
"""
|
||||
# 只有保底
|
||||
self._data = {}
|
||||
# 超过60秒重置抽卡次数
|
||||
self._data: TTLCache[int, TCount] = TTLCache(maxsize=1000, ttl=60)
|
||||
self._guarantee_tuple = game_draw_count_rule
|
||||
self._star2name = star2name
|
||||
self._max_draw_count = max_draw_count
|
||||
|
||||
@classmethod
|
||||
def get_count_class(cls) -> TCount:
|
||||
raise NotImplementedError
|
||||
|
||||
def _get_count(self, key: int) -> TCount:
|
||||
if self._data.get(key) is None:
|
||||
self._data[key] = self.get_count_class()
|
||||
else:
|
||||
self._data[key] = self._data[key]
|
||||
return self._data[key]
|
||||
|
||||
def increase(self, key: int, value: int = 1):
|
||||
"""
|
||||
用户抽卡次数加1
|
||||
"""
|
||||
if self._data.get(key) is None:
|
||||
self._data[key] = BaseUserCount()
|
||||
else:
|
||||
self._data[key].count += 1
|
||||
self._get_count(key).count += value
|
||||
|
||||
def get_max_guarantee(self):
|
||||
"""
|
||||
@@ -54,103 +64,74 @@ class DrawCountManager:
|
||||
"""
|
||||
获取当前抽卡次数
|
||||
"""
|
||||
return self._data[key].count
|
||||
|
||||
def update_time(self, key: int):
|
||||
"""
|
||||
更新抽卡时间
|
||||
"""
|
||||
self._data[key].time_ = time.time()
|
||||
return self._get_count(key).count
|
||||
|
||||
def reset(self, key: int):
|
||||
"""
|
||||
清空记录
|
||||
"""
|
||||
del self._data[key]
|
||||
self._data.pop(key, None)
|
||||
|
||||
|
||||
class GenshinCountManager(DrawCountManager):
|
||||
class UserCount(BaseUserCount):
|
||||
five_index: int = 0 # 获取五星时的抽卡次数
|
||||
four_index: int = 0 # 获取四星时的抽卡次数
|
||||
is_up: bool = False # 下次五星是否必定为up
|
||||
class GenshinUserCount(BaseUserCount):
|
||||
five_index: int = 0 # 获取五星时的抽卡次数
|
||||
four_index: int = 0 # 获取四星时的抽卡次数
|
||||
is_up: bool = False # 下次五星是否必定为up
|
||||
|
||||
def increase(self, key: int, value: int = 1):
|
||||
"""
|
||||
用户抽卡次数加1
|
||||
"""
|
||||
if self._data.get(key) is None:
|
||||
self._data[key] = self.UserCount()
|
||||
else:
|
||||
self._data[key].count += 1
|
||||
|
||||
class GenshinCountManager(DrawCountManager[GenshinUserCount]):
|
||||
@classmethod
|
||||
def get_count_class(cls) -> GenshinUserCount:
|
||||
return GenshinUserCount()
|
||||
|
||||
def set_is_up(self, key: int, value: bool):
|
||||
"""
|
||||
设置下次是否必定up
|
||||
"""
|
||||
self._data[key].is_up = value
|
||||
self._get_count(key).is_up = value
|
||||
|
||||
def is_up(self, key: int) -> bool:
|
||||
"""
|
||||
判断该次保底是否必定为up
|
||||
"""
|
||||
return self._data[key].is_up
|
||||
return self._get_count(key).is_up
|
||||
|
||||
def get_user_five_index(self, key: int) -> int:
|
||||
"""
|
||||
获取用户上次获取五星的次数
|
||||
"""
|
||||
return self._data[key].five_index
|
||||
return self._get_count(key).five_index
|
||||
|
||||
def get_user_four_index(self, key: int) -> int:
|
||||
"""
|
||||
获取用户上次获取四星的次数
|
||||
"""
|
||||
return self._data[key].four_index
|
||||
return self._get_count(key).four_index
|
||||
|
||||
def mark_five_index(self, key: int):
|
||||
"""
|
||||
标记用户该次次数为五星
|
||||
"""
|
||||
self._data[key].five_index = self._data[key].count
|
||||
self._get_count(key).five_index = self._get_count(key).count
|
||||
|
||||
def mark_four_index(self, key: int):
|
||||
"""
|
||||
标记用户该次次数为四星
|
||||
"""
|
||||
self._data[key].four_index = self._data[key].count
|
||||
|
||||
def check_timeout(self, key: int):
|
||||
"""
|
||||
检查用户距离上次抽卡是否超时
|
||||
"""
|
||||
if key in self._data.keys() and self._is_timeout(key):
|
||||
del self._data[key]
|
||||
self._get_count(key).four_index = self._get_count(key).count
|
||||
|
||||
def check_count(self, key: int, count: int):
|
||||
"""
|
||||
检查用户该次抽卡次数累计是否超过最大限制次数
|
||||
"""
|
||||
if (
|
||||
key in self._data.keys()
|
||||
and self._data[key].count + count > self._max_draw_count
|
||||
):
|
||||
del self._data[key]
|
||||
|
||||
def _is_timeout(self, key: int) -> bool:
|
||||
return time.time() - self._data[key].time_ > self._data[key].timeout
|
||||
if self._get_count(key).count + count > self._max_draw_count:
|
||||
self._data.pop(key, None)
|
||||
|
||||
def get_user_guarantee_count(self, key: int) -> int:
|
||||
user = self._get_count(key)
|
||||
return (
|
||||
self.get_max_guarantee()
|
||||
- (
|
||||
(
|
||||
self._data[key].count % self.get_max_guarantee()
|
||||
if self._data[key].count > 0
|
||||
else 0
|
||||
)
|
||||
- self._data[key].five_index
|
||||
)
|
||||
- (user.count % self.get_max_guarantee() - user.five_index)
|
||||
) % self.get_max_guarantee() or self.get_max_guarantee()
|
||||
|
||||
def check(self, key: int) -> Optional[int]:
|
||||
@@ -158,12 +139,11 @@ class GenshinCountManager(DrawCountManager):
|
||||
是否保底
|
||||
"""
|
||||
# print(self._data)
|
||||
user: GenshinCountManager.UserCount = self._data[key]
|
||||
user = self._get_count(key)
|
||||
if user.count - user.five_index == 90:
|
||||
user.five_index = 90
|
||||
user.five_index = user.count
|
||||
return 5
|
||||
if user.count - user.four_index == 10:
|
||||
user.four_index = user.count
|
||||
return 4
|
||||
return None
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import contextlib
|
||||
import random
|
||||
import dateparser
|
||||
from lxml import etree
|
||||
from typing import List, Optional, Tuple
|
||||
from PIL import ImageDraw
|
||||
from urllib.parse import unquote
|
||||
from pydantic import ValidationError
|
||||
from nonebot.log import logger
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from utils.message_builder import image
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
|
||||
from utils.message_builder import image
|
||||
from .base_handle import BaseHandle, BaseData, UpEvent as _UpEvent, UpChar as _UpChar
|
||||
from ..config import draw_config
|
||||
from ..util import remove_prohibited_str, cn2py
|
||||
from ..util import remove_prohibited_str, cn2py, load_font
|
||||
from utils.image_utils import BuildImage
|
||||
|
||||
try:
|
||||
@@ -59,19 +59,25 @@ class AzurHandle(BaseHandle[AzurChar]):
|
||||
# print(up_ship)
|
||||
acquire_char = None
|
||||
if up_ship and up_pool_flag:
|
||||
up_zoom = [(0, up_ship[0].zoom / 100)]
|
||||
up_zoom: List[Tuple[float, float]] = [(0, up_ship[0].zoom / 100)]
|
||||
# 初始化概率
|
||||
cur_ = up_ship[0].zoom / 100
|
||||
for i in range(len(up_ship)):
|
||||
with contextlib.suppress(IndexError):
|
||||
try:
|
||||
up_zoom.append((cur_, cur_ + up_ship[i + 1].zoom / 100))
|
||||
cur_ += up_ship[i + 1].zoom / 100
|
||||
except IndexError:
|
||||
pass
|
||||
rand = random.random()
|
||||
# 抽取up
|
||||
for i, zoom in enumerate(up_zoom):
|
||||
if zoom[0] <= rand <= zoom[1]:
|
||||
with contextlib.suppress(IndexError):
|
||||
acquire_char = [x for x in self.ALL_CHAR if x.name == up_ship[i].name][0]
|
||||
try:
|
||||
acquire_char = [
|
||||
x for x in self.ALL_CHAR if x.name == up_ship[i].name
|
||||
][0]
|
||||
except IndexError:
|
||||
pass
|
||||
# 没有up或者未抽取到up
|
||||
if not acquire_char:
|
||||
star = self.get_star(
|
||||
@@ -83,17 +89,19 @@ class AzurHandle(BaseHandle[AzurChar]):
|
||||
self.config.AZUR_ONE_P,
|
||||
],
|
||||
)
|
||||
acquire_char = random.choice([
|
||||
x
|
||||
for x in self.ALL_CHAR
|
||||
if x.star == star and x.type_ in type_ and not x.limited
|
||||
])
|
||||
acquire_char = random.choice(
|
||||
[
|
||||
x
|
||||
for x in self.ALL_CHAR
|
||||
if x.star == star and x.type_ in type_ and not x.limited
|
||||
]
|
||||
)
|
||||
return acquire_char
|
||||
|
||||
async def draw(self, count: int, **kwargs) -> Message:
|
||||
def draw(self, count: int, **kwargs) -> Message:
|
||||
index2card = self.get_cards(count, **kwargs)
|
||||
cards = [card[0] for card in index2card]
|
||||
up_list = [x.name for x in self.UP_EVENT.up_char] if self.UP_EVENT.up_char else []
|
||||
up_list = [x.name for x in self.UP_EVENT.up_char] if self.UP_EVENT else []
|
||||
result = self.format_result(index2card, **{**kwargs, "up_list": up_list})
|
||||
return image(b64=self.generate_img(cards).pic2bs4()) + result
|
||||
|
||||
@@ -103,22 +111,25 @@ class AzurHandle(BaseHandle[AzurChar]):
|
||||
sep_b = 20
|
||||
w = 100
|
||||
h = 100
|
||||
bg = BuildImage(w + sep_w * 2, h + sep_t + sep_b, font="msyh.ttf")
|
||||
frame_path = self.img_path / f"{card.star}_star.png"
|
||||
bg = BuildImage(w + sep_w * 2, h + sep_t + sep_b)
|
||||
frame_path = str(self.img_path / f"{card.star}_star.png")
|
||||
frame = BuildImage(w, h, background=frame_path)
|
||||
img_path = self.img_path / f"{cn2py(card.name)}.png"
|
||||
img_path = str(self.img_path / f"{cn2py(card.name)}.png")
|
||||
img = BuildImage(w, h, background=img_path)
|
||||
# 加圆角
|
||||
frame.circle_corner(6)
|
||||
img.circle_corner(6)
|
||||
bg.paste(img, (sep_w, sep_t), alpha=True)
|
||||
bg.paste(frame, (sep_w, sep_t), alpha=True)
|
||||
bg.circle_corner(6)
|
||||
# 加名字
|
||||
text = card.name[:6] + "..." if len(card.name) > 7 else card.name
|
||||
text_w, text_h = bg.getsize(text)
|
||||
bg.text(
|
||||
font = load_font(fontsize=14)
|
||||
text_w, text_h = font.getsize(text)
|
||||
draw = ImageDraw.Draw(bg.markImg)
|
||||
draw.text(
|
||||
(sep_w + (w - text_w) / 2, h + sep_t + (sep_b - text_h) / 2),
|
||||
text,
|
||||
font=font,
|
||||
fill=["#808080", "#3b8bff", "#8000ff", "#c90", "#ee494c"][card.star - 1],
|
||||
)
|
||||
return bg
|
||||
@@ -146,6 +157,7 @@ class AzurHandle(BaseHandle[AzurChar]):
|
||||
if self.UP_EVENT:
|
||||
data = {"char": json.loads(self.UP_EVENT.json())}
|
||||
self.dump_data(data, f"draw_card_up/{self.game_name}_up_char.json")
|
||||
self.dump_data(data, f"draw_card_up/{self.game_name}_up_char.json")
|
||||
|
||||
async def _update_info(self):
|
||||
info = {}
|
||||
@@ -220,17 +232,22 @@ class AzurHandle(BaseHandle[AzurChar]):
|
||||
|
||||
@staticmethod
|
||||
def parse_star(star: str) -> int:
|
||||
if star in {"舰娘头像外框普通.png", "舰娘头像外框白色.png"}:
|
||||
if star in ["舰娘头像外框普通.png", "舰娘头像外框白色.png"]:
|
||||
return 1
|
||||
elif star in {"舰娘头像外框稀有.png", "舰娘头像外框蓝色.png"}:
|
||||
elif star in ["舰娘头像外框稀有.png", "舰娘头像外框蓝色.png"]:
|
||||
return 2
|
||||
elif star in {"舰娘头像外框精锐.png", "舰娘头像外框紫色.png"}:
|
||||
elif star in ["舰娘头像外框精锐.png", "舰娘头像外框紫色.png"]:
|
||||
return 3
|
||||
elif star in {"舰娘头像外框超稀有.png", "舰娘头像外框金色.png"}:
|
||||
elif star in ["舰娘头像外框超稀有.png", "舰娘头像外框金色.png"]:
|
||||
return 4
|
||||
elif star in {"舰娘头像外框海上传奇.png", "舰娘头像外框彩色.png"}:
|
||||
elif star in ["舰娘头像外框海上传奇.png", "舰娘头像外框彩色.png"]:
|
||||
return 5
|
||||
elif star in {"舰娘头像外框最高方案.png", "舰娘头像外框决战方案.png", "舰娘头像外框超稀有META.png", "舰娘头像外框精锐META.png"}:
|
||||
elif star in [
|
||||
"舰娘头像外框最高方案.png",
|
||||
"舰娘头像外框决战方案.png",
|
||||
"舰娘头像外框超稀有META.png",
|
||||
"舰娘头像外框精锐META.png",
|
||||
]:
|
||||
return 6
|
||||
else:
|
||||
return 6
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import random
|
||||
from lxml import etree
|
||||
from typing import List, Tuple
|
||||
from PIL import ImageDraw
|
||||
from urllib.parse import unquote
|
||||
from nonebot.log import logger
|
||||
|
||||
from .base_handle import BaseHandle, BaseData
|
||||
from ..config import draw_config
|
||||
from ..util import remove_prohibited_str, cn2py, load_font
|
||||
from lxml import etree
|
||||
from nonebot.log import logger
|
||||
from PIL import ImageDraw
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from utils.image_utils import BuildImage
|
||||
|
||||
from ..config import draw_config
|
||||
from ..util import cn2py, load_font, remove_prohibited_str
|
||||
from .base_handle import BaseData, BaseHandle
|
||||
|
||||
|
||||
class BaChar(BaseData):
|
||||
pass
|
||||
@@ -66,17 +68,19 @@ class BaHandle(BaseHandle[BaChar]):
|
||||
bar = BuildImage(bar_w, bar_h, color="#6495ED")
|
||||
bg.paste(img, (sep_w, sep_h), alpha=True)
|
||||
bg.paste(bar, (sep_w, img_h - bar_h + sep_h), alpha=True)
|
||||
if (card.star == 1):
|
||||
if card.star == 1:
|
||||
star_path = str(self.img_path / "star-1.png")
|
||||
star_w = 15
|
||||
elif (card.star == 2):
|
||||
elif card.star == 2:
|
||||
star_path = str(self.img_path / "star-2.png")
|
||||
star_w = 30
|
||||
else:
|
||||
star_path = str(self.img_path / "star-3.png")
|
||||
star_w = 45
|
||||
star = BuildImage(star_w, star_h, background=star_path)
|
||||
bg.paste(star, (img_w // 2 - 15 * (card.star - 1) // 2, img_h - star_h), alpha=True)
|
||||
bg.paste(
|
||||
star, (img_w // 2 - 15 * (card.star - 1) // 2, img_h - star_h), alpha=True
|
||||
)
|
||||
text = card.name[:5] + "..." if len(card.name) > 6 else card.name
|
||||
font = load_font(fontsize=14)
|
||||
text_w, text_h = font.getsize(text)
|
||||
@@ -98,36 +102,38 @@ class BaHandle(BaseHandle[BaChar]):
|
||||
)
|
||||
for key, value in self.load_data().items()
|
||||
]
|
||||
|
||||
|
||||
def title2star(self, title: int):
|
||||
if title == 'Star-3.png':
|
||||
if title == "Star-3.png":
|
||||
return 3
|
||||
elif title == 'Star-2.png':
|
||||
elif title == "Star-2.png":
|
||||
return 2
|
||||
else:
|
||||
return 1
|
||||
|
||||
async def _update_info(self):
|
||||
info = {}
|
||||
url = "https://wiki.biligame.com/bluearchive/学生筛选"
|
||||
result = await self.get_url(url)
|
||||
url = "https://lonqie.github.io/SchaleDB/data/cn/students.min.json?v=49"
|
||||
result = (await AsyncHttpx.get(url)).json()
|
||||
if not result:
|
||||
logger.warning(f"更新 {self.game_name_cn} 出错")
|
||||
return
|
||||
else:
|
||||
dom = etree.HTML(result, etree.HTMLParser())
|
||||
char_list = dom.xpath("//div[@class='filters']/table[2]/tbody/tr")
|
||||
for char in char_list:
|
||||
for char in result:
|
||||
try:
|
||||
name = char.xpath("./td[2]/a/div/text()")[0]
|
||||
avatar = char.xpath("./td[1]/div/div/a/img/@data-src")[0]
|
||||
star_pic = char.xpath("./td[4]/img/@alt")[0]
|
||||
name = char["Name"]
|
||||
avatar = (
|
||||
"https://github.com/lonqie/SchaleDB/raw/main/images/student/icon/"
|
||||
+ char["CollectionTexture"]
|
||||
+ ".png"
|
||||
)
|
||||
star = char["StarGrade"]
|
||||
except IndexError:
|
||||
continue
|
||||
member_dict = {
|
||||
"头像": unquote(str(avatar)),
|
||||
"名称": remove_prohibited_str(name),
|
||||
"星级": self.title2star(star_pic),
|
||||
"头像": avatar,
|
||||
"名称": name,
|
||||
"星级": star,
|
||||
}
|
||||
info[member_dict["名称"]] = member_dict
|
||||
self.dump_data(info)
|
||||
@@ -146,5 +152,5 @@ class BaHandle(BaseHandle[BaChar]):
|
||||
)
|
||||
await self.download_img(
|
||||
"https://patchwiki.biligame.com/images/bluearchive/thumb/8/8a/577yv79x1rwxk8efdccpblo0lozl158.png/46px-Star-3.png",
|
||||
"star-3"
|
||||
)
|
||||
"star-3",
|
||||
)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import math
|
||||
import anyio
|
||||
import random
|
||||
import aiohttp
|
||||
import asyncio
|
||||
import aiofiles
|
||||
from PIL import Image
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Extra
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from typing import Dict, List, Optional, TypeVar, Generic, Tuple
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.message_builder import image
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
from nonebot.log import logger
|
||||
import asyncio
|
||||
|
||||
from configs.path_config import DATA_PATH
|
||||
from utils.message_builder import image
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -50,29 +50,25 @@ class UpEvent(BaseModel):
|
||||
start_time: Optional[datetime] # 开始时间
|
||||
end_time: Optional[datetime] # 结束时间
|
||||
up_char: List[UpChar] # up对象
|
||||
up_name: str = "" # up名称
|
||||
|
||||
|
||||
TC = TypeVar("TC", bound="BaseData")
|
||||
|
||||
|
||||
class BaseHandle(Generic[TC]):
|
||||
def __init__(self, game_name: str, game_name_cn: str, game_card_color: str = "#ffffff"):
|
||||
def __init__(self, game_name: str, game_name_cn: str):
|
||||
self.game_name = game_name
|
||||
self.game_name_cn = game_name_cn
|
||||
self.max_star = 1 # 最大星级
|
||||
self.data_path = DRAW_PATH
|
||||
self.img_path = IMAGE_PATH / f"draw_card/{self.game_name}"
|
||||
self.up_path = DRAW_PATH / "draw_card_up"
|
||||
self.game_card_color: str = "#ffffff"
|
||||
self.data_path = DATA_PATH / "draw_card"
|
||||
self.img_path = DRAW_PATH / f"{self.game_name}"
|
||||
self.up_path = DATA_PATH / "draw_card" / "draw_card_up"
|
||||
self.img_path.mkdir(parents=True, exist_ok=True)
|
||||
self.up_path.mkdir(parents=True, exist_ok=True)
|
||||
self.data_files: List[str] = [f"{self.game_name}.json"]
|
||||
self.game_card_color: str = game_card_color
|
||||
|
||||
async def draw(self, count: int, **kwargs) -> Message:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, self._draw, count)
|
||||
|
||||
def _draw(self, count: int, **kwargs) -> Message:
|
||||
def draw(self, count: int, **kwargs) -> Message:
|
||||
index2card = self.get_cards(count, **kwargs)
|
||||
cards = [card[0] for card in index2card]
|
||||
result = self.format_result(index2card)
|
||||
@@ -173,7 +169,6 @@ class BaseHandle(Generic[TC]):
|
||||
card_imgs: List[BuildImage] = []
|
||||
for card, num in zip(card_list, num_list):
|
||||
card_img = self.generate_card_img(card)
|
||||
|
||||
# 数量 > 1 时加数字上标
|
||||
if num > 1:
|
||||
label = circled_number(num)
|
||||
@@ -274,7 +269,7 @@ class BaseHandle(Generic[TC]):
|
||||
return True
|
||||
try:
|
||||
async with self.session.get(url, timeout=10) as response:
|
||||
async with aiofiles.open(str(img_path), "wb") as f:
|
||||
async with await anyio.open_file(img_path, "wb") as f:
|
||||
await f.write(await response.read())
|
||||
return True
|
||||
except TimeoutError:
|
||||
|
||||
@@ -6,10 +6,10 @@ from urllib.parse import unquote
|
||||
from typing import List, Optional, Tuple
|
||||
from pydantic import ValidationError
|
||||
from datetime import datetime, timedelta
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from utils.message_builder import image
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
from nonebot.log import logger
|
||||
import asyncio
|
||||
|
||||
from utils.message_builder import image
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -37,21 +37,23 @@ class GenshinArms(GenshinData):
|
||||
|
||||
class GenshinHandle(BaseHandle[GenshinData]):
|
||||
def __init__(self):
|
||||
super().__init__("genshin", "原神", "#ebebeb")
|
||||
super().__init__("genshin", "原神")
|
||||
self.data_files.append("genshin_arms.json")
|
||||
self.max_star = 5
|
||||
self.game_card_color = "#ebebeb"
|
||||
self.config = draw_config.genshin
|
||||
|
||||
self.ALL_CHAR: List[GenshinData] = []
|
||||
self.ALL_ARMS: List[GenshinData] = []
|
||||
self.UP_CHAR: Optional[UpEvent] = None
|
||||
self.UP_CHAR_LIST: Optional[UpEvent] = []
|
||||
self.UP_ARMS: Optional[UpEvent] = None
|
||||
|
||||
self.count_manager = GenshinCountManager((10, 90), ("4", "5"), 180)
|
||||
|
||||
# 抽取卡池
|
||||
def get_card(
|
||||
self, pool_name: str, mode: int = 1, add: float = 0.0, is_up: bool = False
|
||||
self, pool_name: str, mode: int = 1, add: float = 0.0, is_up: bool = False, card_index: int = 0
|
||||
):
|
||||
"""
|
||||
mode 1:普通抽 2:四星保底 3:五星保底
|
||||
@@ -74,7 +76,7 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
star = 5
|
||||
|
||||
if pool_name == "char":
|
||||
up_event = self.UP_CHAR
|
||||
up_event = self.UP_CHAR_LIST[card_index]
|
||||
all_list = self.ALL_CHAR + [
|
||||
x for x in self.ALL_ARMS if x.star == star and x.star < 5
|
||||
]
|
||||
@@ -105,14 +107,13 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
return acquire_char
|
||||
|
||||
def get_cards(
|
||||
self, count: int, user_id: int, pool_name: str
|
||||
self, count: int, user_id: int, pool_name: str, card_index: int = 0
|
||||
) -> List[Tuple[GenshinData, int]]:
|
||||
card_list = [] # 获取角色列表
|
||||
add = 0.0
|
||||
count_manager = self.count_manager
|
||||
count_manager.check_timeout(user_id) # 检查上次抽卡次数是否超时
|
||||
count_manager.check_count(user_id, count) # 检查次数累计
|
||||
pool = self.UP_CHAR if pool_name == "char" else self.UP_ARMS
|
||||
pool = self.UP_CHAR_LIST[card_index] if pool_name == "char" else self.UP_ARMS
|
||||
for i in range(count):
|
||||
count_manager.increase(user_id)
|
||||
star = count_manager.check(user_id) # 是否有四星或五星保底
|
||||
@@ -123,13 +124,13 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
add += draw_config.genshin.I72_ADD
|
||||
if star:
|
||||
if star == 4:
|
||||
card = self.get_card(pool_name, 2, add=add)
|
||||
card = self.get_card(pool_name, 2, add=add, card_index=card_index)
|
||||
else:
|
||||
card = self.get_card(
|
||||
pool_name, 3, add, count_manager.is_up(user_id)
|
||||
pool_name, 3, add, count_manager.is_up(user_id), card_index=card_index
|
||||
)
|
||||
else:
|
||||
card = self.get_card(pool_name, 1, add, count_manager.is_up(user_id))
|
||||
card = self.get_card(pool_name, 1, add, count_manager.is_up(user_id), card_index=card_index)
|
||||
# print(f"{count_manager.get_user_count(user_id)}:",
|
||||
# count_manager.get_user_five_index(user_id), star, card.star, add)
|
||||
# 四星角色
|
||||
@@ -147,7 +148,6 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
else:
|
||||
count_manager.set_is_up(user_id, False)
|
||||
card_list.append((card, count_manager.get_user_count(user_id)))
|
||||
count_manager.update_time(user_id)
|
||||
return card_list
|
||||
|
||||
def generate_card_img(self, card: GenshinData) -> BuildImage:
|
||||
@@ -188,11 +188,11 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
bg.paste(star, (sep_w + int((frame_w - star.width) / 2), sep_h - 6), alpha=True)
|
||||
return bg
|
||||
|
||||
def format_pool_info(self, pool_name: str) -> str:
|
||||
def format_pool_info(self, pool_name: str, card_index: int = 0) -> str:
|
||||
info = ""
|
||||
up_event = None
|
||||
if pool_name == "char":
|
||||
up_event = self.UP_CHAR
|
||||
up_event = self.UP_CHAR_LIST[card_index]
|
||||
elif pool_name == "arms":
|
||||
up_event = self.UP_ARMS
|
||||
if up_event:
|
||||
@@ -205,15 +205,18 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
info = f"当前up池:{up_event.title}\n{info}"
|
||||
return info.strip()
|
||||
|
||||
async def draw(self, count: int, user_id: int, pool_name: str = "", **kwargs) -> Message:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, self._draw, count, user_id, pool_name)
|
||||
|
||||
def _draw(self, count: int, user_id: int, pool_name: str = "", **kwargs) -> Message:
|
||||
index2cards = self.get_cards(count, user_id, pool_name)
|
||||
def draw(self, count: int, user_id: int, pool_name: str = "", **kwargs) -> Message:
|
||||
card_index = 0
|
||||
if "1" in pool_name:
|
||||
card_index = 1
|
||||
pool_name = pool_name.replace("1", "")
|
||||
index2cards = self.get_cards(count, user_id, pool_name, card_index)
|
||||
cards = [card[0] for card in index2cards]
|
||||
up_event = None
|
||||
if pool_name == "char":
|
||||
up_event = self.UP_CHAR
|
||||
if card_index == 1 and len(self.UP_CHAR_LIST) == 1:
|
||||
return Message("当前没有第二个角色UP池")
|
||||
up_event = self.UP_CHAR_LIST[card_index]
|
||||
elif pool_name == "arms":
|
||||
up_event = self.UP_ARMS
|
||||
up_list = [x.name for x in up_event.up_char] if up_event else []
|
||||
@@ -225,7 +228,7 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
)
|
||||
result += f"\n距离保底发还剩 {self.count_manager.get_user_guarantee_count(user_id)} 抽"
|
||||
# result += "\n【五星:0.6%,四星:5.1%,第72抽开始五星概率每抽加0.585%】"
|
||||
pool_info = self.format_pool_info(pool_name)
|
||||
pool_info = self.format_pool_info(pool_name, card_index)
|
||||
img = self.generate_img(cards)
|
||||
bk = BuildImage(img.w, img.h + 50, font_size=20, color="#ebebeb")
|
||||
bk.paste(img)
|
||||
@@ -255,17 +258,20 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
def load_up_char(self):
|
||||
try:
|
||||
data = self.load_data(f"draw_card_up/{self.game_name}_up_char.json")
|
||||
self.UP_CHAR = UpEvent.parse_obj(data.get("char", {}))
|
||||
self.UP_CHAR_LIST.append(UpEvent.parse_obj(data.get("char", {})))
|
||||
self.UP_CHAR_LIST.append(UpEvent.parse_obj(data.get("char1", {})))
|
||||
self.UP_ARMS = UpEvent.parse_obj(data.get("arms", {}))
|
||||
except ValidationError:
|
||||
logger.warning(f"{self.game_name}_up_char 解析出错")
|
||||
|
||||
def dump_up_char(self):
|
||||
if self.UP_CHAR and self.UP_ARMS:
|
||||
if self.UP_CHAR_LIST and self.UP_ARMS:
|
||||
data = {
|
||||
"char": json.loads(self.UP_CHAR.json()),
|
||||
"char": json.loads(self.UP_CHAR_LIST[0].json()),
|
||||
"arms": json.loads(self.UP_ARMS.json()),
|
||||
}
|
||||
if len(self.UP_CHAR_LIST) > 1:
|
||||
data['char1'] = json.loads(self.UP_CHAR_LIST[1].json())
|
||||
self.dump_data(data, f"draw_card_up/{self.game_name}_up_char.json")
|
||||
|
||||
async def _update_info(self):
|
||||
@@ -359,6 +365,7 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
await self.update_up_char()
|
||||
|
||||
async def update_up_char(self):
|
||||
self.UP_CHAR_LIST = []
|
||||
url = "https://wiki.biligame.com/ys/祈愿"
|
||||
result = await self.get_url(url)
|
||||
if not result:
|
||||
@@ -399,14 +406,15 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
for name in star4_list
|
||||
],
|
||||
)
|
||||
if index == 0:
|
||||
self.UP_CHAR = up_event
|
||||
elif index == 1:
|
||||
if '神铸赋形' not in title:
|
||||
self.UP_CHAR_LIST.append(up_event)
|
||||
else:
|
||||
self.UP_ARMS = up_event
|
||||
if self.UP_CHAR and self.UP_ARMS:
|
||||
if self.UP_CHAR_LIST and self.UP_ARMS:
|
||||
self.dump_up_char()
|
||||
char_title = " & ".join([x.title for x in self.UP_CHAR_LIST])
|
||||
logger.info(
|
||||
f"成功获取{self.game_name_cn}当前up信息...当前up池: {self.UP_CHAR.title} & {self.UP_ARMS.title}"
|
||||
f"成功获取{self.game_name_cn}当前up信息...当前up池: {char_title} & {self.UP_ARMS.title}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"{self.game_name_cn}UP更新出错 {type(e)}:{e}")
|
||||
@@ -418,12 +426,23 @@ class GenshinHandle(BaseHandle[GenshinData]):
|
||||
async def _reload_pool(self) -> Optional[Message]:
|
||||
await self.update_up_char()
|
||||
self.load_up_char()
|
||||
if self.UP_CHAR and self.UP_ARMS:
|
||||
if self.UP_CHAR_LIST and self.UP_ARMS:
|
||||
if len(self.UP_CHAR_LIST) > 1:
|
||||
return Message(
|
||||
Message.template("重载成功!\n当前UP池子:{} & {} & {}{:image}{:image}{:image}").format(
|
||||
self.UP_CHAR_LIST[0].title,
|
||||
self.UP_CHAR_LIST[1].title,
|
||||
self.UP_ARMS.title,
|
||||
self.UP_CHAR_LIST[0].pool_img,
|
||||
self.UP_CHAR_LIST[1].pool_img,
|
||||
self.UP_ARMS.pool_img,
|
||||
)
|
||||
)
|
||||
return Message(
|
||||
Message.template("重载成功!\n当前UP池子:{} & {}{:image}{:image}").format(
|
||||
self.UP_CHAR.title,
|
||||
char_title,
|
||||
self.UP_ARMS.title,
|
||||
self.UP_CHAR.pool_img,
|
||||
self.UP_CHAR_LIST[0].pool_img,
|
||||
self.UP_ARMS.pool_img,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -7,10 +7,10 @@ from datetime import datetime
|
||||
from urllib.parse import unquote
|
||||
from typing import List, Optional, Tuple
|
||||
from pydantic import ValidationError
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from utils.message_builder import image
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
from nonebot.log import logger
|
||||
import asyncio
|
||||
|
||||
from utils.message_builder import image
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -137,10 +137,7 @@ class GuardianHandle(BaseHandle[GuardianData]):
|
||||
info = f"当前up池:{up_event.title}\n{info}"
|
||||
return info.strip()
|
||||
|
||||
async def draw(self, count: int, pool_name: str, **kwargs) -> Message:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, self._draw, count, pool_name)
|
||||
|
||||
def _draw(self, count: int, pool_name: str, **kwargs) -> Message:
|
||||
def draw(self, count: int, pool_name: str, **kwargs) -> Message:
|
||||
index2card = self.get_cards(count, pool_name)
|
||||
cards = [card[0] for card in index2card]
|
||||
up_event = self.UP_CHAR if pool_name == "char" else self.UP_ARMS
|
||||
@@ -238,9 +235,12 @@ class GuardianHandle(BaseHandle[GuardianData]):
|
||||
char_list = dom.xpath("//table[@id='CardSelectTr']/tbody/tr")
|
||||
for char in char_list:
|
||||
try:
|
||||
name = char.xpath("./td[1]/a/@title")[0]
|
||||
avatar = char.xpath("./td[1]/a/img/@src")[0]
|
||||
star = char.xpath("./td[1]/span/img/@alt")[0]
|
||||
# name = char.xpath("./td[1]/a/@title")[0]
|
||||
# avatar = char.xpath("./td[1]/a/img/@src")[0]
|
||||
# star = char.xpath("./td[1]/span/img/@alt")[0]
|
||||
name = char.xpath("./th[1]/a[1]/@title")[0]
|
||||
avatar = char.xpath("./th[1]/a/img/@src")[0]
|
||||
star = char.xpath("./th[1]/span/img/@alt")[0]
|
||||
except IndexError:
|
||||
continue
|
||||
member_dict = {
|
||||
|
||||
@@ -8,10 +8,10 @@ from datetime import datetime
|
||||
from urllib.parse import unquote
|
||||
from typing import List, Optional, Tuple
|
||||
from pydantic import ValidationError
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from utils.message_builder import image
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
from nonebot.log import logger
|
||||
import asyncio
|
||||
|
||||
from utils.message_builder import image
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -40,9 +40,10 @@ class PrettyCard(PrettyData):
|
||||
|
||||
class PrettyHandle(BaseHandle[PrettyData]):
|
||||
def __init__(self):
|
||||
super().__init__("pretty", "赛马娘", "#eff2f5")
|
||||
super().__init__("pretty", "赛马娘")
|
||||
self.data_files.append("pretty_card.json")
|
||||
self.max_star = 3
|
||||
self.game_card_color = "#eff2f5"
|
||||
self.config = draw_config.pretty
|
||||
|
||||
self.ALL_CHAR: List[PrettyChar] = []
|
||||
@@ -129,10 +130,7 @@ class PrettyHandle(BaseHandle[PrettyData]):
|
||||
info = f"当前up池:{up_event.title}\n{info}"
|
||||
return info.strip()
|
||||
|
||||
async def draw(self, count: int, pool_name: str, **kwargs) -> Message:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, self._draw, count, pool_name)
|
||||
|
||||
def _draw(self, count: int, pool_name: str, **kwargs) -> Message:
|
||||
def draw(self, count: int, pool_name: str, **kwargs) -> Message:
|
||||
pool_name = "char" if not pool_name else pool_name
|
||||
index2card = self.get_cards(count, pool_name)
|
||||
cards = [card[0] for card in index2card]
|
||||
@@ -350,52 +348,48 @@ class PrettyHandle(BaseHandle[PrettyData]):
|
||||
char_img = ""
|
||||
card_img = ""
|
||||
up_chars = []
|
||||
up_chars_name = []
|
||||
up_cards = []
|
||||
up_cards_name = []
|
||||
soup = BeautifulSoup(result, "lxml")
|
||||
heads = soup.find_all("span", {"class": "mw-headline"})
|
||||
for head in heads:
|
||||
if "时间" in head.text or "期间" in head.text:
|
||||
if "时间" in head.text:
|
||||
time = head.find_next("p").text.split("\n")[0]
|
||||
if "~" in time:
|
||||
start, end = time.split("~")
|
||||
start_time = dateparser.parse(start)
|
||||
end_time = dateparser.parse(end)
|
||||
elif "赛马娘" in head.text:
|
||||
char_img = head.find_next("center").find("img")[
|
||||
char_img = head.find_next("a", {"class": "image"}).find("img")[
|
||||
"src"
|
||||
]
|
||||
lines = str(head.find_next("p").text).split("\n")
|
||||
chars = [
|
||||
line
|
||||
for line in lines
|
||||
if "★" in line and "【" in line and "】" in line
|
||||
if "★" in line and "(" in line and ")" in line
|
||||
]
|
||||
for char in set(chars): # list去重
|
||||
for char in chars:
|
||||
star = char.count("★")
|
||||
name = re.split(r"[【】]", char)[-2].strip()
|
||||
name = re.split(r"[()]", char)[-2].strip()
|
||||
up_chars.append(
|
||||
UpChar(name=name, star=star, limited=False, zoom=70)
|
||||
)
|
||||
up_chars_name.append(name)
|
||||
elif "支援卡" in head.text:
|
||||
card_img = head.find_next("center").find("img")[
|
||||
card_img = head.find_next("a", {"class": "image"}).find("img")[
|
||||
"src"
|
||||
]
|
||||
lines = str(head.find_next("p").text).split("\n")
|
||||
cards = [
|
||||
line
|
||||
for line in lines
|
||||
if "R" in line and "【" in line and "】" in line
|
||||
if "R" in line and "(" in line and ")" in line
|
||||
]
|
||||
for card in cards:
|
||||
star = 3 if "SSR" in card else 2 if "SR" in card else 1
|
||||
name = re.split(r"[【】]", card)[-2].strip()
|
||||
name = re.split(r"[()]", card)[-2].strip()
|
||||
up_cards.append(
|
||||
UpChar(name=name, star=star, limited=False, zoom=70)
|
||||
)
|
||||
up_cards_name.append(name)
|
||||
if start_time and end_time:
|
||||
if start_time <= datetime.now() <= end_time:
|
||||
self.UP_CHAR = UpEvent(
|
||||
@@ -404,7 +398,6 @@ class PrettyHandle(BaseHandle[PrettyData]):
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
up_char=up_chars,
|
||||
up_name=up_chars_name,
|
||||
)
|
||||
self.UP_CARD = UpEvent(
|
||||
title=title,
|
||||
@@ -412,7 +405,6 @@ class PrettyHandle(BaseHandle[PrettyData]):
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
up_char=up_cards,
|
||||
up_name=up_cards_name,
|
||||
)
|
||||
self.dump_up_char()
|
||||
logger.info(f"成功获取{self.game_name_cn}当前up信息...当前up池: {title}")
|
||||
@@ -424,10 +416,9 @@ class PrettyHandle(BaseHandle[PrettyData]):
|
||||
self.load_up_char()
|
||||
if self.UP_CHAR and self.UP_CARD:
|
||||
return Message(
|
||||
Message.template("重载成功!\n当前UP池子:{}{:image}\n当前支援卡池子:{}{:image}").format(
|
||||
self.UP_CHAR.up_name,
|
||||
Message.template("重载成功!\n当前UP池子:{}{:image}{:image}").format(
|
||||
self.UP_CHAR.title,
|
||||
self.UP_CHAR.pool_img,
|
||||
self.UP_CARD.up_name,
|
||||
self.UP_CARD.pool_img,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import re
|
||||
import random
|
||||
import dateparser
|
||||
from lxml import etree
|
||||
from PIL import ImageDraw
|
||||
import re
|
||||
from datetime import datetime
|
||||
from urllib.parse import unquote
|
||||
from typing import List, Optional, Tuple
|
||||
from pydantic import ValidationError
|
||||
from nonebot.adapters.onebot.v11 import Message
|
||||
from utils.message_builder import image
|
||||
from urllib.parse import unquote
|
||||
|
||||
import dateparser
|
||||
from PIL import ImageDraw
|
||||
from lxml import etree
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
from nonebot.log import logger
|
||||
import asyncio
|
||||
from pydantic import ValidationError
|
||||
|
||||
from utils.message_builder import image
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -104,17 +105,18 @@ class PrtsHandle(BaseHandle[Operator]):
|
||||
info = f"当前up池: {self.UP_EVENT.title}\n{info}"
|
||||
return info.strip()
|
||||
|
||||
async def draw(self, count: int, **kwargs) -> Message:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, self._draw, count)
|
||||
|
||||
def _draw(self, count: int, **kwargs) -> Message:
|
||||
def draw(self, count: int, **kwargs) -> Message:
|
||||
index2card = self.get_cards(count)
|
||||
"""这里cards修复了抽卡图文不符的bug"""
|
||||
cards = [card[0] for card in index2card]
|
||||
up_list = [x.name for x in self.UP_EVENT.up_char] if self.UP_EVENT else []
|
||||
result = self.format_result(index2card, up_list=up_list)
|
||||
pool_info = self.format_pool_info()
|
||||
return pool_info + image(b64=self.generate_img(cards).pic2bs4()) + result
|
||||
return (
|
||||
pool_info
|
||||
+ image(b64=self.generate_img(cards).pic2bs4())
|
||||
+ result
|
||||
)
|
||||
|
||||
def generate_card_img(self, card: Operator) -> BuildImage:
|
||||
sep_w = 5
|
||||
@@ -177,6 +179,7 @@ class PrtsHandle(BaseHandle[Operator]):
|
||||
self.dump_data(data, f"draw_card_up/{self.game_name}_up_char.json")
|
||||
|
||||
async def _update_info(self):
|
||||
"""更新信息"""
|
||||
info = {}
|
||||
url = "https://wiki.biligame.com/arknights/干员数据表"
|
||||
result = await self.get_url(url)
|
||||
@@ -288,10 +291,7 @@ class PrtsHandle(BaseHandle[Operator]):
|
||||
up_chars.append(
|
||||
UpChar(name=name, star=star, limited=False, zoom=zoom)
|
||||
)
|
||||
if start_time <= datetime.now() <= end_time: # 跳过过时的卡池
|
||||
break # 这里break会导致个问题:如果一个公告里有两个池子,会漏掉下面的池子,比如 5.19 的定向寻访。但目前我也没啥好想法解决
|
||||
chars: List[str] = [] # 查找下一个卡池之前清空 chars
|
||||
up_chars = [] # 查找下一个卡池之前清空 up_chars
|
||||
break # 这里break会导致个问题:如果一个公告里有两个池子,会漏掉下面的池子,比如 5.19 的定向寻访。但目前我也没啥好想法解决
|
||||
if title and start_time and end_time:
|
||||
if start_time <= datetime.now() <= end_time:
|
||||
self.UP_EVENT = UpEvent(
|
||||
@@ -309,6 +309,6 @@ class PrtsHandle(BaseHandle[Operator]):
|
||||
await self.update_up_char()
|
||||
self.load_up_char()
|
||||
if self.UP_EVENT:
|
||||
return f"重载成功!\n当前UP池子:{self.UP_EVENT.title}" + image(
|
||||
return f"重载成功!\n当前UP池子:{self.UP_EVENT.title}" + MessageSegment.image(
|
||||
self.UP_EVENT.pool_img
|
||||
)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
from nonebot.internal.rule import Rule
|
||||
|
||||
from configs.config import Config
|
||||
|
||||
|
||||
def rule(game) -> Rule:
|
||||
async def _rule() -> bool:
|
||||
return Config.get_config("draw_card", game.config_name, True)
|
||||
|
||||
return Rule(_rule)
|
||||
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import platform
|
||||
import pypinyin
|
||||
from pathlib import Path
|
||||
from PIL.ImageFont import FreeTypeFont
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from PIL.Image import Image as IMG
|
||||
|
||||
from configs.path_config import FONT_PATH
|
||||
|
||||
dir_path = Path(__file__).parent.absolute()
|
||||
|
||||
|
||||
def cn2py(word) -> str:
|
||||
"""保存声调,防止出现类似方舟干员红与吽拼音相同声调不同导致红照片无法保存的问题"""
|
||||
temp = ""
|
||||
for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
|
||||
for i in pypinyin.pinyin(word, style=pypinyin.Style.TONE3):
|
||||
temp += "".join(i)
|
||||
return temp
|
||||
|
||||
@@ -26,9 +31,9 @@ def remove_prohibited_str(name: str) -> str:
|
||||
return name
|
||||
|
||||
|
||||
def load_font(font_name: str = "msyh.ttf", fontsize: int = 16) -> FreeTypeFont:
|
||||
def load_font(fontname: str = "msyh.ttf", fontsize: int = 16) -> FreeTypeFont:
|
||||
return ImageFont.truetype(
|
||||
str(FONT_PATH / f"{font_name}"), fontsize, encoding="utf-8"
|
||||
str(FONT_PATH / f"{fontname}"), fontsize, encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ async def _():
|
||||
gl = [g["group_id"] for g in gl]
|
||||
msg_list, code = await get_epic_free(bot, "Group")
|
||||
for g in gl:
|
||||
if await group_manager.check_group_task_status(g, "epic_free_game"):
|
||||
if group_manager.check_task_status("epic_free_game", g):
|
||||
try:
|
||||
if msg_list and code == 200:
|
||||
await bot.send_group_forward_msg(group_id=g, messages=msg_list)
|
||||
|
||||
@@ -24,6 +24,22 @@ async def get_epic_game():
|
||||
logger.error(f"Epic 访问接口错误 {type(e)}:{e}")
|
||||
return None
|
||||
|
||||
# 此处用于获取游戏简介
|
||||
async def get_epic_game_desp(name):
|
||||
desp_url = "https://store-content-ipv4.ak.epicgames.com/api/zh-CN/content/products/" + str(name)
|
||||
headers = {
|
||||
"Referer": "https://store.epicgames.com/zh-CN/p/" + str(name),
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36",
|
||||
}
|
||||
try:
|
||||
res = await AsyncHttpx.get(desp_url, headers=headers, timeout=10)
|
||||
res_json = res.json()
|
||||
gamesDesp = res_json["pages"][0]["data"]["about"]
|
||||
return gamesDesp
|
||||
except Exception as e:
|
||||
logger.error(f"Epic 访问接口错误 {type(e)}:{e}")
|
||||
return None
|
||||
|
||||
# 获取 Epic Game Store 免费游戏信息
|
||||
# 处理免费游戏的信息方法借鉴 pip 包 epicstore_api 示例
|
||||
@@ -95,7 +111,10 @@ async def get_epic_free(bot: Bot, type_event: str):
|
||||
game_dev = pair["value"]
|
||||
if pair["key"] == "publisherName":
|
||||
game_pub = pair["value"]
|
||||
game_desp = game["description"]
|
||||
if game.get("productSlug"):
|
||||
gamesDesp = await get_epic_game_desp(game["productSlug"])
|
||||
#game_desp = game["description"]
|
||||
game_desp = gamesDesp["description"]
|
||||
try:
|
||||
end_date_iso = game["promotions"]["promotionalOffers"][0][
|
||||
"promotionalOffers"
|
||||
@@ -168,4 +187,4 @@ async def get_epic_free(bot: Bot, type_event: str):
|
||||
except TypeError as e:
|
||||
# logger.info(str(e))
|
||||
pass
|
||||
return msg_list, 200
|
||||
return msg_list, 200
|
||||
+15
-6
@@ -1,6 +1,4 @@
|
||||
from io import BytesIO
|
||||
import imagehash
|
||||
from PIL import Image
|
||||
from utils.image_utils import get_img_hash
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from configs.path_config import TEMP_PATH
|
||||
import random
|
||||
@@ -10,6 +8,7 @@ from utils.utils import get_message_img, get_message_text
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from configs.config import Config
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from services.log import logger
|
||||
from configs.config import NICKNAME
|
||||
|
||||
|
||||
@@ -91,7 +90,7 @@ async def _(event: GroupMessageEvent):
|
||||
if not img and not msg:
|
||||
return
|
||||
if img:
|
||||
img_hash = await get_fudu_img_hash(img[0])
|
||||
img_hash = await get_fudu_img_hash(img[0],event.group_id)
|
||||
else:
|
||||
img_hash = ""
|
||||
add_msg = msg + "|-|" + img_hash
|
||||
@@ -124,5 +123,15 @@ async def _(event: GroupMessageEvent):
|
||||
await fudu.finish("[[_task|fudu]]" + rst)
|
||||
|
||||
|
||||
async def get_fudu_img_hash(url):
|
||||
return str(imagehash.average_hash(Image.open(BytesIO((await AsyncHttpx.get(url)).content))))
|
||||
async def get_fudu_img_hash(url, group_id):
|
||||
try:
|
||||
if await AsyncHttpx.download_file(
|
||||
url, TEMP_PATH / f"compare_{group_id}_img.jpg"
|
||||
):
|
||||
img_hash = get_img_hash(TEMP_PATH / f"compare_{group_id}_img.jpg")
|
||||
return str(img_hash)
|
||||
else:
|
||||
logger.warning(f"复读下载图片失败...")
|
||||
except Exception as e:
|
||||
logger.warning(f"复读读取图片Hash出错 {type(e)}:{e}")
|
||||
return ""
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import nonebot
|
||||
|
||||
nonebot.load_plugins("plugins/genshin")
|
||||
|
||||
nonebot.load_plugins(str(Path(__file__).parent.resolve()))
|
||||
|
||||
@@ -71,5 +71,5 @@ async def _():
|
||||
if alc_img:
|
||||
mes = "[[_task|genshin_alc]]" + alc_img + "\n ※ 黄历数据来源于 genshin.pub"
|
||||
for gid in gl:
|
||||
if await group_manager.check_group_task_status(gid, "genshin_alc"):
|
||||
if group_manager.check_group_task_status(gid, "genshin_alc"):
|
||||
await bot.send_group_msg(group_id=int(gid), message="" + mes)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from configs.path_config import IMAGE_PATH, TEXT_PATH
|
||||
from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH
|
||||
from utils.image_utils import BuildImage
|
||||
from typing import Tuple, List
|
||||
from math import sqrt, pow
|
||||
@@ -118,7 +118,7 @@ class Map:
|
||||
self._generate_best_route()
|
||||
self.map.crop((min_width, min_height, max_width, max_height))
|
||||
rand = random.randint(1, 10000)
|
||||
self.map.save(f"{TEXT_PATH}/genshin_map_{rand}.png")
|
||||
self.map.save(f"{TEMP_PATH}/genshin_map_{rand}.png")
|
||||
return rand
|
||||
|
||||
# 资源数量
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import Tuple, Optional, List
|
||||
from configs.path_config import IMAGE_PATH, TEXT_PATH
|
||||
from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH
|
||||
from utils.message_builder import image
|
||||
from services.log import logger
|
||||
from utils.image_utils import BuildImage
|
||||
@@ -57,7 +57,7 @@ async def query_resource(resource_name: str) -> str:
|
||||
None, map_.generate_resource_icon_in_map
|
||||
)
|
||||
return (
|
||||
f"{image(f'genshin_map_{rand}.png', 'temp')}"
|
||||
f"{image(TEMP_PATH / f'genshin_map_{rand}.png')}"
|
||||
f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
from configs.config import Config
|
||||
import nonebot
|
||||
|
||||
@@ -26,7 +28,7 @@ Config.add_plugin_config(
|
||||
"5"
|
||||
)
|
||||
|
||||
nonebot.load_plugins("plugins/genshin/query_user")
|
||||
nonebot.load_plugins(str(Path(__file__).parent.resolve()))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
|
||||
from services.log import logger
|
||||
from .data_source import get_user_memo, get_memo
|
||||
from .._models import Genshin
|
||||
from nonebot.plugin import export
|
||||
|
||||
|
||||
__zx_plugin_name__ = "原神便笺查询"
|
||||
@@ -28,10 +27,6 @@ __plugin_settings__ = {
|
||||
__plugin_block_limit__ = {}
|
||||
|
||||
|
||||
export = export()
|
||||
|
||||
export.get_memo = get_memo
|
||||
|
||||
query_memo_matcher = on_command("原神便签查询", aliases={"原神便笺查询", "yss"}, priority=5, block=True)
|
||||
|
||||
|
||||
|
||||
@@ -234,7 +234,7 @@ def get_home_data_image(home_data_list: List[Dict]) -> BuildImage:
|
||||
画出家园数据
|
||||
:param home_data_list: 家园列表
|
||||
"""
|
||||
h = 130 + 340 * 4
|
||||
h = 130 + 340 * len(home_data_list)
|
||||
region = BuildImage(
|
||||
550, h, color="#E3DBD1", font="HYWenHei-85W.ttf", font_size=40
|
||||
)
|
||||
|
||||
@@ -19,7 +19,9 @@ import pytz
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
|
||||
get_memo = require("query_memo").get_memo
|
||||
require("query_memo")
|
||||
|
||||
from ..query_memo import get_memo
|
||||
|
||||
|
||||
global_map = {}
|
||||
|
||||
@@ -101,7 +101,7 @@ cases_matcher_group = MatcherGroup(priority=5, permission=GROUP, block=True)
|
||||
|
||||
k_open_case = cases_matcher_group.on_command("开箱")
|
||||
|
||||
reload_count = cases_matcher_group.on_command("重置开箱")
|
||||
reload_count = cases_matcher_group.on_command("重置开箱",permission=SUPERUSER)
|
||||
|
||||
|
||||
@reload_count.handle()
|
||||
|
||||
@@ -31,7 +31,7 @@ async def open_case(user_qq: int, group: int, case_name: str = "狂牙大行动"
|
||||
async with db.transaction():
|
||||
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
|
||||
# 一天次数上限
|
||||
if user.today_open_total > int(
|
||||
if user.today_open_total >= int(
|
||||
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
|
||||
+ int(impression)
|
||||
/ Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
|
||||
@@ -155,7 +155,7 @@ async def open_shilian_case(user_qq: int, group: int, case_name: str, num: int =
|
||||
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
|
||||
+ int(impression) / Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
|
||||
)
|
||||
if user.today_open_total == max_count:
|
||||
if user.today_open_total >= max_count:
|
||||
return _handle_is_MAX_COUNT()
|
||||
if max_count - user.today_open_total < num:
|
||||
return (
|
||||
|
||||
@@ -73,7 +73,7 @@ async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
|
||||
"page_num": f"{i}",
|
||||
"search": skin,
|
||||
}
|
||||
res = await AsyncHttpx.get(url, params=parameter)
|
||||
res = await AsyncHttpx.get(url, params=parameter, cookies=cookie)
|
||||
data = res.json()["data"][
|
||||
"items"
|
||||
]
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from nonebot import on_message
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, ActionFailed
|
||||
|
||||
from utils.manager import group_manager
|
||||
from utils.utils import get_message_json, get_local_proxy, is_number, get_message_text
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from utils.message_builder import image
|
||||
@@ -34,7 +36,10 @@ Config.add_plugin_config(
|
||||
)
|
||||
|
||||
|
||||
parse_bilibili_json = on_message(priority=1, permission=GROUP, block=False)
|
||||
async def plugin_on_checker(event: GroupMessageEvent) -> bool:
|
||||
return group_manager.get_plugin_status("parse_bilibili_json", event.group_id)
|
||||
|
||||
parse_bilibili_json = on_message(priority=1, permission=GROUP, block=False, rule=plugin_on_checker)
|
||||
|
||||
_tmp = {}
|
||||
|
||||
@@ -124,7 +129,7 @@ async def _(event: GroupMessageEvent):
|
||||
url,
|
||||
timeout=7,
|
||||
) as response:
|
||||
url = str(response.url).split("?")[0]
|
||||
url = (str(response.url).split("?")[0]).strip("/")
|
||||
bvid = url.split("/")[-1]
|
||||
vd_info = await video.get_video_base_info(bvid)
|
||||
if vd_info:
|
||||
|
||||
@@ -50,7 +50,7 @@ headers = {
|
||||
|
||||
@pid_search.got("pid", prompt="需要查询的图片PID是?")
|
||||
async def _g(event: MessageEvent, state: T_State, pid: str = Arg("pid")):
|
||||
url = Config.get_config("hibiapi", "HIBIAPI") + "/api/pixiv/"
|
||||
url = Config.get_config("hibiapi", "HIBIAPI") + "/api/pixiv/illust"
|
||||
if pid in ["取消", "算了"]:
|
||||
await pid_search.finish("已取消操作...")
|
||||
if not is_number(pid):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from configs.config import Config
|
||||
from utils.manager import GDict
|
||||
from utils.utils import GDict
|
||||
import nonebot
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from .._model import Setu
|
||||
import asyncio
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -22,6 +23,7 @@ except ModuleNotFoundError:
|
||||
url = "https://api.lolicon.app/setu/v2"
|
||||
path = "_setu"
|
||||
r18_path = "_r18"
|
||||
host_pattern = re.compile(r"https?://([^/]+)")
|
||||
|
||||
|
||||
# 获取url
|
||||
@@ -89,7 +91,9 @@ async def search_online_setu(
|
||||
"""
|
||||
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
|
||||
if ws_url:
|
||||
url_ = url_.replace("i.pximg.net", ws_url).replace("i.pixiv.cat", ws_url)
|
||||
host_match = re.match(host_pattern, url_)
|
||||
host = host_match.group(1)
|
||||
url_ = url_.replace(host, ws_url)
|
||||
index = random.randint(1, 100000) if id_ is None else id_
|
||||
path_ = IMAGE_PATH / path_ if path_ else TEMP_PATH
|
||||
file_name = f"{index}_temp_setu.jpg" if path_ == TEMP_PATH else f"{index}.jpg"
|
||||
|
||||
@@ -18,6 +18,7 @@ from configs.path_config import DATA_PATH
|
||||
from services.log import logger
|
||||
from .utils import clear_sign_data_pic
|
||||
from utils.utils import is_number
|
||||
from .goods_register import driver
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
|
||||
from models.sign_group_user import SignGroupUser
|
||||
from configs.config import Config
|
||||
from nonebot import Driver
|
||||
from utils.decorator.shop import shop_register, NotMeetUseConditionsException
|
||||
import nonebot
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def _():
|
||||
"""
|
||||
导入内置的三个商品
|
||||
"""
|
||||
|
||||
@shop_register(
|
||||
name=("好感度双倍加持卡Ⅰ", "好感度双倍加持卡Ⅱ", "好感度双倍加持卡Ⅲ"),
|
||||
price=(30, 150, 250),
|
||||
des=(
|
||||
"下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)",
|
||||
"下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)",
|
||||
"下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)",
|
||||
),
|
||||
load_status=Config.get_config("shop", "IMPORT_DEFAULT_SHOP_GOODS"),
|
||||
icon=("favorability_card_1.png", "favorability_card_2.png", "favorability_card_3.png"),
|
||||
** {"好感度双倍加持卡Ⅰ_prob": 0.1, "好感度双倍加持卡Ⅱ_prob": 0.2, "好感度双倍加持卡Ⅲ_prob": 0.3},
|
||||
)
|
||||
async def sign_card(user_id: int, group_id: int, prob: float):
|
||||
user = await SignGroupUser.ensure(user_id, group_id)
|
||||
await user.update(add_probability=prob).apply()
|
||||
|
||||
@shop_register(
|
||||
name="测试道具A",
|
||||
price=99,
|
||||
des="随便侧而出",
|
||||
load_status=False,
|
||||
icon="sword.png",
|
||||
)
|
||||
async def _(user_id: int, group_id: int):
|
||||
print(user_id, group_id, '使用测试道具')
|
||||
|
||||
@shop_register.before_handle(name="测试道具A", load_status=False)
|
||||
async def _(user_id: int, group_id: int):
|
||||
print(user_id, group_id, '第一个使用前函数(before handle)')
|
||||
|
||||
@shop_register.before_handle(name="测试道具A", load_status=False)
|
||||
async def _(user_id: int, group_id: int):
|
||||
print(user_id, group_id, '第二个使用前函数(before handle)222')
|
||||
raise NotMeetUseConditionsException("太笨了!") # 抛出异常,阻断使用,并返回信息
|
||||
|
||||
@shop_register.after_handle(name="测试道具A", load_status=False)
|
||||
async def _(user_id: int, group_id: int):
|
||||
print(user_id, group_id, '第一个使用后函数(after handle)')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from services.db_context import db
|
||||
|
||||
|
||||
class Statistics(db.Model):
|
||||
__tablename__ = "statistics"
|
||||
id = db.Column(db.Integer(), primary_key=True)
|
||||
user_qq = db.Column(db.BigInteger(), nullable=False)
|
||||
group_id = db.Column(db.BigInteger())
|
||||
plugin_name = db.Column(db.String(), nullable=False)
|
||||
create_time = db.Column(db.DateTime(timezone=True), nullable=False)
|
||||
|
||||
@classmethod
|
||||
async def add_statistic(cls, user_qq: int, group_id: Optional[int], plugin_name: str):
|
||||
"""
|
||||
说明:
|
||||
添加记录
|
||||
参数:
|
||||
:param user_qq: qq
|
||||
:param group_id: 群号
|
||||
:param plugin_name: 插件model
|
||||
"""
|
||||
await cls.create(
|
||||
user_qq=user_qq,
|
||||
group_id=group_id,
|
||||
plugin_name=plugin_name,
|
||||
create_time=datetime.now(),
|
||||
)
|
||||
@@ -172,8 +172,8 @@ async def generate_statistics_img(
|
||||
data: dict, arg: str, name: str, plugin: str, day_index: int
|
||||
):
|
||||
try:
|
||||
plugin = plugins2settings_manager.get_plugin_data(plugin)['cmd'][0]
|
||||
except (KeyError, IndexError):
|
||||
plugin = plugins2settings_manager.get_plugin_data(plugin).cmd[0]
|
||||
except (KeyError, IndexError, AttributeError):
|
||||
pass
|
||||
bar_graph = None
|
||||
if arg == "day_statistics":
|
||||
|
||||
@@ -2,12 +2,12 @@ from configs.path_config import DATA_PATH
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.message import run_postprocessor
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent
|
||||
from datetime import datetime
|
||||
from utils.manager import plugins2settings_manager
|
||||
from utils.utils import scheduler
|
||||
from nonebot.typing import Optional
|
||||
from pathlib import Path
|
||||
from ._model import Statistics
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -90,7 +90,7 @@ async def _(
|
||||
matcher: Matcher,
|
||||
exception: Optional[Exception],
|
||||
bot: Bot,
|
||||
event: GroupMessageEvent,
|
||||
event: MessageEvent,
|
||||
state: T_State,
|
||||
):
|
||||
global _prefix_count_dict
|
||||
@@ -99,6 +99,11 @@ async def _(
|
||||
and matcher.priority not in [1, 999]
|
||||
and matcher.plugin_name not in ["update_info", "statistics_handle"]
|
||||
):
|
||||
await Statistics.add_statistic(
|
||||
event.user_id,
|
||||
event.group_id if isinstance(event, GroupMessageEvent) else None,
|
||||
matcher.plugin_name,
|
||||
)
|
||||
module = matcher.plugin_name
|
||||
day_index = _prefix_count_dict["day_index"]
|
||||
try:
|
||||
@@ -107,8 +112,8 @@ async def _(
|
||||
group_id = "total"
|
||||
user_id = str(event.user_id)
|
||||
plugin_name = plugins2settings_manager.get_plugin_data(module)
|
||||
if plugin_name and plugin_name.get('cmd'):
|
||||
plugin_name = plugin_name.get('cmd')[0]
|
||||
if plugin_name and plugin_name.cmd:
|
||||
plugin_name = plugin_name.cmd[0]
|
||||
check_exists_key(group_id, user_id, plugin_name)
|
||||
for data in [_prefix_count_dict, _prefix_user_count_dict]:
|
||||
data["total_statistics"]["total"][plugin_name] += 1
|
||||
@@ -124,17 +129,11 @@ async def _(
|
||||
key = user_id
|
||||
data["total_statistics"][key][plugin_name] += 1
|
||||
data["day_statistics"][key][plugin_name] += 1
|
||||
data["week_statistics"][key][str(day_index % 7)][
|
||||
plugin_name
|
||||
] += 1
|
||||
data["month_statistics"][key][str(day_index % 30)][
|
||||
plugin_name
|
||||
] += 1
|
||||
data["week_statistics"][key][str(day_index % 7)][plugin_name] += 1
|
||||
data["month_statistics"][key][str(day_index % 30)][plugin_name] += 1
|
||||
with open(statistics_group_file, "w", encoding="utf8") as f:
|
||||
json.dump(_prefix_count_dict, f, indent=4, ensure_ascii=False)
|
||||
with open(
|
||||
statistics_user_file, "w", encoding="utf8"
|
||||
) as f:
|
||||
with open(statistics_user_file, "w", encoding="utf8") as f:
|
||||
json.dump(_prefix_user_count_dict, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
@@ -153,7 +152,7 @@ def check_exists_key(group_id: str, user_id: str, plugin_name: str):
|
||||
data["week_statistics"]["total"][plugin_name] = 0
|
||||
if not data["month_statistics"]["total"].get(plugin_name):
|
||||
data["month_statistics"]["total"][plugin_name] = 0
|
||||
|
||||
|
||||
if not data["total_statistics"].get(key):
|
||||
data["total_statistics"][key] = {}
|
||||
if not data["total_statistics"][key].get(plugin_name):
|
||||
@@ -163,7 +162,7 @@ def check_exists_key(group_id: str, user_id: str, plugin_name: str):
|
||||
if not data["day_statistics"][key].get(plugin_name):
|
||||
data["day_statistics"][key][plugin_name] = 0
|
||||
|
||||
if key != 'total':
|
||||
if key != "total":
|
||||
if not data["week_statistics"].get(key):
|
||||
data["week_statistics"][key] = {}
|
||||
if data["week_statistics"][key].get("0") is None:
|
||||
@@ -172,7 +171,7 @@ def check_exists_key(group_id: str, user_id: str, plugin_name: str):
|
||||
if data["week_statistics"][key]["0"].get(plugin_name) is None:
|
||||
for i in range(7):
|
||||
data["week_statistics"][key][str(i)][plugin_name] = 0
|
||||
|
||||
|
||||
if not data["month_statistics"].get(key):
|
||||
data["month_statistics"][key] = {}
|
||||
if data["month_statistics"][key].get("0") is None:
|
||||
@@ -214,4 +213,3 @@ async def _():
|
||||
json.dump(_prefix_count_dict, f, indent=4, ensure_ascii=False)
|
||||
with open(statistics_user_file, "w", encoding="utf8") as f:
|
||||
json.dump(_prefix_user_count_dict, f, indent=4, ensure_ascii=False)
|
||||
|
||||
|
||||
@@ -1,22 +1,56 @@
|
||||
from utils.http_utils import AsyncHttpx
|
||||
import time
|
||||
import random
|
||||
from hashlib import md5
|
||||
|
||||
url = f"http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
|
||||
# url = f"http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
|
||||
url = f"https://fanyi-api.baidu.com/api/trans/vip/translate"
|
||||
|
||||
|
||||
async def translate_msg(language_type, msg):
|
||||
# 获取lts时间戳,salt加密盐,sign加密签名
|
||||
def get_lts_salt_sign(word):
|
||||
lts = str(int(time.time() * 10000))
|
||||
salt = lts + str(random.randint(0, 9))
|
||||
string = "fanyideskweb" + word + salt + "Ygy_4c=r#e#4EX^NUGUc5"
|
||||
s = md5()
|
||||
# md5的加密串必须为字节码
|
||||
s.update(string.encode())
|
||||
# 16进制加密
|
||||
sign = s.hexdigest()
|
||||
print(lts, salt, sign)
|
||||
return lts, salt, sign
|
||||
|
||||
async def translate_msg(language_type, word):
|
||||
# data = {
|
||||
# "type": parse_language(language_type),
|
||||
# "i": msg,
|
||||
# "doctype": "json",
|
||||
# "version": "2.1",
|
||||
# "keyfrom": "fanyi.web",
|
||||
# "ue": "UTF-8",
|
||||
# "action": "FY_BY_CLICKBUTTON",
|
||||
# "typoResult": "true",
|
||||
# }
|
||||
lts, salt, sign = get_lts_salt_sign(word)
|
||||
data = {
|
||||
"type": parse_language(language_type),
|
||||
"i": msg,
|
||||
"doctype": "json",
|
||||
"version": "2.1",
|
||||
"keyfrom": "fanyi.web",
|
||||
"ue": "UTF-8",
|
||||
"action": "FY_BY_CLICKBUTTON",
|
||||
"typoResult": "true",
|
||||
'i': word,
|
||||
'from': 'AUTO',
|
||||
'to': 'AUTO',
|
||||
'smartresult': 'dict',
|
||||
'client': 'fanyideskweb',
|
||||
'salt': salt,
|
||||
'sign': sign,
|
||||
'lts': lts,
|
||||
'bv': 'bdc0570a34c12469d01bfac66273680d',
|
||||
'doctype': 'json',
|
||||
'version': '2.1',
|
||||
'keyfrom': 'fanyi.web',
|
||||
'action': 'FY_BY_REALTlME'
|
||||
}
|
||||
data = (await AsyncHttpx.post(url, data=data)).json()
|
||||
if data["errorCode"] == 0:
|
||||
return f'原文:{msg}\n翻译:{data["translateResult"][0][0]["tgt"]}'
|
||||
return f'原文:{word}\n翻译:{data["translateResult"][0][0]["tgt"]}'
|
||||
return "翻译惜败.."
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user