Compare commits

...
191 Commits
Author SHA1 Message Date
HibiKier 216d32cf21 Update README.md 2022-06-19 23:16:11 +08:00
HibiKier 248fae4fe6 Update __version__ 2022-06-19 23:15:40 +08:00
HibiKier b479b6839d Update README.md 2022-06-19 22:29:44 +08:00
HibiKier 1a4e1e9515 Merge pull request #835 from yajiwa/main
词条优化问题展示,修改含机器人昵称和@逻辑
2022-06-19 22:29:20 +08:00
yajiwa e5160a4ee8 Merge branch 'HibiKier:main' into main 2022-06-19 17:26:13 +08:00
yajiwa 56ea3964a7 update word_bank 2022-06-19 17:24:50 +08:00
HibiKier ad73778286 update README.md 2022-06-19 16:55:02 +08:00
HibiKier 3e548f48c8 Merge pull request #828 from McElaga/main
修复原神树脂重复提醒的bug
2022-06-19 16:54:25 +08:00
HibiKier ae466931fa fix webui 2022-06-19 16:44:37 +08:00
HibiKier 68052b526f update image_utils 2022-06-18 15:23:36 +08:00
HibiKier 903b5b88a7 update image_utils 2022-06-18 15:09:55 +08:00
HibiKier 007823d6b2 update README.md 2022-06-18 15:03:05 +08:00
HibiKier db5c4fb349 Merge pull request #830 from po-lan/main
我不太会提交单个文件,我就把俄罗斯轮盘的文件 改回去了,再提交的
2022-06-18 15:00:46 +08:00
HibiKier c37901290a fix nickname 2022-06-18 14:57:54 +08:00
HibiKier da67f1f6f8 update webui 2022-06-18 14:48:46 +08:00
HibiKier 5172fa69e5 fix web ui 2022-06-18 14:31:44 +08:00
po-lan dd7280cd0d 恢复 原先的文件 2022-06-18 14:08:59 +08:00
McElaga 0d0f522c88 Merge branch 'HibiKier:main' into main 2022-06-18 09:27:12 +08:00
McElaga 5429e6ed5c Merge branch 'main' of https://github.com/McElaga/zhenxun_bot 2022-06-18 09:15:24 +08:00
McElaga 9db69fa05b 修复一点逻辑小问题 2022-06-18 09:15:19 +08:00
HibiKier 3b8d52bcb5 Update README.md 2022-06-17 18:50:37 +08:00
HibiKier 807f39a336 Update README.md 2022-06-17 18:50:15 +08:00
HibiKier fea2f30461 Merge pull request #820 from LambdaYH/patch-2
修复wordbank的一些小问题
2022-06-17 18:49:42 +08:00
po-lan 5d97e3f95f Update __init__.py 2022-06-16 16:15:39 +08:00
po-lan 63e6ca3e99 Update __init__.py 2022-06-16 15:40:46 +08:00
po-lan b11590ec3c ban掉被击毙的人一段时间 2022-06-16 15:38:20 +08:00
po-lan 3a43ed6919 如果需要 保存到 config 可以少调用一次 2022-06-16 14:38:41 +08:00
po-lan 15ce9c91fb Update __init__.py 2022-06-16 14:25:22 +08:00
LambdaYH 0e8d7537d4 fix wordbank 2022-06-16 00:43:32 +08:00
Cinte 1fca0787be fix: 修复之前更改正则引入的问题 2022-06-15 23:16:39 +08:00
HibiKier af30285c00 Update browser.py 2022-06-15 10:08:43 +08:00
HibiKier a84cab7afd replace bt url 2022-06-14 20:40:11 +08:00
HibiKier 593573ddfb fix pix 2022-06-14 19:48:32 +08:00
HibiKier e9e9f81bdb Merge pull request #806 from LambdaYH/patch-2
fix: 修复添加词条时对answer中图片的处理
2022-06-14 19:31:53 +08:00
HibiKier 61f624841b Merge pull request #810 from LambdaYH/patch-3
fix: 自动更新群组
2022-06-14 19:31:18 +08:00
HibiKier 4bb38a2730 Merge pull request #812 from po-lan/main
可关闭 ssl 验证
2022-06-14 19:22:25 +08:00
HibiKier d4ec0df00c Update http_utils.py 2022-06-14 19:22:12 +08:00
po-lan c8a7d855f8 Update http_utils.py 2022-06-14 18:47:43 +08:00
Cinte 73a126dcd5 fix: 自动更新群组 2022-06-14 09:18:03 +08:00
HibiKier 0736533389 fix search_image 2022-06-13 22:16:45 +08:00
Cinte 2695d658ab fix: 修复添加词条时对answer中图片的处理 2022-06-13 22:11:18 +08:00
HibiKier 947166e793 Merge pull request #804 from po-lan/main
Windows 重启适配
2022-06-13 20:20:30 +08:00
po-lan 80c49a7cf5 Update __init__.py 2022-06-13 15:34:28 +08:00
po-lan 55bfa8f669 Update __init__.py
Windows 重启适配
2022-06-13 15:24:28 +08:00
HibiKier 74ade14f5e Update README.md 2022-06-13 11:07:34 +08:00
HibiKier c9b5218ebc Merge pull request #798 from CopilotLaLaLa/main
webui中token.json文件写入补充
2022-06-13 11:07:11 +08:00
HibiKier b324b2bd65 Merge pull request #800 from yajiwa/main
update setu_img
2022-06-13 11:06:20 +08:00
HibiKier 35c038efa2 Update utils.py 2022-06-13 11:05:16 +08:00
HibiKier caa404d58d Update utils.py 2022-06-13 11:03:21 +08:00
yajiwa 830103b9d5 update change_img_md5 2022-06-13 10:59:29 +08:00
yajiwa 6e18379597 update setu_img 2022-06-13 10:08:51 +08:00
yajiwa 6effbacb28 add change_img_md5 2022-06-13 10:08:09 +08:00
CopilotLaLaLa a20a1a0234 同步原仓库 2022-06-12 15:23:10 +00:00
CopilotLaLaLa 3667724061 token_json文件写入 2022-06-12 15:16:07 +00:00
HibiKier 785179e4a7 update pix 2022-06-11 17:57:19 +08:00
HibiKier 715338f821 Merge pull request #791 from mmmjie/main
两处BUG的修复
2022-06-10 21:31:51 +08:00
mmmjie 7d5a82ab6d Update update_picture.py
对于temp/temp的错误路径,减少了一个temp
TEMP_PATH 已经指向了一个temp了
2022-06-10 00:37:18 +08:00
mmmjie e764cfcc1c Update white2black_image.py
随着7b836ac 对utils/image_utils.py 的改动
调整此插件对于 utils/image_utils.py改动的引用部分
2022-06-10 00:35:57 +08:00
HibiKier 363acf37bc fix bug and update 2022-06-09 20:39:48 +08:00
HibiKier 5fd687c1e4 Merge pull request #778 from SinKy-Yan/main
fix auto update bug
2022-06-09 19:37:26 +08:00
HibiKier dbedcbb93d Update pyproject.toml 2022-06-08 11:51:32 +08:00
HibiKier 9e9611f11f Update README.md 2022-06-08 11:43:10 +08:00
HibiKier 44002838da Merge pull request #779 from MingxuanGame/main
chore(deps): update `nonebot-adapter-onebot`
2022-06-08 11:42:43 +08:00
MingxuanGame 4daab8459f chore(deps): update nonebot-adapter-onebot 2022-06-07 11:57:34 +00:00
HibiKier 5a002f75cc Merge pull request #777 from LambdaYH/patch-1
fix image_utils.py
2022-06-07 19:27:31 +08:00
源源球球✨ a2180a1365 fix auto update bug 2022-06-07 10:19:23 +00:00
Cinte 7b836acf36 fix image_utils.py
https://github.com/HibiKier/zhenxun_bot/commit/ae8a214a3a5c08a51cacd1dc37583c0b32e6332f
之前这个commit里面看到函数参数有写着int类型就把`font_size`类型转换给去了,结果导致了部分地方输入float类型后报错。现在改回来
2022-06-07 17:06:16 +08:00
HibiKier a112a561cc Update README.md 2022-06-05 20:30:49 +08:00
HibiKier 6dcc2a69f4 Update README.md 2022-06-05 19:56:42 +08:00
HibiKier 74e9c55a09 update v0.1.5.8 2022-06-05 19:51:23 +08:00
HibiKier d4d6e736a4 Merge pull request #764 from McElaga/main
金币红包功能增加更多封面
2022-06-05 19:08:51 +08:00
HibiKier 5cf9938fa2 Merge pull request #763 from RShock/main
fix gold_redbag
2022-06-05 19:04:40 +08:00
McElaga 72ad0ad983 commit on main 2022-06-04 12:34:18 +08:00
咕咕型小r 690750d91e fix gold_redbag 2022-06-04 12:09:05 +08:00
HibiKier 9f1dfc4b9c Merge pull request #756 from McElaga/main
修复原神树脂提醒bug(已实测)
2022-06-03 16:15:50 +08:00
HibiKier 05eab5307f Update README.md 2022-06-03 16:13:29 +08:00
HibiKier b0fe70c960 Merge pull request #745 from LambdaYH/main
稍微调整了一下查看所有请求中的年龄绘制
2022-06-03 16:07:01 +08:00
McElaga 09d7992bc4 comit on main 2022-06-03 12:09:15 +08:00
McElaga c832a432c1 commit on main 2022-06-03 11:52:40 +08:00
HibiKier 41c22f4314 fix ShopRegister 2022-06-03 01:14:34 +08:00
HibiKier 252d45c79b fix webui update plugin_shop 2022-06-03 00:59:00 +08:00
Cinte ae8a214a3a Update image_utils.py 2022-06-02 10:06:55 +08:00
LambdaYH 86ce6d7664 fix: 稍微调整了一下查看所有请求中的年龄绘制 2022-06-02 10:02:03 +08:00
McElaga 67e96d6106 commit on main 2022-06-02 08:55:24 +08:00
HibiKier 24d9ec2b75 Update __init__.py 2022-06-01 11:05:12 +08:00
HibiKier 501e47c6ec fix image2text 2022-05-31 20:45:28 +08:00
HibiKier 5534a5a5c2 Merge pull request #707 from HiDolen/main
修复抽卡插件:方舟更新UP池信息时,若公告的第一个池子过期会导致无法更新UP池信息
2022-05-31 20:14:48 +08:00
HibiKier 7246aabf40 Merge pull request #712 from McElaga/main
修复发红包图片背景未透明化;修复原神树脂提醒参数错误
2022-05-31 20:07:35 +08:00
HibiKier 604ffae87e Merge pull request #711 from LambdaYH/patch-1
bot_friend_group将group_handle.修改为friend_handle.
2022-05-31 20:06:12 +08:00
HibiKier 2d5c16456b Merge pull request #721 from LambdaYH/patch-2
修复开启/关闭全部功能时帮助图片未重绘
2022-05-31 20:01:39 +08:00
Cinte d44f7633dc 修复开启/关闭全部功能时帮助图片未重绘 2022-05-30 20:43:48 +08:00
Cinte 469ac4035c 大概是把group_handle写成了friend_handle 2022-05-30 11:27:14 +08:00
McElaga dab218a6d7 commit on main 2022-05-30 11:14:47 +08:00
Dolen d6fc675d57 修复抽卡插件:避免被跳过的卡池信息污染后面的卡池信息 2022-05-30 11:11:49 +08:00
McElaga 04148f7365 commit on main 2022-05-30 11:00:19 +08:00
Dolen 4c34ac570f 修复抽卡插件:方舟更新UP池信息时,若公告的第一个池子过期会导致无法更新UP池信息 2022-05-29 23:13:36 +08:00
HibiKier fbdb8758a3 Update README.md 2022-05-29 22:21:26 +08:00
HibiKier 2d08747d70 Merge pull request #705 from yajiwa/main
商店插件判断是否有requirements.txt文件
2022-05-29 22:21:03 +08:00
yajiwa 0b4bacbbd1 update plugin_shop 2022-05-29 21:57:01 +08:00
yajiwa e0412c7edb Merge branch 'HibiKier:main' into main 2022-05-29 21:03:12 +08:00
HibiKier 38501cebf1 Update data_source.py 2022-05-29 20:56:03 +08:00
HibiKier ee45d0217e Update __init__.py 2022-05-29 20:55:32 +08:00
HibiKier 558f362919 update v0.1.5.8 2022-05-29 20:47:18 +08:00
HibiKier fb9db2f50c fix 2022-05-29 19:57:57 +08:00
HibiKier c1862e9c68 fix bt 2022-05-29 19:15:29 +08:00
HibiKier 731bde8e28 update v0.1.5.7 2022-05-29 19:14:36 +08:00
HibiKier 47c87f8694 update db_context 2022-05-28 22:50:23 +08:00
HibiKier 5558cdacc3 Update README.md 2022-05-28 21:09:58 +08:00
HibiKier 4650d244a5 Merge pull request #688 from McElaga/main
修复微博热搜报错,发红包小bug
2022-05-28 21:08:17 +08:00
HibiKier c65b8aae07 update webui 2022-05-28 20:57:08 +08:00
HibiKier 7ba2fb9584 update black_word 2022-05-28 20:55:14 +08:00
HibiKier 9a2cfd0c9b zhenxun_update add config 2022-05-28 18:28:38 +08:00
HibiKier a7d61b1f2b add config 2022-05-28 18:12:08 +08:00
HibiKier 7ab185f7d7 fix poke 2022-05-28 17:48:28 +08:00
HibiKier 724541d691 fix bug 2022-05-28 17:22:51 +08:00
McElaga baa6cda9c2 commit on main 2022-05-28 10:31:27 +08:00
HibiKier 9c987e9aad log2cn 2022-05-26 22:49:48 +08:00
HibiKier 134974ea9c Merge pull request #667 from NumberSir/main
更新抽卡插件
2022-05-26 22:43:11 +08:00
HibiKier 2d946958e3 Merge pull request #668 from HanakoLuna/patch-1
更新BT搜索源地址
2022-05-26 22:42:37 +08:00
Lya_Yami ffe010e9ce 更新BT搜索源地址 2022-05-26 20:47:12 +08:00
HibiKier 1c67252b0c Update README.md 2022-05-26 20:26:14 +08:00
HibiKier 60c1be25d4 Merge pull request #643 from LambdaYH/patch-1
修复[滴滴滴]会被转义成[滴滴滴]导致无法触发的问题
2022-05-26 20:25:45 +08:00
Number_Sir 18323a0916 更新抽卡插件
修复了方舟抽卡图文不符的问题
修复了方舟许多三星抽不出来的问题
修复了方舟重载卡池失败的问题
2022-05-26 20:07:09 +08:00
HibiKier 9d98abded9 Merge pull request #660 from Sakuracio/main
Replace URL
2022-05-26 19:49:23 +08:00
MangataAkihi b06a742b8c Update README.md 2022-05-26 17:20:37 +08:00
github-actions[bot] 87fe44f188 Auto generate poetry.lock 2022-05-26 09:18:16 +00:00
Cinte 96f6ef1693 修复[滴滴滴]会被转义成[滴滴滴]导致无法触发的问题 2022-05-26 09:59:45 +08:00
github-actions[bot] 374b7b7261 Auto generate poetry.lock 2022-05-25 23:42:48 +00:00
HibiKier 23c4141e55 Update README.md 2022-05-25 20:53:09 +08:00
HibiKier c21200c2a9 Merge pull request #610 from yajiwa/main
修复碧蓝航线/明日方舟up池解析出错的问题
2022-05-25 20:52:58 +08:00
HibiKier 4a8b94259d Merge pull request #602 from HiDolen/main-patch
修改翻译插件,添加缺失的冒号
2022-05-25 20:49:51 +08:00
HibiKier 28a58df27b Merge pull request #607 from MingxuanGame/main
feat: stream downloading and progress
2022-05-25 20:49:20 +08:00
HibiKier caaf486bbe Merge branch 'main' into main 2022-05-25 20:49:07 +08:00
HibiKier 0a972a399e Merge pull request #617 from mouhensama/main
把gamedraw的ba卡池搬运了过来并且进行了真寻的适配。
2022-05-25 20:44:07 +08:00
HibiKier 245dad1239 Merge pull request #624 from HiDolen/main-patch2
修改nickname插件:一处文案错误,添加敏感词
2022-05-25 20:42:51 +08:00
Dolen a6b6a2fbff 修改nickname插件:一处文案错误 2022-05-25 17:21:00 +08:00
Dolen 53000a949b 修改nickname插件:添加一个敏感词 2022-05-25 17:03:44 +08:00
Dolen eae1dd59a7 修改nickname插件:一处文案错误 2022-05-25 17:02:09 +08:00
HibiKier e6347a76a8 Update issue-template.md 2022-05-25 14:44:28 +08:00
HibiKier 13e0fb3df7 Delete bug-issue-template.md 2022-05-25 13:42:22 +08:00
HibiKier 3f1b23ef8a Update issue templates 2022-05-25 13:41:35 +08:00
HibiKier acae7f0658 Create ISSUE_TEMPLATE.md 2022-05-25 13:37:29 +08:00
HibiKier a9456b1bd6 Merge pull request #608 from AkashiCoin/main
Use Action to automatically generate poetry.lock
2022-05-25 13:35:39 +08:00
mouhensama e4d5a230d2 把nonebot_plugin_gamedraw的ba卡池搬运了过来并且进行了真寻的适配。 2022-05-25 11:47:08 +08:00
HibiKier fedf44b9fa Update README.md 2022-05-25 10:54:52 +08:00
HibiKier 451db104e8 Update config.py 2022-05-25 08:52:22 +08:00
HibiKier 9ac4c7f4e3 Update README.md 2022-05-25 08:52:15 +08:00
HibiKier 7cf1c6f016 Update README.md 2022-05-25 08:41:59 +08:00
yajiwa 6dd87ee301 fix draw_card 2022-05-25 07:02:42 +08:00
MingxuanGame 96837fa8db fix: rich from dev dependent to main dependent 2022-05-25 01:19:12 +08:00
MingxuanGame d816e76962 fix: rich from dev dependent to main dependent 2022-05-25 01:13:27 +08:00
AkashiCoin 310945d9cd Merge branch 'HibiKier:main' into main 2022-05-25 01:01:11 +08:00
MingxuanGame 1aba480495 feat: stream downloading and progress 2022-05-25 00:56:41 +08:00
HibiKier 07407749fe Update README.md 2022-05-24 22:05:38 +08:00
HibiKier dfab70dd90 Merge pull request #581 from HiDolen/main
修复抽卡插件:方舟抽卡的抽取和显示问题
2022-05-24 22:05:13 +08:00
Dolen 3b15469c98 修改翻译插件,发送消息添加冒号 2022-05-24 08:59:14 -05:00
HibiKier e4590800c2 Update README.md 2022-05-24 21:20:59 +08:00
HibiKier c63d4b8ad0 Merge pull request #573 from jk6589jk/patch-2
修复复读不能复读图片的问题
2022-05-24 21:19:41 +08:00
HibiKier 1fb913e2ed Merge pull request #576 from MingxuanGame/main
refactor&fix(manager): modify argument
2022-05-24 21:18:22 +08:00
HibiKier 72ace2dab7 Merge pull request #579 from yajiwa/main
更新"微博热搜"接口
2022-05-24 21:14:51 +08:00
HibiKier 3bcef18629 Merge pull request #600 from sdy623/main
bugfix: 修正了签到时日期时间的显示不补齐零的bug (符合日期时间表示法 ISO 8601)
2022-05-24 21:13:33 +08:00
sdy623 c91758519c bugfix: 修正了签到时日期时间的显示不补齐零的bug (符合日期时间表示法 ISO 8601) 2022-05-24 20:19:32 +08:00
jk6589jk 9c8f2e7aa0 Update fudu.py 2022-05-24 14:01:08 +08:00
Dolen 5f377af6d5 修复抽卡插件:方舟抽卡的抽取和显示问题 2022-05-24 09:13:10 +08:00
yajiwa 570b5b1766 update wbtop 2022-05-24 06:01:23 +08:00
MingxuanGame c4d53d58eb refactor&fix(manager): modify argument 2022-05-24 01:27:55 +08:00
jk6589jk ed65033cf1 修复复读不能复读图片的问题
IMAGE_PATH = Path() / "resources" / "image"
TEMP_PATH = Path() / "resources" / "temp"
image()默认读取在 resource/img 目录下,读写路径不同,导致找不到图片

打断打断施法!,rst.endswith("打断施法!")在复读内容含有图片时会报错
2022-05-23 22:06:53 +08:00
HibiKier 41836bde26 Update README.md 2022-05-23 22:05:19 +08:00
HibiKier 8381858742 Update README.md 2022-05-23 22:02:49 +08:00
HibiKier 1040bd0d58 update v0.1.5.6 2022-05-23 22:01:56 +08:00
HibiKier 404e47332e Merge pull request #441 from with9/main
添加pixiv搜图多关键词支持;修复p站搜图数量参数问题
2022-05-23 21:52:33 +08:00
HibiKier 3db128785e Update __init__.py 2022-05-23 21:52:08 +08:00
HibiKier 2189ea11df Update README.md 2022-05-23 19:46:30 +08:00
HibiKier 49b9bd65b0 Merge pull request #552 from jk6589jk/patch-1
修复有置顶的up主B站动态获取失败
2022-05-23 19:45:59 +08:00
jk6589jk b3fdb1ff58 修复B站动态获取失败
bili-dyn-item__tag的父项的父项才是完整的一条置顶动态
2022-05-23 12:59:53 +08:00
HibiKier c79e3fdcf0 Update README.md 2022-05-23 07:52:27 +08:00
HibiKier d7509f7030 Merge pull request #545 from yajiwa/main
修复"清除已删除插件数据"
2022-05-23 07:51:54 +08:00
yajiwa 5c99b55502 fix none_plugin_count 2022-05-23 02:35:57 +08:00
yajiwa fd255f022b Merge branch 'HibiKier:main' into main 2022-05-23 02:27:00 +08:00
github-actions[bot] 8d3f101a68 Auto generate poetry.lock 2022-05-21 18:38:05 +00:00
AkashiCoin c8ac2b6281 Update Generate.yml 2022-05-22 02:35:20 +08:00
AkashiCoin d7d8efd305 Merge branch 'HibiKier:main' into main 2022-05-22 02:04:34 +08:00
HibiKier a4bc04c958 Update pid_search.py 2022-05-22 01:46:52 +08:00
AkashiCoin 5fc208c95a Create Generate.yml 2022-05-22 00:29:54 +08:00
HibiKier 02743d5955 Merge pull request #384 from AkashiCoin/main
Update anime.json of Kyomotoi/AnimeThesaurus
2022-05-21 23:40:13 +08:00
HibiKier a7ffebea35 Merge pull request #503 from yajiwa/main
修复命令不唯一的问题
2022-05-21 23:39:39 +08:00
AkashiCoin 1de5ae09bc Merge branch 'HibiKier:main' into main 2022-05-21 20:46:04 +08:00
yajiwa 8b735f1cb5 fix word_clouds 2022-05-21 20:08:53 +08:00
with9 9cdd2326c8 添加pixiv搜图多关键词支持;修复p站搜图数量参数问题 2022-05-20 19:35:18 +08:00
AkashiCoin d75653631d Merge branch 'HibiKier:main' into main 2022-05-19 23:21:02 +08:00
AkashiCoin e234c8906e Update anime.json 2022-05-19 23:20:00 +08:00
142 changed files with 1662 additions and 617 deletions
+23
View File
@@ -0,0 +1,23 @@
---
name: Issue template
about: " issue template's purpose here."
title: ''
labels: ''
assignees: ''
---
### 系统版本:Ubuntu 20.04
### 真寻版本:0.1.5.3
### 错误截图
[img]
### 日志截图
[img]
### 错误说明
发生了xx错误...
+38
View File
@@ -0,0 +1,38 @@
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
View File
@@ -0,0 +1,9 @@
### 系统版本:Ubuntu 20.04
### 真寻版本:0.1.5.3
### 错误截图
[img]
### 错误说明
发生了xx错误...
+1
View File
@@ -140,6 +140,7 @@ cython_debug/
test.py test.py
server_ip.py server_ip.py
game_utils.py
member_activity_handle.py member_activity_handle.py
Yu-Gi-Oh/ Yu-Gi-Oh/
csgo/ csgo/
+129 -2
View File
@@ -18,6 +18,11 @@
## 声明 ## 声明
此项目仅用于学习交流,请勿用于非法用途 此项目仅用于学习交流,请勿用于非法用途
# Nonebot2
<img style="height: 200px;width: 200px;" src="https://camo.githubusercontent.com/0ef71e86056da694c540790aa4a4e314396884d6c4fdb95362a7538b27a1b034/68747470733a2f2f76322e6e6f6e65626f742e6465762f6c6f676f2e706e67">
非常 [ **[NICE](https://github.com/nonebot/nonebot2)** ] 的OneBot框架
## 未完成的文档 ## 未完成的文档
# [传送门](https://hibikier.github.io/zhenxun_bot/) # [传送门](https://hibikier.github.io/zhenxun_bot/)
@@ -109,7 +114,7 @@
- [x] 获取b站视频封面 - [x] 获取b站视频封面
- [x] 通过PID获取图片 - [x] 通过PID获取图片
- [x] 功能统计可视化 - [x] 功能统计可视化
- [x] 词云
- [x] 关于 - [x] 关于
### 已实现的管理员功能 ### 已实现的管理员功能
@@ -231,13 +236,135 @@ python bot.py
## 使用Docker ## 使用Docker
__Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
#### GitHub:[Sakuracio/zxenv](https://github.com/Sakuracio/zxenv) #### GitHub:[Sakuracio/zhenxun_bot_docker](https://github.com/Sakuracio/zhenxun_bot_docker)
#### DockerHub:[hibikier/zhenxun_bot](https://hub.docker.com/r/hibikier/zhenxun_bot) #### DockerHub:[hibikier/zhenxun_bot](https://hub.docker.com/r/hibikier/zhenxun_bot)
## 更新 ## 更新
### 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
* 修复\[滴滴滴]会被转义成&#91;滴滴滴&#93;导致无法触发的问题
* 将一些错误以中文提示输出
* 更新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] ### 2022/5/22 \[v0.1.5.4]
* 使用action自动更新poetry.lock [@pull/515](https://github.com/HibiKier/zhenxun_bot/pull/515) * 使用action自动更新poetry.lock [@pull/515](https://github.com/HibiKier/zhenxun_bot/pull/515)
+1 -1
View File
@@ -1 +1 @@
__version__: v0.1.5.4 __version__: v0.1.6.0
@@ -118,6 +118,8 @@ async def change_group_switch(cmd: str, group_id: int, is_super: bool = False):
group_manager.unblock_plugin(f, group_id) group_manager.unblock_plugin(f, group_id)
else: else:
group_manager.block_plugin(f, group_id) group_manager.block_plugin(f, group_id)
if group_help_file.exists():
group_help_file.unlink()
return f"已 {status} 全部功能!" return f"已 {status} 全部功能!"
if cmd in [task_data[x] for x in task_data.keys()]: if cmd in [task_data[x] for x in task_data.keys()]:
type_ = "task" type_ = "task"
+2 -1
View File
@@ -4,7 +4,7 @@ from nonebot import on_message
from services.log import logger from services.log import logger
from models.group_info import GroupInfo from models.group_info import GroupInfo
from models.friend_user import FriendUser from models.friend_user import FriendUser
from nonebot.adapters.onebot.v11.exception import ActionFailed from nonebot.adapters.onebot.v11 import ActionFailed
from configs.config import NICKNAME, Config from configs.config import NICKNAME, Config
from utils.manager import group_manager from utils.manager import group_manager
from pathlib import Path from pathlib import Path
@@ -107,6 +107,7 @@ async def _():
group_info["group_name"], group_info["group_name"],
group_info["max_member_count"], group_info["max_member_count"],
group_info["member_count"], group_info["member_count"],
1
) )
logger.info(f"自动更新群组 {g} 信息成功") logger.info(f"自动更新群组 {g} 信息成功")
except Exception as e: except Exception as e:
+3 -2
View File
@@ -2,6 +2,7 @@ from configs.config import Config
from models.chat_history import ChatHistory from models.chat_history import ChatHistory
from nonebot import on_message from nonebot import on_message
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
from utils.utils import get_message_text
from ._rule import rule from ._rule import rule
@@ -22,10 +23,10 @@ chat_history = on_message(rule=rule, priority=1, block=False)
async def _(event: MessageEvent): async def _(event: MessageEvent):
if isinstance(event, GroupMessageEvent): if isinstance(event, GroupMessageEvent):
await ChatHistory.add_chat_msg( await ChatHistory.add_chat_msg(
event.user_id, event.group_id, str(event.get_message()) event.user_id, event.group_id, str(event.get_message()), get_message_text(event.json())
) )
else: else:
await ChatHistory.add_chat_msg(event.user_id, None, str(event.get_message())) await ChatHistory.add_chat_msg(event.user_id, None, str(event.get_message()), get_message_text(event.json()))
# @test.handle() # @test.handle()
+1 -1
View File
@@ -7,10 +7,10 @@ from datetime import datetime
from services.log import logger from services.log import logger
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
ActionFailed,
GroupIncreaseNoticeEvent, GroupIncreaseNoticeEvent,
GroupDecreaseNoticeEvent, GroupDecreaseNoticeEvent,
) )
from nonebot.adapters.onebot.v11.exception import ActionFailed
from utils.manager import group_manager, plugins2settings_manager, requests_manager from utils.manager import group_manager, plugins2settings_manager, requests_manager
from configs.config import NICKNAME from configs.config import NICKNAME
from models.group_info import GroupInfo from models.group_info import GroupInfo
+10 -3
View File
@@ -1,6 +1,5 @@
from nonebot.matcher import Matcher from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, run_postprocessor, IgnoredException from nonebot.message import run_preprocessor, run_postprocessor, IgnoredException
from nonebot.adapters.onebot.v11.exception import ActionFailed
from models.friend_user import FriendUser from models.friend_user import FriendUser
from models.group_member_info import GroupInfoUser from models.group_member_info import GroupInfoUser
from models.bag_user import BagUser from models.bag_user import BagUser
@@ -23,6 +22,7 @@ from nonebot.typing import T_State
from typing import Optional from typing import Optional
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
ActionFailed,
MessageEvent, MessageEvent,
GroupMessageEvent, GroupMessageEvent,
PokeNotifyEvent, PokeNotifyEvent,
@@ -91,7 +91,10 @@ async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
except AttributeError: except AttributeError:
pass pass
# 群黑名单检测 群总开关检测 # 群黑名单检测 群总开关检测
if isinstance(event, GroupMessageEvent) or matcher.plugin_name == other_limit_plugins: if (
isinstance(event, GroupMessageEvent)
or matcher.plugin_name in other_limit_plugins
):
try: try:
if ( if (
group_manager.get_group_level(event.group_id) < 0 group_manager.get_group_level(event.group_id) < 0
@@ -148,7 +151,11 @@ async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
raise IgnoredException("权限不足") raise IgnoredException("权限不足")
if module in plugins2info_dict.keys() and matcher.priority not in [1, 999]: 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 (
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: if status_message_manager.get(event.group_id) is None:
status_message_manager.delete(event.group_id) status_message_manager.delete(event.group_id)
if plugins2info_dict[module]["level"] > group_manager.get_group_level( if plugins2info_dict[module]["level"] > group_manager.get_group_level(
+1 -1
View File
@@ -1,11 +1,11 @@
from nonebot.matcher import Matcher from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, IgnoredException from nonebot.message import run_preprocessor, IgnoredException
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.typing import T_State from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
Event, Event,
MessageEvent, MessageEvent,
ActionFailed,
PokeNotifyEvent, PokeNotifyEvent,
GroupMessageEvent, GroupMessageEvent,
) )
+1 -1
View File
@@ -1,9 +1,9 @@
from nonebot.matcher import Matcher from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, IgnoredException from nonebot.message import run_preprocessor, IgnoredException
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.typing import T_State from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
ActionFailed,
MessageEvent, MessageEvent,
GroupMessageEvent, GroupMessageEvent,
) )
@@ -20,26 +20,36 @@ def init_none_plugin_count_manager():
""" """
清除已删除插件数据 清除已删除插件数据
""" """
modules = [x.module for x in get_matchers()] modules = [x.plugin_name for x in get_matchers()]
for module in none_plugin_count_manager.keys(): plugins_manager_list = list(plugins_manager.keys())
if module not in modules: for module in plugins_manager_list:
none_plugin_count_manager.add_count(module) if module not in modules or none_plugin_count_manager.check(module):
else:
none_plugin_count_manager.reset(module)
if none_plugin_count_manager.check(module):
try: try:
plugin_name = plugins_manager.get(module)["plugin_name"] plugin_name = plugins_manager.get(module)["plugin_name"]
except (AttributeError, KeyError): except (AttributeError, KeyError):
plugin_name = "" plugin_name = ""
try: if none_plugin_count_manager.check(module):
plugins2settings_manager.delete(module) try:
plugins2count_manager.delete(module) plugins2settings_manager.delete(module)
plugins2cd_manager.delete(module) plugins2settings_manager.save()
plugins2block_manager.delete(module) plugins2count_manager.delete(module)
plugins_manager.delete(module) plugins2count_manager.save()
resources_manager.remove_resource(module) plugins2cd_manager.delete(module)
logger.info(f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据...") plugins2cd_manager.save()
except Exception as e: plugins2block_manager.delete(module)
logger.error( plugins2block_manager.save()
f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据失败...{type(e)}:{e}" 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} 插件疑似已删除,加载{none_plugin_count_manager._max_count}次失败后将清除对应插件数据,当前次数:{none_plugin_count_manager._data[module]}")
else:
none_plugin_count_manager.reset(module)
none_plugin_count_manager.save()
@@ -3,6 +3,7 @@ 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
from configs.config import Config from configs.config import Config
from services.log import logger from services.log import logger
from utils.text_utils import prompt2cn
from utils.utils import get_matchers from utils.utils import get_matchers
from ruamel import yaml from ruamel import yaml
import nonebot import nonebot
@@ -56,7 +57,9 @@ def init_plugins_config(data_path):
_override=True, _override=True,
) )
else: else:
Config.add_plugin_config(matcher.plugin_name, key, plugin_configs[key]) Config.add_plugin_config(
matcher.plugin_name, key, plugin_configs[key]
)
else: else:
plugin_configs = _data[matcher.plugin_name] plugin_configs = _data[matcher.plugin_name]
for key in plugin_configs: for key in plugin_configs:
@@ -79,7 +82,10 @@ def init_plugins_config(data_path):
_data[plugin].yaml_set_start_comment(plugin_name, indent=2) _data[plugin].yaml_set_start_comment(plugin_name, indent=2)
# 初始化未设置的管理员权限等级 # 初始化未设置的管理员权限等级
for k, v in Config.get_admin_level_data(): for k, v in Config.get_admin_level_data():
admin_manager.set_admin_level(k, v) try:
admin_manager.set_admin_level(k, v)
except KeyError as e:
raise KeyError(f"{e} ****** 请检查是否有插件加载失败 ******")
# 存完插件基本设置 # 存完插件基本设置
with open(plugins2config_file, "w", encoding="utf8") as wf: with open(plugins2config_file, "w", encoding="utf8") as wf:
round_trip_dump( round_trip_dump(
@@ -96,14 +102,23 @@ def init_plugins_config(data_path):
for plugin in Config.keys(): for plugin in Config.keys():
_tmp_data[plugin] = {} _tmp_data[plugin] = {}
for k in Config[plugin].keys(): for k in Config[plugin].keys():
if _data.get(plugin) and k in _data[plugin].keys(): try:
Config.set_config(plugin, k, _data[plugin][k]) if _data.get(plugin) and k in _data[plugin].keys():
if level2module := Config.get_level2module(plugin, k): Config.set_config(plugin, k, _data[plugin][k])
try: if level2module := Config.get_level2module(plugin, k):
admin_manager.set_admin_level(level2module, _data[plugin][k]) try:
except KeyError: admin_manager.set_admin_level(
logger.warning(f"{level2module} 设置权限等级失败:{_data[plugin][k]}") level2module, _data[plugin][k]
_tmp_data[plugin][k] = Config.get_config(plugin, k) )
except KeyError:
logger.warning(
f"{level2module} 设置权限等级失败:{_data[plugin][k]}"
)
_tmp_data[plugin][k] = Config.get_config(plugin, k)
except AttributeError as e:
raise AttributeError(
f"{e}\n" + prompt2cn("可能为config.yaml配置文件填写不规范", 46)
)
Config.save() Config.save()
temp_file = Path() / "configs" / "temp_config.yaml" temp_file = Path() / "configs" / "temp_config.yaml"
try: try:
@@ -28,7 +28,7 @@ def init_plugins_cd_limit(data_path):
_module = _plugin.module _module = _plugin.module
plugin_cd_limit = _module.__getattribute__("__plugin_cd_limit__") plugin_cd_limit = _module.__getattribute__("__plugin_cd_limit__")
plugins2cd_manager.add_cd_limit( plugins2cd_manager.add_cd_limit(
matcher.plugin_name, data_dict=plugin_cd_limit matcher.plugin_name, **plugin_cd_limit
) )
except AttributeError: except AttributeError:
pass pass
@@ -76,7 +76,7 @@ def init_plugins_block_limit(data_path):
_module = _plugin.module _module = _plugin.module
plugin_block_limit = _module.__getattribute__("__plugin_block_limit__") plugin_block_limit = _module.__getattribute__("__plugin_block_limit__")
plugins2block_manager.add_block_limit( plugins2block_manager.add_block_limit(
matcher.plugin_name, data_dict=plugin_block_limit matcher.plugin_name, **plugin_block_limit
) )
except AttributeError: except AttributeError:
pass pass
@@ -124,7 +124,7 @@ def init_plugins_count_limit(data_path):
_module = _plugin.module _module = _plugin.module
plugin_count_limit = _module.__getattribute__("__plugin_count_limit__") plugin_count_limit = _module.__getattribute__("__plugin_count_limit__")
plugins2count_manager.add_count_limit( plugins2count_manager.add_count_limit(
matcher.plugin_name, data_dict=plugin_count_limit matcher.plugin_name, **plugin_count_limit
) )
except AttributeError: except AttributeError:
pass pass
+1 -1
View File
@@ -1,6 +1,7 @@
from nonebot import on_request, on_message from nonebot import on_request, on_message
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
ActionFailed,
FriendRequestEvent, FriendRequestEvent,
GroupRequestEvent, GroupRequestEvent,
MessageEvent, MessageEvent,
@@ -8,7 +9,6 @@ from nonebot.adapters.onebot.v11 import (
from models.friend_user import FriendUser from models.friend_user import FriendUser
from datetime import datetime from datetime import datetime
from configs.config import NICKNAME, Config from configs.config import NICKNAME, Config
from nonebot.adapters.onebot.v11.exception import ActionFailed
from utils.manager import requests_manager from utils.manager import requests_manager
from models.group_info import GroupInfo from models.group_info import GroupInfo
from utils.utils import scheduler from utils.utils import scheduler
+14 -7
View File
@@ -1,4 +1,4 @@
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, PrivateMessageEvent, Message from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, PrivateMessageEvent, Message, MessageEvent
from nonebot import on_command from nonebot import on_command
from nonebot.typing import T_State from nonebot.typing import T_State
from nonebot.rule import to_me from nonebot.rule import to_me
@@ -22,9 +22,15 @@ __plugin_des__ = "区区昵称,才不想叫呢!"
__plugin_cmd__ = ["以后叫我 [昵称]", f"{NICKNAME}我是谁"] __plugin_cmd__ = ["以后叫我 [昵称]", f"{NICKNAME}我是谁"]
__plugin_version__ = 0.1 __plugin_version__ = 0.1
__plugin_author__ = "HibiKier" __plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["昵称", "昵称系统"],
}
__plugin_configs__ = { __plugin_configs__ = {
"BLACK_WORD": { "BLACK_WORD": {
"value": ["爸", "爹", "爷"], "value": ["爸", "爹", "爷", "父亲"],
"help": "昵称所屏蔽的关键词,会被替换为 *", "help": "昵称所屏蔽的关键词,会被替换为 *",
"default_value": None "default_value": None
} }
@@ -47,7 +53,7 @@ cancel_nickname = on_command("取消昵称", rule=to_me(), priority=5, block=Tru
@nickname.handle() @nickname.handle()
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()): async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip() msg = arg.extract_plain_text().strip()
if not msg: if not msg:
await nickname.finish("叫你空白?叫你虚空?叫你无名??", at_sender=True) await nickname.finish("叫你空白?叫你虚空?叫你无名??", at_sender=True)
@@ -57,8 +63,9 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
await nickname.finish("笨蛋!休想占用我的名字!#", at_sender=True) await nickname.finish("笨蛋!休想占用我的名字!#", at_sender=True)
_tmp = "" _tmp = ""
black_word = Config.get_config("nickname", "BLACK_WORD") black_word = Config.get_config("nickname", "BLACK_WORD")
for x in msg: if black_word:
_tmp += "*" if x in black_word else x for x in msg:
_tmp += "*" if x in black_word else x
msg = _tmp msg = _tmp
if isinstance(event, GroupMessageEvent): if isinstance(event, GroupMessageEvent):
if await GroupInfoUser.set_group_member_nickname( if await GroupInfoUser.set_group_member_nickname(
@@ -73,7 +80,7 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
f"好啦好啦,我知道啦,{msg},以后就这么叫你吧", f"好啦好啦,我知道啦,{msg},以后就这么叫你吧",
f"嗯嗯,{NICKNAME}记住你的昵称了哦,{msg}", f"嗯嗯,{NICKNAME}记住你的昵称了哦,{msg}",
f"好突然,突然要叫你昵称什么的...{msg}..", f"好突然,突然要叫你昵称什么的...{msg}..",
f"{NICKNAME}会好好记住的{msg}的,放心吧", f"{NICKNAME}会好好记住{msg}的,放心吧",
f"好..好.,那窝以后就叫你{msg}了.", f"好..好.,那窝以后就叫你{msg}了.",
] ]
) )
@@ -90,7 +97,7 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
f"好啦好啦,我知道啦,{msg},以后就这么叫你吧", f"好啦好啦,我知道啦,{msg},以后就这么叫你吧",
f"嗯嗯,{NICKNAME}记住你的昵称了哦,{msg}", f"嗯嗯,{NICKNAME}记住你的昵称了哦,{msg}",
f"好突然,突然要叫你昵称什么的...{msg}..", f"好突然,突然要叫你昵称什么的...{msg}..",
f"{NICKNAME}会好好记住的{msg}的,放心吧", f"{NICKNAME}会好好记住{msg}的,放心吧",
f"好..好.,那窝以后就叫你{msg}了.", f"好..好.,那窝以后就叫你{msg}了.",
] ]
) )
+68
View File
@@ -0,0 +1,68 @@
from nonebot import on_command, on_regex
from .data_source import show_plugin_repo, install_plugin, uninstall_plugin, download_json
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, MessageEvent
from nonebot.params import CommandArg
from utils.message_builder import image
from nonebot.permission import SUPERUSER
__zx_plugin_name__ = "插件商店 [Superuser]"
__plugin_usage__ = """
usage:
下载安装插件
指令:
查看插件仓库
更新插件仓库
安装插件 [name/id] (重新安装等同于更新)
卸载插件 [name/id]
""".strip()
__plugin_des__ = "从真寻适配仓库中下载插件"
__plugin_cmd__ = ["查看插件仓库", "更新插件仓库", "安装插件 [name/id]", "卸载插件 [name/id]"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
show_repo = on_regex("^查看插件仓库$", priority=1, block=True, permission=SUPERUSER)
update_repo = on_regex("^更新插件仓库$", priority=1, block=True, permission=SUPERUSER)
install_plugin_matcher = on_command("安装插件", priority=1, block=True, permission=SUPERUSER)
uninstall_plugin_matcher = on_command("卸载插件", priority=1, block=True, permission=SUPERUSER)
@install_plugin_matcher.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
arg = arg.extract_plain_text().strip()
msg = await install_plugin(arg)
await install_plugin_matcher.send(msg)
@uninstall_plugin_matcher.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
arg = arg.extract_plain_text().strip()
msg = await uninstall_plugin(arg)
await install_plugin_matcher.send(msg)
@update_repo.handle()
async def _(bot: Bot, event: MessageEvent):
code = await download_json()
if code == 200:
await update_repo.finish("更新插件仓库信息成功!")
await update_repo.send("更新插件仓库信息失败!")
@show_repo.handle()
async def _(bot: Bot, event: MessageEvent):
msg = await show_plugin_repo()
if isinstance(msg, int):
await show_repo.finish("文件下载失败或解压失败..")
await show_repo.send(image(b64=msg))
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看插件仓库"
)
+198
View File
@@ -0,0 +1,198 @@
import os
import shutil
import zipfile
from pathlib import Path
from typing import Union, Tuple
from utils.manager import plugins_manager
import ujson as json
from services import logger
from utils.http_utils import AsyncHttpx
from configs.path_config import TEMP_PATH, DATA_PATH
from utils.image_utils import text2image, BuildImage
from utils.utils import is_number
path = DATA_PATH / "plugin_shop"
if not path.exists():
path.mkdir(parents=True, exist_ok=True)
repo_json_url = "https://github.com/zhenxun-org/nonebot_plugins_zhenxun_bot/archive/refs/heads/index.zip"
repo_zip_path = TEMP_PATH / "plugin_repo_json.zip"
plugin_json = path / "zhenxun_plugins.json"
extensive_plugin_path = Path() / "extensive_plugin"
path = DATA_PATH / "plugin_shop"
if not path.exists():
path.mkdir(parents=True, exist_ok=True)
if not extensive_plugin_path.exists():
extensive_plugin_path.mkdir(parents=True, exist_ok=True)
data = {}
async def install_plugin(name: str) -> str:
"""
安装插件
:param name: 插件名或下标
"""
try:
if is_number(name):
name, code = await get_plugin_name(int(name))
if code != 200:
return name
plugin_url = data[name]["download_url"]
url = (await AsyncHttpx.get(plugin_url)).headers.get("Location")
zip_file = TEMP_PATH / f"{name}.zip"
if zip_file.exists():
zip_file.unlink()
if await AsyncHttpx.download_file(url, zip_file):
logger.debug("开始解压插件压缩包...")
# 解压
zf = zipfile.ZipFile(zip_file, "r")
extract_path = TEMP_PATH / f"{name}"
if extract_path.exists():
shutil.rmtree(extract_path.absolute(), ignore_errors=True)
extract_path.mkdir(exist_ok=True, parents=True)
for file in zf.namelist():
zf.extract(file, extract_path)
zf.close()
logger.debug("解压插件压缩包完成...")
logger.debug("开始移动插件文件夹...")
if (extensive_plugin_path / f"{name}").exists():
logger.debug("extensive_plugin目录下文件夹已存在,删除该目录插件文件夹...")
shutil.rmtree(
(extensive_plugin_path / f"{name}").absolute(), ignore_errors=True
)
extract_path.rename(extensive_plugin_path / f"{name}")
tmp = ""
if "pyproject.toml" in os.listdir(extensive_plugin_path / f"{name}"):
tmp = "检测到该插件含有额外依赖,当前安装无法保证依赖完全安装成功。"
os.system(
f"poetry run pip install -r {(extensive_plugin_path / f'{name}' / 'pyproject.toml').absolute()}"
)
elif "requirements.txt" in os.listdir(extensive_plugin_path / f"{name}"):
tmp = "检测到该插件含有额外依赖,当前安装无法保证依赖完全安装成功。"
os.system(
f"poetry run pip install -r {(extensive_plugin_path / f'{name}' / 'requirements.txt').absolute()}"
)
with open(extensive_plugin_path / f"{name}" / "plugin_info.json", "w") as f:
json.dump(data[name], f, ensure_ascii=False, indent=4)
logger.debug("移动插件文件夹完成...")
logger.info(f"成功安装插件 {name} 成功!\n{tmp}")
return f"成功安装插件 {name},请重启真寻!"
except Exception as e:
logger.error(f"安装插件 {name} 失败 {type(e)}:{e}")
return f"安装插件 {name} 失败 {type(e)}:{e}"
async def uninstall_plugin(name: str) -> str:
"""
删除插件
:param name: 插件名或下标
"""
try:
if is_number(name):
name, code = await get_plugin_name(int(name))
if code != 200:
return name
if name not in os.listdir(extensive_plugin_path):
return f"未安装 {name} 插件!"
shutil.rmtree((extensive_plugin_path / name).absolute(), ignore_errors=True)
logger.info(f"插件 {name} 删除成功!")
return f"插件 {name} 删除成功!"
except Exception as e:
logger.error(f"删除插件 {name} 失败 {type(e)}:{e}")
return f"删除插件 {name} 失败 {type(e)}:{e}"
async def show_plugin_repo() -> Union[int, str]:
"""
获取插件仓库数据并格式化
"""
if not plugin_json.exists():
code = await download_json()
if code != 200:
return code
plugin_info = json.load(open(plugin_json, "r", encoding="utf8"))
load_plugin_list = plugins_manager.get_data().keys()
image_list = []
w, h = 0, 0
line_height = 10
for i, key in enumerate(plugin_info.keys()):
data[key] = {
"名称": plugin_info[key]["plugin_name"],
"模块": key,
"作者": plugin_info[key]["author"],
"版本": plugin_info[key]["version"],
"简介": plugin_info[key]["introduction"],
"download_url": plugin_info[key]["download_url"],
"github_url": plugin_info[key]["github_url"],
}
status = ""
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>"
s = (
f'id:{i+1}\n名称:{plugin_info[key]["plugin_name"]}'
f' \t\t{status}\n'
f"模块:{key}\n"
f'作者:{plugin_info[key]["author"]}\n'
f'版本:{plugin_info[key]["version"]} \t\t{version}\n'
f'简介:{plugin_info[key]["introduction"]}\n'
f"-------------------"
)
img = await text2image(s, font_size=20, color="#f9f6f2")
w = w if w > img.w else img.w
h += img.h + line_height
image_list.append(img)
A = BuildImage(w + 50, h + 50, color="#f9f6f2")
cur_h = 25
for img in image_list:
await A.apaste(img, (25, cur_h))
cur_h += img.h + line_height
return A.pic2bs4()
async def download_json() -> int:
"""
下载插件库json文件
"""
try:
url = (await AsyncHttpx.get(repo_json_url)).headers.get("Location")
if repo_zip_path.exists():
repo_zip_path.unlink()
if await AsyncHttpx.download_file(url, repo_zip_path):
zf = zipfile.ZipFile(repo_zip_path, "r")
extract_path = path / "temp"
for file in zf.namelist():
zf.extract(file, extract_path)
zf.close()
if plugin_json.exists():
plugin_json.unlink()
(
extract_path
/ "nonebot_plugins_zhenxun_bot-index"
/ "zhenxun_plugins.json"
).rename(plugin_json)
shutil.rmtree(extract_path.absolute(), ignore_errors=True)
return 200
except Exception as e:
logger.error(f"下载插件库压缩包失败或解压失败 {type(e)}:{e}")
return 999
async def get_plugin_name(name: int) -> Tuple[str, int]:
"""
通过下标获取插件名
:param name: 下标
"""
name = int(name)
if not data:
await show_plugin_repo()
if name < 1 or name > len(data.keys()):
return "下标超过上下限!", 999
name = list(data.keys())[name - 1]
return name, 200
+4
View File
@@ -108,6 +108,10 @@ async def _():
"ALTER TABLE genshin ADD bind_group Integer;", "ALTER TABLE genshin ADD bind_group Integer;",
"genshin" "genshin"
), # 新增原神群号绑定字段 ), # 新增原神群号绑定字段
(
"ALTER TABLE chat_history ADD plain_text Text;",
"chat_history"
), # 新增纯文本
] ]
for sql in sql_str: for sql in sql_str:
try: try:
+7 -2
View File
@@ -1,9 +1,10 @@
from nonebot import on_command from nonebot import on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message, ActionFailed
from nonebot.params import CommandArg from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11.permission import GROUP from nonebot.adapters.onebot.v11.permission import GROUP
from utils.data_utils import init_rank from utils.data_utils import init_rank
from models.bag_user import BagUser from models.bag_user import BagUser
from utils.image_utils import text2image
from utils.message_builder import image from utils.message_builder import image
from utils.utils import is_number from utils.utils import is_number
@@ -34,7 +35,11 @@ gold_rank = on_command("金币排行", priority=5, block=True, permission=GROUP)
@my_gold.handle() @my_gold.handle()
async def _(event: GroupMessageEvent): async def _(event: GroupMessageEvent):
await my_gold.finish(await BagUser.get_user_total_gold(event.user_id, event.group_id)) msg = await BagUser.get_user_total_gold(event.user_id, event.group_id)
try:
await my_gold.send(msg)
except ActionFailed:
await my_gold.send(image(b64=(await text2image(msg, color="#f9f6f2", padding=10)).pic2bs4()))
@gold_rank.handle() @gold_rank.handle()
+1 -1
View File
@@ -26,7 +26,7 @@ class GoodsUseFuncManager:
判断商品使用方法是否被注册 判断商品使用方法是否被注册
:param goods_name: 商品名称 :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: def get_max_num_limit(self, goods_name: str) -> int:
""" """
+6 -6
View File
@@ -119,18 +119,18 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
) )
flag = await requests_manager.approve(bot, id_, "group") flag = await requests_manager.approve(bot, id_, "group")
else: else:
await friend_handle.send("同意群聊请求失败,未找到此id的请求..") await group_handle.send("同意群聊请求失败,未找到此id的请求..")
else: else:
flag = await requests_manager.refused(bot, id_, "group") flag = await requests_manager.refused(bot, id_, "group")
if flag == 1: if flag == 1:
await friend_handle.send(f"{cmd[:2]}群聊请求失败,该请求已失效..") await group_handle.send(f"{cmd[:2]}群聊请求失败,该请求已失效..")
requests_manager.delete_request(id_, "group") requests_manager.delete_request(id_, "group")
elif flag == 2: elif flag == 2:
await friend_handle.send(f"{cmd[:2]}群聊请求失败,未找到此id的请求..") await group_handle.send(f"{cmd[:2]}群聊请求失败,未找到此id的请求..")
else: else:
await friend_handle.send(f"{cmd[:2]}群聊请求成功!") await group_handle.send(f"{cmd[:2]}群聊请求成功!")
else: else:
await friend_handle.send("id必须为纯数字!") await group_handle.send("id必须为纯数字!")
@cls_request.handle() @cls_request.handle()
@@ -150,4 +150,4 @@ async def _():
@clear_request.handle() @clear_request.handle()
async def _(): async def _():
requests_manager.clear() requests_manager.clear()
await cls_request.send("已清空所有好友/群聊请求..") await clear_request.send("已清空所有好友/群聊请求..")
+11 -11
View File
@@ -1,4 +1,11 @@
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GROUP, GroupMessageEvent, Message from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GROUP,
GroupMessageEvent,
Message,
ActionFailed,
)
from nonebot import on_command, on_regex from nonebot import on_command, on_regex
from nonebot.permission import SUPERUSER from nonebot.permission import SUPERUSER
from nonebot.typing import T_State from nonebot.typing import T_State
@@ -8,7 +15,6 @@ from utils.manager import group_manager, plugins2settings_manager
from models.group_info import GroupInfo from models.group_info import GroupInfo
from services.log import logger from services.log import logger
from configs.config import NICKNAME from configs.config import NICKNAME
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.params import Command, CommandArg from nonebot.params import Command, CommandArg
from typing import Tuple from typing import Tuple
@@ -137,9 +143,7 @@ async def _():
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()): async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0] cmd = cmd[0]
msg = arg.extract_plain_text().strip().split() msg = arg.extract_plain_text().strip().split()
all_group = [ all_group = [g["group_id"] for g in await bot.get_group_list()]
g["group_id"] for g in await bot.get_group_list()
]
group_list = [] group_list = []
for group in msg: for group in msg:
if is_number(group) and int(group) in all_group: if is_number(group) and int(group) in all_group:
@@ -151,9 +155,7 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
else: else:
group_manager.delete_group_white_list(group) group_manager.delete_group_white_list(group)
group_list = [str(x) for x in group_list] group_list = [str(x) for x in group_list]
await manager_group_whitelist.send( await manager_group_whitelist.send("已成功将 " + "\n".join(group_list) + " " + cmd)
"已成功将 " + "\n".join(group_list) + " " + cmd
)
else: else:
await manager_group_whitelist.send(f"添加失败,请检查{NICKNAME}是否已加入这些群聊或重复添加/删除群白单名") await manager_group_whitelist.send(f"添加失败,请检查{NICKNAME}是否已加入这些群聊或重复添加/删除群白单名")
@@ -199,6 +201,4 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
else: else:
if await GroupInfo.get_group_info(group_id): if await GroupInfo.get_group_info(group_id):
await GroupInfo.set_group_flag(group_id, 0) await GroupInfo.set_group_flag(group_id, 0)
await group_auth.send( await group_auth.send(f"已为 {group_id} {cmd[:2]}群认证..")
f'已为 {group_id} {cmd[:2]}群认证..'
)
+1
View File
@@ -12,6 +12,7 @@ driver.on_shutdown(disconnect)
nonebot.load_plugin("nonebot_plugin_apscheduler") nonebot.load_plugin("nonebot_plugin_apscheduler")
nonebot.load_plugins("basic_plugins") nonebot.load_plugins("basic_plugins")
nonebot.load_plugins("plugins") nonebot.load_plugins("plugins")
nonebot.load_plugins("extensive_plugin")
# 最后加载权限控制 # 最后加载权限控制
nonebot.load_plugins("basic_plugins/hooks") nonebot.load_plugins("basic_plugins/hooks")
+34 -8
View File
@@ -2,6 +2,7 @@ from typing import Optional, Any, Union
from pathlib import Path from pathlib import Path
from ruamel.yaml import YAML from ruamel.yaml import YAML
from ruamel import yaml from ruamel import yaml
from ruamel.yaml.scanner import ScannerError
class ConfigsManager: class ConfigsManager:
@@ -21,9 +22,24 @@ class ConfigsManager:
if file.exists(): if file.exists():
with open(file, "r", encoding="utf8") as f: with open(file, "r", encoding="utf8") as f:
self._data = _yaml.load(f) self._data = _yaml.load(f)
if not self._data:
self.file.unlink()
raise ValueError(
"配置文件为空!\n"
"***********************************************************\n"
"****** 配置文件 plugins2config.yaml 为空,已删除,请重启 ******\n"
"***********************************************************"
)
if self._simple_file.exists(): if self._simple_file.exists():
with open(self._simple_file, "r", encoding="utf8") as f: try:
self._simple_data = _yaml.load(f) with open(self._simple_file, "r", encoding="utf8") as f:
self._simple_data = _yaml.load(f)
except ScannerError as e:
raise ScannerError(
f"{e}\n**********************************************\n"
f"****** 可能为config.yaml配置文件填写不规范 ******\n"
f"**********************************************"
)
def add_plugin_config( def add_plugin_config(
self, self,
@@ -78,18 +94,22 @@ class ConfigsManager:
del self._data[module] del self._data[module]
self.save() self.save()
def set_config(self, module: str, key: str, value: str): def set_config(self, module: str, key: str, value: Any , save_simple_data: bool = False):
""" """
设置配置值 设置配置值
:param module: 模块名 :param module: 模块名
:param key: 配置名称 :param key: 配置名称
:param value: 值 :param value: 值
:param save_simple_data: 同时保存至config.yaml
""" """
if module in self._data.keys(): if module in self._data.keys():
if self._data[module].get(key) is not None and self._data[module][key] != value: if (
self._data[module].get(key) is not None
and self._data[module][key] != value
):
self._data[module][key]["value"] = value self._data[module][key]["value"] = value
self._simple_data[module][key] = value self._simple_data[module][key] = value
self.save() self.save(save_simple_data = save_simple_data)
def set_help(self, module: str, key: str, help_: str): def set_help(self, module: str, key: str, help_: str):
""" """
@@ -103,7 +123,7 @@ class ConfigsManager:
self._data[module][key]["help"] = help_ self._data[module][key]["help"] = help_
self.save() self.save()
def set_default_value(self, module: str, key: str, value: str): def set_default_value(self, module: str, key: str, value: Any):
""" """
设置配置默认值 设置配置默认值
:param module: 模块名 :param module: 模块名
@@ -115,7 +135,9 @@ class ConfigsManager:
self._data[module][key]["default_value"] = value self._data[module][key]["default_value"] = value
self.save() self.save()
def get_config(self, module: str, key: str, default: Optional[Any] = None) -> Optional[Any]: def get_config(
self, module: str, key: str, default: Optional[Any] = None
) -> Optional[Any]:
""" """
获取指定配置值 获取指定配置值
:param module: 模块名 :param module: 模块名
@@ -161,7 +183,11 @@ class ConfigsManager:
if save_simple_data: if save_simple_data:
with open(self._simple_file, "w", encoding="utf8") as f: with open(self._simple_file, "w", encoding="utf8") as f:
yaml.dump( yaml.dump(
self._simple_data, f, indent=2, Dumper=yaml.RoundTripDumper, allow_unicode=True self._simple_data,
f,
indent=2,
Dumper=yaml.RoundTripDumper,
allow_unicode=True,
) )
path = path if path else self.file path = path if path else self.file
with open(path, "w", encoding="utf8") as f: with open(path, "w", encoding="utf8") as f:
+3 -3
View File
@@ -11,12 +11,13 @@ class ChatHistory(db.Model):
user_qq = db.Column(db.BigInteger(), nullable=False) user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.BigInteger()) group_id = db.Column(db.BigInteger())
text = db.Column(db.Text()) text = db.Column(db.Text())
plain_text = db.Column(db.Text())
create_time = db.Column(db.DateTime(timezone=True), nullable=False) create_time = db.Column(db.DateTime(timezone=True), nullable=False)
@classmethod @classmethod
async def add_chat_msg(cls, user_qq: int, group_id: Optional[int], text: str): async def add_chat_msg(cls, user_qq: int, group_id: Optional[int], text: str, plain_text: str):
await cls.create( await cls.create(
user_qq=user_qq, group_id=group_id, text=text, create_time=datetime.now() user_qq=user_qq, group_id=group_id, text=text, plain_text=plain_text, create_time=datetime.now()
) )
@classmethod @classmethod
@@ -97,7 +98,6 @@ class ChatHistory(db.Model):
if date_scope: if date_scope:
sql += f"AND create_time BETWEEN '{date_scope[0]}' AND '{date_scope[1]}' " sql += f"AND create_time BETWEEN '{date_scope[0]}' AND '{date_scope[1]}' "
sql += f"GROUP BY user_qq ORDER BY sum {order if order and order.upper() != 'DES' else ''} LIMIT {limit}" sql += f"GROUP BY user_qq ORDER BY sum {order if order and order.upper() != 'DES' else ''} LIMIT {limit}"
print(sql)
return await db.all(db.text(sql)) return await db.all(db.text(sql))
@classmethod @classmethod
-25
View File
@@ -1,7 +1,3 @@
from nonebot.adapters.onebot.v11 import MessageSegment
from utils.image_utils import BuildImage
from utils.message_builder import image
from configs.path_config import IMAGE_PATH
from typing import Optional, Tuple, Union from typing import Optional, Tuple, Union
from configs.config import Config from configs.config import Config
from utils.http_utils import AsyncHttpx from utils.http_utils import AsyncHttpx
@@ -28,24 +24,3 @@ async def get_data(url: str, params: Optional[dict] = None) -> Tuple[Union[dict,
return f'发生了错误...code:{data["code"]}', 999 return f'发生了错误...code:{data["code"]}', 999
except TimeoutError: except TimeoutError:
return "超时了....", 998 return "超时了....", 998
def gen_wbtop_pic(data: dict) -> MessageSegment:
"""
生成微博热搜图片
:param data: 微博热搜数据
"""
bk = BuildImage(700, 32 * 50 + 280, 700, 32, color="#797979")
wbtop_bk = BuildImage(700, 280, background=f"{IMAGE_PATH}/other/webtop.png")
bk.paste(wbtop_bk)
text_bk = BuildImage(700, 32 * 50, 700, 32, color="#797979")
for i, data in enumerate(data):
title = f"{i+1}. {data['hot_word']}"
hot = data["hot_word_num"]
img = BuildImage(700, 30, font_size=20)
w, h = img.getsize(title)
img.text((10, int((30 - h) / 2)), title)
img.text((580, int((30 - h) / 2)), hot)
text_bk.paste(img)
bk.paste(text_bk, (0, 280))
return image(b64=bk.pic2bs4())
+4 -2
View File
@@ -228,12 +228,14 @@ async def send_sub_msg(rst: str, sub: BilibiliSub, bot: Bot):
:param sub: BilibiliSub :param sub: BilibiliSub
:param bot: Bot :param bot: Bot
""" """
temp_group = []
if rst: if rst:
for x in sub.sub_users.split(",")[:-1]: for x in sub.sub_users.split(",")[:-1]:
try: try:
if ":" in x: if ":" in x and x.split(":")[1] not in temp_group:
temp_group.append(x.split(":")[1])
await bot.send_group_msg( await bot.send_group_msg(
group_id=int(x.split(":")[1]), message=Message(rst) group_id=int(x.split(":")[1]), message=Message(rst)
) )
else: else:
await bot.send_private_msg(user_id=int(x), message=Message(rst)) await bot.send_private_msg(user_id=int(x), message=Message(rst))
+1 -1
View File
@@ -330,7 +330,7 @@ async def get_user_dynamic(
""" """
xs = document.getElementsByClassName('bili-dyn-item__tag'); xs = document.getElementsByClassName('bili-dyn-item__tag');
for (x of xs) { for (x of xs) {
x.parentNode.remove(); x.parentNode.parentNode.remove();
} }
""" """
) )
-1
View File
@@ -38,7 +38,6 @@ async def create_live_des_image(uid: int, title: str, cover: str, tags: str, des
ava = BuildImage(100, 100, background=BytesIO(await get_pic(face))) ava = BuildImage(100, 100, background=BytesIO(await get_pic(face)))
ava.circle() ava.circle()
cover = BuildImage(470, 265, background=BytesIO(await get_pic(cover))) cover = BuildImage(470, 265, background=BytesIO(await get_pic(cover)))
print()
def _create_live_des_image( def _create_live_des_image(
+5 -1
View File
@@ -8,6 +8,7 @@ from nonebot.adapters.onebot.v11 import (
from nonebot.matcher import Matcher from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor from nonebot.message import run_preprocessor
from utils.image_utils import BuildImage from utils.image_utils import BuildImage
from utils.manager import group_manager
from utils.utils import get_message_text, is_number from utils.utils import get_message_text, is_number
from nonebot.params import RegexGroup, CommandArg from nonebot.params import RegexGroup, CommandArg
from .utils import black_word_manager from .utils import black_word_manager
@@ -155,7 +156,11 @@ async def _(
and matcher.plugin_name == "black_word" and matcher.plugin_name == "black_word"
and not await BanUser.is_ban(event.user_id) and not await BanUser.is_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers and str(event.user_id) not in bot.config.superusers
and not get_message_text(event.json()).startswith("原神绑定")
): ):
# 屏蔽群权限-1的群
if isinstance(event, GroupMessageEvent) and group_manager.get_group_level(event.group_id) < 0:
return
user_id = event.user_id user_id = event.user_id
group_id = event.group_id if isinstance(event, GroupMessageEvent) else None group_id = event.group_id if isinstance(event, GroupMessageEvent) else None
msg = get_message_text(event.json()) msg = get_message_text(event.json())
@@ -241,7 +246,6 @@ async def _(event: MessageEvent, arg: Message = CommandArg()):
uid = int(msg[0]) uid = int(msg[0])
id_ = int(msg[1]) id_ = int(msg[1])
punish_level = int(msg[2]) punish_level = int(msg[2])
print(uid, id_, punish_level)
rst = await set_user_punish(uid, id_, punish_level) rst = await set_user_punish(uid, id_, punish_level)
await set_punish.send(rst) await set_punish.send(rst)
logger.info( logger.info(
-1
View File
@@ -68,7 +68,6 @@ class BlackWord(db.Model):
user = await query.where(cls.black_word == black_word).order_by(cls.id.desc()).gino.first() user = await query.where(cls.black_word == black_word).order_by(cls.id.desc()).gino.first()
elif id_: elif id_:
user_list = await query.gino.all() user_list = await query.gino.all()
print(len(user_list))
if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)): if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)):
return False return False
user = user_list[id_] user = user_list[id_]
+1 -3
View File
@@ -6,7 +6,7 @@ from configs.config import Config
from pathlib import Path from pathlib import Path
from services.log import logger from services.log import logger
from models.ban_user import BanUser from models.ban_user import BanUser
from nonebot.adapters.onebot.v11.exception import ActionFailed from nonebot.adapters.onebot.v11 import ActionFailed
from models.group_member_info import GroupInfoUser from models.group_member_info import GroupInfoUser
from utils.http_utils import AsyncHttpx from utils.http_utils import AsyncHttpx
import random import random
@@ -88,9 +88,7 @@ class BlackWordManager:
:param group_id: 群号 :param group_id: 群号
:param message: 消息 :param message: 消息
""" """
print(user_id, group_id, message)
if data := self._check(message): if data := self._check(message):
print(data)
if data[0]: if data[0]:
await _add_user_black_word( await _add_user_black_word(
user_id, group_id, data[0], message, int(data[1]) user_id, group_id, data[0], message, int(data[1])
+1 -1
View File
@@ -80,8 +80,8 @@ async def _(
except TimeoutError: except TimeoutError:
await bt.finish(f"搜索 {keyword} 超时...") await bt.finish(f"搜索 {keyword} 超时...")
except Exception as e: except Exception as e:
await bt.finish(f"bt 其他未知错误..")
logger.error(f"bt 错误 {type(e)}:{e}") logger.error(f"bt 错误 {type(e)}:{e}")
await bt.finish(f"bt 其他未知错误..")
if not send_flag: if not send_flag:
await bt.send(f"{keyword} 未搜索到...") await bt.send(f"{keyword} 未搜索到...")
logger.info(f"USER {event.user_id} BT搜索 {keyword} 第 {page} 页") logger.info(f"USER {event.user_id} BT搜索 {keyword} 第 {page} 页")
+2 -2
View File
@@ -9,7 +9,7 @@ import platform
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
url = "http://www.eclzz.mobi" url = "http://www.eclzz.one/"
async def get_bt_info(keyword: str, page: int): async def get_bt_info(keyword: str, page: int):
@@ -19,7 +19,7 @@ async def get_bt_info(keyword: str, page: int):
:param page: 页数 :param page: 页数
""" """
text = (await AsyncHttpx.get(f"{url}/s/{keyword}_rel_{page}.html", timeout=5)).text text = (await AsyncHttpx.get(f"{url}/s/{keyword}_rel_{page}.html", timeout=5)).text
if text.find("大约0条结果") != -1: if "大约0条结果" in text:
return return
soup = BeautifulSoup(text, "lxml") soup = BeautifulSoup(text, "lxml")
item_lst = soup.find_all("div", {"class": "search-item"}) item_lst = soup.find_all("div", {"class": "search-item"})
+30 -24
View File
@@ -5,7 +5,7 @@ from .data_source import check_update, get_latest_version_data
from services.log import logger from services.log import logger
from utils.utils import scheduler, get_bot from utils.utils import scheduler, get_bot
from pathlib import Path from pathlib import Path
from configs.config import Config from configs.config import NICKNAME, Config
from nonebot.rule import to_me from nonebot.rule import to_me
from nonebot.params import ArgStr from nonebot.params import ArgStr
import platform import platform
@@ -25,6 +25,11 @@ __plugin_cmd__ = ["检查更新真寻", "重启"]
__plugin_version__ = 0.1 __plugin_version__ = 0.1
__plugin_author__ = "HibiKier" __plugin_author__ = "HibiKier"
__plugin_configs__ = { __plugin_configs__ = {
"UPDATE_REMIND": {
"value": True,
"help": "真寻是否检测版本状态",
"default": True,
},
"AUTO_UPDATE_ZHENXUN": { "AUTO_UPDATE_ZHENXUN": {
"value": False, "value": False,
"help": "真寻是否自动检查更新", "help": "真寻是否自动检查更新",
@@ -66,18 +71,18 @@ async def _(bot: Bot):
) )
@restart.handle()
async def _():
if str(platform.system()).lower() == "windows":
await restart.finish("暂无windows重启脚本...")
@restart.got("flag", prompt=f"确定是否重启{NICKNAME}?确定请回复[是|好|确定](重启失败咱们将失去联系,请谨慎!)")
@restart.got("flag", prompt="确定是否重启真寻?(重启失败咱们将失去联系,请谨慎!)")
async def _(flag: str = ArgStr("flag")): async def _(flag: str = ArgStr("flag")):
if flag.lower() in ["true", "是", "好", "确定", "确定是"]: if flag.lower() in ["true", "是", "好", "确定", "确定是"]:
await restart.send("开始重启真寻..请稍等...") await restart.send(f"开始重启{NICKNAME}..请稍等...")
open("is_restart", "w") open("is_restart", "w")
os.system("./restart.sh") if str(platform.system()).lower() == "windows":
import sys
python = sys.executable
os.execl(python, python, *sys.argv)
else:
os.system("./restart.sh")
else: else:
await restart.send("已取消操作...") await restart.send("已取消操作...")
@@ -88,7 +93,7 @@ async def _(flag: str = ArgStr("flag")):
minute=0, minute=0,
) )
async def _(): async def _():
if Config.get_config("check_zhenxun_update", "AUTO_UPDATE_ZHENXUN"): if Config.get_config("check_zhenxun_update", "UPDATE_REMIND"):
_version = "v0.0.0" _version = "v0.0.0"
_version_file = Path() / "__version__" _version_file = Path() / "__version__"
if _version_file.exists(): if _version_file.exists():
@@ -108,17 +113,18 @@ async def _():
message=f"检测到真寻版本更新\n" message=f"检测到真寻版本更新\n"
f"当前版本:{_version},最新版本:{latest_version}", f"当前版本:{_version},最新版本:{latest_version}",
) )
# try: if Config.get_config("check_zhenxun_update", "AUTO_UPDATE_ZHENXUN"):
# code = await check_update(bot) try:
# except Exception as e: code = await check_update(bot)
# logger.error(f"更新真寻未知错误 {type(e)}:{e}") except Exception as e:
# await bot.send_private_msg( logger.error(f"更新真寻未知错误 {type(e)}:{e}")
# user_id=int(list(bot.config.superusers)[0]), await bot.send_private_msg(
# message=f"更新真寻未知错误 {type(e)}:{e}\n", user_id=int(list(bot.config.superusers)[0]),
# ) message=f"更新真寻未知错误 {type(e)}:{e}\n",
# else: )
# if code == 200: else:
# await bot.send_private_msg( if code == 200:
# user_id=int(list(bot.config.superusers)[0]), await bot.send_private_msg(
# message=f"更新完毕,请重启真寻....", user_id=int(list(bot.config.superusers)[0]),
# ) message=f"更新完毕,请重启{NICKNAME}....",
)
+5 -2
View File
@@ -162,7 +162,7 @@ def _file_handle(latest_version: str) -> str:
if backup_file.exists(): if backup_file.exists():
backup_file.unlink() backup_file.unlink()
if file not in [config_file, config_path_file]: if file not in [config_file, config_path_file]:
os.rename(file.absolute(), backup_file.absolute()) shutil.move(file.absolute(), backup_file.absolute())
else: else:
with open(file, "r", encoding="utf8") as rf: with open(file, "r", encoding="utf8") as rf:
data = rf.read() data = rf.read()
@@ -174,7 +174,7 @@ def _file_handle(latest_version: str) -> str:
old_file = Path() / file old_file = Path() / file
if old_file not in [config_file, config_path_file] and file != "configs": if old_file not in [config_file, config_path_file] and file != "configs":
if not old_file.exists() and new_file.exists(): if not old_file.exists() and new_file.exists():
os.rename(new_file.absolute(), old_file.absolute()) shutil.move(new_file.absolute(), old_file.absolute())
logger.info(f"已更新文件:{file}") logger.info(f"已更新文件:{file}")
# except Exception as e: # except Exception as e:
# error = f'{type(e)}:{e}' # error = f'{type(e)}:{e}'
@@ -189,6 +189,9 @@ def _file_handle(latest_version: str) -> str:
local_update_info_file.unlink() local_update_info_file.unlink()
with open(_version_file, "w", encoding="utf8") as f: with open(_version_file, "w", encoding="utf8") as f:
f.write(f"__version__: {latest_version}") f.write(f"__version__: {latest_version}")
os.system(
f"poetry run pip install -r {(Path() / 'pyproject.toml').absolute()}"
)
return error return error
+1 -1
View File
@@ -53,7 +53,7 @@ __plugin_settings__ = {
dialogue_data = {} dialogue_data = {}
dialogue = on_command("[滴滴滴]", aliases={"滴滴滴-"}, priority=5, block=True) dialogue = on_command("&#91;滴滴滴&#93;", aliases={"滴滴滴-"}, priority=5, block=True)
reply = on_command("/t", priority=1, permission=SUPERUSER, block=True) reply = on_command("/t", priority=1, permission=SUPERUSER, block=True)
+11 -2
View File
@@ -23,6 +23,7 @@ from .handles.onmyoji_handle import OnmyojiHandle
from .handles.pcr_handle import PcrHandle from .handles.pcr_handle import PcrHandle
from .handles.pretty_handle import PrettyHandle from .handles.pretty_handle import PrettyHandle
from .handles.prts_handle import PrtsHandle from .handles.prts_handle import PrtsHandle
from .handles.ba_handle import BaHandle
from .config import draw_config from .config import draw_config
@@ -30,7 +31,7 @@ from .config import draw_config
__zx_plugin_name__ = "游戏抽卡" __zx_plugin_name__ = "游戏抽卡"
__plugin_usage__ = """ __plugin_usage__ = """
usage: usage:
模拟赛马娘,原神,明日方舟,坎公骑冠剑,公主连结(国/台),碧蓝航线,FGO,阴阳师进行抽卡 模拟赛马娘,原神,明日方舟,坎公骑冠剑,公主连结(国/台),碧蓝航线,FGO,阴阳师,碧蓝档案进行抽卡
指令: 指令:
原神[1-180]抽: 原神常驻池 原神[1-180]抽: 原神常驻池
原神角色[1-180]抽: 原神角色UP池子 原神角色[1-180]抽: 原神角色UP池子
@@ -43,6 +44,7 @@ usage:
碧蓝航线/碧蓝[重型/轻型/特型/活动][1-300]抽: 碧蓝航线重型/轻型/特型/活动卡池 碧蓝航线/碧蓝[重型/轻型/特型/活动][1-300]抽: 碧蓝航线重型/轻型/特型/活动卡池
fgo[1-300]抽: fgo卡池 fgo[1-300]抽: fgo卡池
阴阳师[1-300]抽: 阴阳师卡池 阴阳师[1-300]抽: 阴阳师卡池
ba/碧蓝档案[1-200]抽:碧蓝档案卡池
* 以上指令可以通过 XX一井 来指定最大抽取数量 * * 以上指令可以通过 XX一井 来指定最大抽取数量 *
* 示例:原神一井 * * 示例:原神一井 *
""".strip() """.strip()
@@ -73,6 +75,7 @@ __plugin_cmd__ = [
"pcr/公主连接[1-300]抽", "pcr/公主连接[1-300]抽",
"fgo[1-300]抽", "fgo[1-300]抽",
"阴阳师[1-300]抽", "阴阳师[1-300]抽",
"碧蓝档案[1-200]抽",
"更新方舟信息 [_superuser]", "更新方舟信息 [_superuser]",
"重载方舟卡池 [_superuser]", "重载方舟卡池 [_superuser]",
"更新原神信息 [_superuser]", "更新原神信息 [_superuser]",
@@ -83,6 +86,7 @@ __plugin_cmd__ = [
"更新碧蓝航线信息 [_superuser]", "更新碧蓝航线信息 [_superuser]",
"更新fgo信息 [_superuser]", "更新fgo信息 [_superuser]",
"更新阴阳师信息 [_superuser]", "更新阴阳师信息 [_superuser]",
"更新碧蓝档案信息 [_superuser]",
] ]
__plugin_type__ = ("抽卡相关", 1) __plugin_type__ = ("抽卡相关", 1)
__plugin_version__ = 0.1 __plugin_version__ = 0.1
@@ -105,7 +109,7 @@ class Game:
games = ( games = (
Game({"azur", "碧蓝", "碧蓝航线"}, AzurHandle(), draw_config.AZUR_FLAG), Game({"azur", "碧蓝航线"}, AzurHandle(), draw_config.AZUR_FLAG),
Game({"fgo", "命运冠位指定"}, FgoHandle(), draw_config.FGO_FLAG), Game({"fgo", "命运冠位指定"}, FgoHandle(), draw_config.FGO_FLAG),
Game( Game(
{"genshin", "原神"}, {"genshin", "原神"},
@@ -130,6 +134,11 @@ games = (
reload_time=4, reload_time=4,
), ),
Game({"prts", "方舟", "明日方舟"}, PrtsHandle(), draw_config.PRTS_FLAG, reload_time=4), Game({"prts", "方舟", "明日方舟"}, PrtsHandle(), draw_config.PRTS_FLAG, reload_time=4),
Game(
{"ba","碧蓝档案"},BaHandle(),
draw_config.BA_FLAG,
max_count=200,
),
) )
+10 -1
View File
@@ -87,6 +87,12 @@ class OnmyojiConfig(BaseModel, extra=Extra.ignore):
ONMYOJI_SR: float = 0.2 ONMYOJI_SR: float = 0.2
ONMYOJI_R: float = 0.7875 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): class Config(BaseModel, extra=Extra.ignore):
# 开关 # 开关
@@ -98,6 +104,7 @@ class Config(BaseModel, extra=Extra.ignore):
AZUR_FLAG: bool = AConfig.get_config("draw_card", "AZUR_FLAG") AZUR_FLAG: bool = AConfig.get_config("draw_card", "AZUR_FLAG")
FGO_FLAG: bool = AConfig.get_config("draw_card", "FGO_FLAG") FGO_FLAG: bool = AConfig.get_config("draw_card", "FGO_FLAG")
ONMYOJI_FLAG: bool = AConfig.get_config("draw_card", "ONMYOJI_FLAG") ONMYOJI_FLAG: bool = AConfig.get_config("draw_card", "ONMYOJI_FLAG")
BA_FLAG: bool = AConfig.get_config("draw_card", "BA_FLAG")
# 其他配置 # 其他配置
PCR_TAI: bool = AConfig.get_config("draw_card", "PCR_TAI") PCR_TAI: bool = AConfig.get_config("draw_card", "PCR_TAI")
@@ -112,6 +119,7 @@ class Config(BaseModel, extra=Extra.ignore):
azur: AzurConfig = AzurConfig() azur: AzurConfig = AzurConfig()
fgo: FgoConfig = FgoConfig() fgo: FgoConfig = FgoConfig()
onmyoji: OnmyojiConfig = OnmyojiConfig() onmyoji: OnmyojiConfig = OnmyojiConfig()
ba: BaConfig = BaConfig()
driver = nonebot.get_driver() driver = nonebot.get_driver()
@@ -133,8 +141,9 @@ for game_flag, game_name in zip(
"FGO_FLAG", "FGO_FLAG",
"ONMYOJI_FLAG", "ONMYOJI_FLAG",
"PCR_TAI", "PCR_TAI",
"BA_FLAG"
], ],
["明日方舟", "原神", "赛马娘", "坎公骑冠剑", "公主连结", "碧蓝航线", "命运-冠位指定(FGO)", "阴阳师", "pcr台服卡池"], ["明日方舟", "原神", "赛马娘", "坎公骑冠剑", "公主连结", "碧蓝航线", "命运-冠位指定(FGO)", "阴阳师", "pcr台服卡池","碧蓝档案"],
): ):
AConfig.add_plugin_config( AConfig.add_plugin_config(
"draw_card", "draw_card",
+1 -1
View File
@@ -293,7 +293,7 @@ class AzurHandle(BaseHandle[AzurChar]):
type_ = ship.xpath("./tbody/tr/td[2]/p/small/text()")[0] # 舰船类型 type_ = ship.xpath("./tbody/tr/td[2]/p/small/text()")[0] # 舰船类型
try: try:
p = float(str(ship.xpath(".//sup/text()")[0]).strip("%")) p = float(str(ship.xpath(".//sup/text()")[0]).strip("%"))
except IndexError: except (IndexError, ValueError):
p = 0 p = 0
star = self.parse_star( star = self.parse_star(
ship.xpath("./tbody/tr/td[1]/div/div/div/a/img/@alt")[0] ship.xpath("./tbody/tr/td[1]/div/div/div/a/img/@alt")[0]
+150
View File
@@ -0,0 +1,150 @@
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 utils.image_utils import BuildImage
class BaChar(BaseData):
pass
class BaHandle(BaseHandle[BaChar]):
def __init__(self):
super().__init__("ba", "碧蓝档案")
self.max_star = 3
self.config = draw_config.ba
self.ALL_CHAR: List[BaChar] = []
def get_card(self, mode: int = 1) -> BaChar:
if mode == 2:
star = self.get_star(
[3, 2], [self.config.BA_THREE_P, self.config.BA_G_TWO_P]
)
else:
star = self.get_star(
[3, 2, 1],
[self.config.BA_THREE_P, self.config.BA_TWO_P, self.config.BA_ONE_P],
)
chars = [x for x in self.ALL_CHAR if x.star == star and not x.limited]
return random.choice(chars)
def get_cards(self, count: int, **kwargs) -> List[Tuple[BaChar, int]]:
card_list = []
card_count = 0 # 保底计算
for i in range(count):
card_count += 1
# 十连保底
if card_count == 10:
card = self.get_card(2)
card_count = 0
else:
card = self.get_card(1)
if card.star > self.max_star - 2:
card_count = 0
card_list.append((card, i + 1))
return card_list
def generate_card_img(self, card: BaChar) -> BuildImage:
sep_w = 5
sep_h = 5
star_h = 15
img_w = 90
img_h = 100
font_h = 20
bar_h = 20
bar_w = 90
bg = BuildImage(img_w + sep_w * 2, img_h + font_h + sep_h * 2, color="#EFF2F5")
img_path = str(self.img_path / f"{cn2py(card.name)}.png")
img = BuildImage(img_w, img_h, background=img_path)
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):
star_path = str(self.img_path / "star-1.png")
star_w = 15
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)
text = card.name[:5] + "..." if len(card.name) > 6 else card.name
font = load_font(fontsize=14)
text_w, text_h = font.getsize(text)
draw = ImageDraw.Draw(bg.markImg)
draw.text(
(sep_w + (img_w - text_w) / 2, sep_h + img_h + (font_h - text_h) / 2),
text,
font=font,
fill="gray",
)
return bg
def _init_data(self):
self.ALL_CHAR = [
BaChar(
name=value["名称"],
star=int(value["星级"]),
limited=True if "(" in key else False,
)
for key, value in self.load_data().items()
]
def title2star(self, title: int):
if title == 'Star-3.png':
return 3
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)
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:
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]
except IndexError:
continue
member_dict = {
"头像": unquote(str(avatar)),
"名称": remove_prohibited_str(name),
"星级": self.title2star(star_pic),
}
info[member_dict["名称"]] = member_dict
self.dump_data(info)
logger.info(f"{self.game_name_cn} 更新成功")
# 下载头像
for value in info.values():
await self.download_img(value["头像"], value["名称"])
# 下载星星
await self.download_img(
"https://patchwiki.biligame.com/images/bluearchive/thumb/e/e0/82nj2x9sxko473g7782r14fztd4zyky.png/15px-Star-1.png",
"star-1",
)
await self.download_img(
"https://patchwiki.biligame.com/images/bluearchive/thumb/0/0b/msaff2g0zk6nlyl1rrn7n1ri4yobcqc.png/30px-Star-2.png",
"star-2",
)
await self.download_img(
"https://patchwiki.biligame.com/images/bluearchive/thumb/8/8a/577yv79x1rwxk8efdccpblo0lozl158.png/46px-Star-3.png",
"star-3"
)
+51 -29
View File
@@ -3,7 +3,6 @@ import random
import dateparser import dateparser
from lxml import etree from lxml import etree
from PIL import ImageDraw from PIL import ImageDraw
from bs4 import BeautifulSoup
from datetime import datetime from datetime import datetime
from urllib.parse import unquote from urllib.parse import unquote
from typing import List, Optional, Tuple from typing import List, Optional, Tuple
@@ -32,8 +31,9 @@ class Operator(BaseData):
class PrtsHandle(BaseHandle[Operator]): class PrtsHandle(BaseHandle[Operator]):
def __init__(self): def __init__(self):
super().__init__("prts", "明日方舟", "#eff2f5") super().__init__(game_name="prts", game_name_cn="明日方舟")
self.max_star = 6 self.max_star = 6
self.game_card_color = "#eff2f5"
self.config = draw_config.prts self.config = draw_config.prts
self.ALL_OPERATOR: List[Operator] = [] self.ALL_OPERATOR: List[Operator] = []
@@ -41,8 +41,8 @@ class PrtsHandle(BaseHandle[Operator]):
def get_card(self, add: float) -> Operator: def get_card(self, add: float) -> Operator:
star = self.get_star( star = self.get_star(
[6, 5, 4, 3], star_list=[6, 5, 4, 3],
[ probability_list=[
self.config.PRTS_SIX_P + add, self.config.PRTS_SIX_P + add,
self.config.PRTS_FIVE_P, self.config.PRTS_FIVE_P,
self.config.PRTS_FOUR_P, self.config.PRTS_FOUR_P,
@@ -53,7 +53,7 @@ class PrtsHandle(BaseHandle[Operator]):
all_operators = [ all_operators = [
x x
for x in self.ALL_OPERATOR for x in self.ALL_OPERATOR
if x.star == star and not any([x.limited, x.event_only, x.recruit_only]) if x.star == star and not any([x.limited, x.recruit_only, x.event_only])
] ]
acquire_operator = None acquire_operator = None
@@ -74,7 +74,7 @@ class PrtsHandle(BaseHandle[Operator]):
acquire_operator = random.choice(all_operators) acquire_operator = random.choice(all_operators)
return acquire_operator return acquire_operator
def get_cards(self, count: int) -> List[Tuple[Operator, int]]: def get_cards(self, count: int, **kwargs) -> List[Tuple[Operator, int]]:
card_list = [] # 获取所有角色 card_list = [] # 获取所有角色
add = 0.0 add = 0.0
count_idx = 0 count_idx = 0
@@ -109,7 +109,8 @@ class PrtsHandle(BaseHandle[Operator]):
def _draw(self, count: int, **kwargs) -> Message: def _draw(self, count: int, **kwargs) -> Message:
index2card = self.get_cards(count) index2card = self.get_cards(count)
cards = [card[0] for card in 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 [] 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) result = self.format_result(index2card, up_list=up_list)
pool_info = self.format_pool_info() pool_info = self.format_pool_info()
@@ -162,7 +163,11 @@ class PrtsHandle(BaseHandle[Operator]):
def load_up_char(self): def load_up_char(self):
try: try:
data = self.load_data(f"draw_card_up/{self.game_name}_up_char.json") data = self.load_data(f"draw_card_up/{self.game_name}_up_char.json")
self.UP_EVENT = UpEvent.parse_obj(data.get("char", {})) """这里的 waring 有点模糊,更新游戏信息时没有up池的情况下也会报错,所以细分了一下"""
if not data:
logger.warning(f"当前无UP池或 {self.game_name}_up_char.json 文件不存在")
else:
self.UP_EVENT = UpEvent.parse_obj(data.get("char", {}))
except ValidationError: except ValidationError:
logger.warning(f"{self.game_name}_up_char 解析出错") logger.warning(f"{self.game_name}_up_char 解析出错")
@@ -185,14 +190,15 @@ class PrtsHandle(BaseHandle[Operator]):
avatar = char.xpath("./td[1]/div/div/div/a/img/@srcset")[0] avatar = char.xpath("./td[1]/div/div/div/a/img/@srcset")[0]
name = char.xpath("./td[2]/a/text()")[0] name = char.xpath("./td[2]/a/text()")[0]
star = char.xpath("./td[5]/text()")[0] star = char.xpath("./td[5]/text()")[0]
sources = str(char.xpath("./td[8]/text()")[0]).split("\n") """这里sources修好了干员获取标签有问题的bug,如三星只能抽到卡缇就是这个原因"""
sources = [_.strip('\n') for _ in char.xpath("./td[8]/text()")]
except IndexError: except IndexError:
continue continue
member_dict = { member_dict = {
"头像": unquote(str(avatar).split(" ")[-2]), "头像": unquote(str(avatar).split(" ")[-2]),
"名称": remove_prohibited_str(str(name).strip()), "名称": remove_prohibited_str(str(name).strip()),
"星级": int(str(star).strip()), "星级": int(str(star).strip()),
"获取途径": [s for s in sources if s], "获取途径": sources,
} }
info[member_dict["名称"]] = member_dict info[member_dict["名称"]] = member_dict
self.dump_data(info) self.dump_data(info)
@@ -208,6 +214,7 @@ class PrtsHandle(BaseHandle[Operator]):
await self.update_up_char() await self.update_up_char()
async def update_up_char(self): async def update_up_char(self):
"""重载卡池"""
announcement_url = "https://ak.hypergryph.com/news.html" announcement_url = "https://ak.hypergryph.com/news.html"
result = await self.get_url(announcement_url) result = await self.get_url(announcement_url)
if not result: if not result:
@@ -221,41 +228,53 @@ class PrtsHandle(BaseHandle[Operator]):
end_time = None end_time = None
up_chars = [] up_chars = []
pool_img = "" pool_img = ""
title = "" for activity_url in activity_urls[:10]: # 减少响应时间, 10个就够了
for activity_url in activity_urls:
activity_url = f"https://ak.hypergryph.com{activity_url}" activity_url = f"https://ak.hypergryph.com{activity_url}"
result = await self.get_url(activity_url) result = await self.get_url(activity_url)
if not result: if not result:
logger.warning(f"{self.game_name_cn}获取公告 {activity_url} 出错") logger.warning(f"{self.game_name_cn}获取公告 {activity_url} 出错")
continue continue
soup = BeautifulSoup(result, "lxml")
contents = soup.find_all("p") """因为鹰角的前端太自由了,这里重写了匹配规则以尽可能避免因为前端乱七八糟而导致的重载失败"""
dom = etree.HTML(result, etree.HTMLParser())
contents = dom.xpath(
"//div[@class='article-content']/p/text() | //div[@class='article-content']/p/span/text() | //div[@class='article-content']/div[@class='media-wrap image-wrap']/img/@src"
)
title = ""
time = ""
chars: List[str] = []
for index, content in enumerate(contents): for index, content in enumerate(contents):
if re.search("(.*)(寻访|复刻).*?开启", content.text): if re.search("(.*)(寻访|复刻).*?开启", content):
title = content.text title = re.split(r"[【】]", content)
if "【" in title and "】" in title: title = "".join(title[1:-1]) if "-" in title else title[1]
title = re.split(r"[【】]", title)[1] lines = [contents[index-2+_] for _ in range(8)] # 从 -2 开始是因为xpath获取的时间有的会在寻访开启这一句之前
lines = [str(contents[index + i + 1].text) for i in range(5)] lines.append("") # 防止IndexError,加个空字符串
time = "" for idx, line in enumerate(lines):
chars: List[str] = []
for line in lines:
match = re.search( match = re.search(
r"(\d{1,2}月\d{1,2}日.*?-.*?\d{1,2}月\d{1,2}日.*?$)", line r"(\d{1,2}月\d{1,2}日.*?-.*?\d{1,2}月\d{1,2}日.*?$)", line
) )
if match: if match:
time = match.group(1) time = match.group(1)
if "★" in line: """因为 <p> 的诡异排版,所以有了下面的一段"""
chars.append(line) if ("★★" in line and "%" in line) or ("★★" in line and "%" in lines[idx + 1]):
chars.append(line) if ("★★" in line and "%" in line) else chars.append(line + lines[idx + 1])
if not time: if not time:
continue continue
start, end = time.replace("月", "/").replace("日", "").split("-")[:2] start, end = time.replace("月", "/").replace("日", " ").split("-")[:2] # 日替换为空格是因为有日后面不接空格的情况,导致 split 出问题
start_time = dateparser.parse(start) start_time = dateparser.parse(start)
end_time = dateparser.parse(end) end_time = dateparser.parse(end)
pool_img = content.find_previous("img")["src"] pool_img = contents[index-2]
r"""两类格式:用/分割,用\分割;★+(概率)+名字,★+名字+(概率)"""
for char in chars: for char in chars:
star = char.split("(")[0].count("★") star = char.split("(")[0].count("★")
name = re.split(r"[:(]", char)[1] name = re.split(r"[:(]", char)[1] if "★(" not in char else re.split("):", char)[1] # 有的括号在前面有的在后面
names = name.split("/") if "/" in name else [name] if "\\" in name:
names = name.split("\\")
elif "/" in name:
names = name.split("/")
else:
names = [name] # 既有用/分割的,又有用\分割的
names = [name.replace("[限定]", "").strip() for name in names] names = [name.replace("[限定]", "").strip() for name in names]
if "权值" in char: if "权值" in char:
match = re.search(r"(在.*?以.*?(\d+).*?倍权值.*?)", char) match = re.search(r"(在.*?以.*?(\d+).*?倍权值.*?)", char)
@@ -269,7 +288,10 @@ class PrtsHandle(BaseHandle[Operator]):
up_chars.append( up_chars.append(
UpChar(name=name, star=star, limited=False, zoom=zoom) UpChar(name=name, star=star, limited=False, zoom=zoom)
) )
break if start_time <= datetime.now() <= end_time: # 跳过过时的卡池
break # 这里break会导致个问题:如果一个公告里有两个池子,会漏掉下面的池子,比如 5.19 的定向寻访。但目前我也没啥好想法解决
chars: List[str] = [] # 查找下一个卡池之前清空 chars
up_chars = [] # 查找下一个卡池之前清空 up_chars
if title and start_time and end_time: if title and start_time and end_time:
if start_time <= datetime.now() <= end_time: if start_time <= datetime.now() <= end_time:
self.UP_EVENT = UpEvent( self.UP_EVENT = UpEvent(
+7 -6
View File
@@ -106,20 +106,21 @@ async def _(event: GroupMessageEvent):
"fudu", "FUDU_PROBABILITY" "fudu", "FUDU_PROBABILITY"
) and not _fudu_list.is_repeater(event.group_id): ) and not _fudu_list.is_repeater(event.group_id):
if random.random() < 0.2: if random.random() < 0.2:
await fudu.finish("[[_task|fudu]]打断施法!") if msg.endswith("打断施法!"):
await fudu.finish("[[_task|fudu]]打断" + msg)
else:
await fudu.finish("[[_task|fudu]]打断施法!")
_fudu_list.set_repeater(event.group_id) _fudu_list.set_repeater(event.group_id)
if img and msg: if img and msg:
rst = msg + image(f"compare_{event.group_id}_img.jpg", "temp") rst = msg + image(TEMP_PATH / f"compare_{event.group_id}_img.jpg")
elif img: elif img:
rst = image(f"compare_{event.group_id}_img.jpg", "temp") rst = image(TEMP_PATH / f"compare_{event.group_id}_img.jpg")
elif msg: elif msg:
rst = msg rst = msg
else: else:
rst = "" rst = ""
if rst: if rst:
if rst.endswith("打断施法!"): await fudu.finish("[[_task|fudu]]" + rst)
rst = "打断" + rst
await fudu.send("[[_task|fudu]]" + rst)
async def get_fudu_img_hash(url, group_id): async def get_fudu_img_hash(url, group_id):
@@ -182,7 +182,7 @@ def parsed_data(
role_data = { role_data = {
"active_day_number": data["stats"]["active_day_number"], # 活跃天数 "active_day_number": data["stats"]["active_day_number"], # 活跃天数
"achievement_number": data["stats"]["achievement_number"], # 达成成就数量 "achievement_number": data["stats"]["achievement_number"], # 达成成就数量
"win_rate": data["stats"]["win_rate"], # "win_rate": data["stats"]["win_rate"],
"anemoculus_number": data["stats"]["anemoculus_number"], # 风神瞳已收集 "anemoculus_number": data["stats"]["anemoculus_number"], # 风神瞳已收集
"geoculus_number": data["stats"]["geoculus_number"], # 岩神瞳已收集 "geoculus_number": data["stats"]["geoculus_number"], # 岩神瞳已收集
"avatar_number": data["stats"]["avatar_number"], # 获得角色数量 "avatar_number": data["stats"]["avatar_number"], # 获得角色数量
@@ -330,18 +330,19 @@ def get_country_data_image(world_data_dict: Dict) -> BuildImage:
f"{world_data_dict['层岩巨渊']['exploration_percentage'] / 10}%", f"{world_data_dict['层岩巨渊']['exploration_percentage'] / 10}%",
fill=(255, 255, 255), fill=(255, 255, 255),
) )
content_bk.text((300, 85), "地下矿区探索", fill=(239, 211, 114)) if world_data_dict.get('层岩巨渊·地下矿区'):
content_bk.text( content_bk.text((300, 85), "地下矿区探索", fill=(239, 211, 114))
(570, 85), content_bk.text(
f"{world_data_dict['层岩巨渊·地下矿区']['exploration_percentage'] / 10}%", (570, 85),
fill=(255, 255, 255), f"{world_data_dict['层岩巨渊·地下矿区']['exploration_percentage'] / 10}%",
) fill=(255, 255, 255),
content_bk.text((300, 150), "流明石触媒", fill=(239, 211, 114)) )
content_bk.text( content_bk.text((300, 150), "流明石触媒", fill=(239, 211, 114))
(570, 150), content_bk.text(
f"LV.{world_data_dict['层岩巨渊·地下矿区']['offerings'][0]['level']}", (570, 150),
fill=(255, 255, 255), f"LV.{world_data_dict['层岩巨渊·地下矿区']['offerings'][0]['level']}",
) fill=(255, 255, 255),
)
elif country in ["龙脊雪山"]: elif country in ["龙脊雪山"]:
content_bk.text((300, 40), "探索", fill=(239, 211, 114)) content_bk.text((300, 40), "探索", fill=(239, 211, 114))
content_bk.text( content_bk.text(
@@ -86,30 +86,28 @@ async def _():
if await Genshin.get_user_resin_recovery_time(u.uid) > datetime.now( if await Genshin.get_user_resin_recovery_time(u.uid) > datetime.now(
pytz.timezone("Asia/Shanghai") pytz.timezone("Asia/Shanghai")
): ):
date = await Genshin.get_user_resin_recovery_time(u.uid) # date = await Genshin.get_user_resin_recovery_time(u.uid) # 不能要,因为可能在这期间用户使用了树脂
scheduler.add_job( add_job(u.user_qq, u.uid)
_remind, # scheduler.add_job(
"date", # _remind,
run_date=date.replace(microsecond=0), # "date",
id=f"genshin_resin_remind_{u.uid}_{u.user_qq}", # run_date=date.replace(microsecond=0),
args=[u.user_qq, u.uid], # id=f"genshin_resin_remind_{u.uid}_{u.user_qq}",
) # args=[u.user_qq, u.uid],
# )
logger.info( logger.info(
f"genshin_resin_remind add_job:USER:{u.user_qq} UID:{u.uid} " f"genshin_resin_remind add_job:USER:{u.user_qq} UID:{u.uid}启动原神树脂提醒 "
f"{date} 原神树脂提醒"
) )
else: else:
await Genshin.clear_resin_remind_time(u.uid) await Genshin.clear_resin_remind_time(u.uid)
add_job(u.user_qq, u.uid) add_job(u.user_qq, u.uid)
logger.info( logger.info(
f"genshin_resin_remind add_job CHECK:USER:{u.user_qq} UID:{u.uid} " f"genshin_resin_remind add_job CHECK:USER:{u.user_qq} UID:{u.uid}启动原神树脂提醒 "
f"{date} 原神树脂提醒"
) )
else: else:
add_job(u.user_qq, u.uid) add_job(u.user_qq, u.uid)
logger.info( logger.info(
f"genshin_resin_remind add_job CHECK:USER:{u.user_qq} UID:{u.uid} " f"genshin_resin_remind add_job CHECK:USER:{u.user_qq} UID:{u.uid}启动原神树脂提醒 "
f"{date} 原神树脂提醒"
) )
@@ -144,17 +142,19 @@ async def _remind(user_id: int, uid: str):
now = datetime.now(pytz.timezone("Asia/Shanghai")) now = datetime.now(pytz.timezone("Asia/Shanghai"))
next_time = None next_time = None
if code == 200: if code == 200:
current_resin = data["current_resin"] # 当前树脂 current_resin = int(data["current_resin"]) # 当前树脂
max_resin = data["max_resin"] # 最大树脂 max_resin = int(data["max_resin"]) # 最大树脂
msg = f"你的已经存了 {current_resin} 个树脂了!不要忘记刷掉!" msg = f"你的已经存了 {current_resin} 个树脂了!不要忘记刷掉!"
# resin_recovery_time = data["resin_recovery_time"] # 树脂全部回复时间 # resin_recovery_time = data["resin_recovery_time"] # 树脂全部回复时间
if current_resin < max_resin: if current_resin < max_resin:
user_manager.remove(uid) user_manager.remove(uid)
user_manager.remove_overflow(uid) user_manager.remove_overflow(uid)
if max_resin - 40 < current_resin <= max_resin - 20: if current_resin < max_resin - 40:
next_time = now + timedelta(minutes=(max_resin - 20 - current_resin + 1) * 8, seconds=10) next_time = now + timedelta(minutes=(max_resin - 40 - current_resin) * 8)
elif current_resin < max_resin: elif max_resin - 40 <= current_resin < max_resin - 20:
next_time = now + timedelta(minutes=(max_resin - current_resin) * 8, seconds=10) next_time = now + timedelta(minutes=(max_resin - 20 - current_resin) * 8)
elif max_resin - 20 <= current_resin < max_resin:
next_time = now + timedelta(minutes=(max_resin - current_resin) * 8)
elif current_resin == max_resin: elif current_resin == max_resin:
custom_overflow_resin = Config.get_config("resin_remind", "CUSTOM_RESIN_OVERFLOW_REMIND") custom_overflow_resin = Config.get_config("resin_remind", "CUSTOM_RESIN_OVERFLOW_REMIND")
if user_manager.is_overflow(uid) and custom_overflow_resin: if user_manager.is_overflow(uid) and custom_overflow_resin:
@@ -164,6 +164,7 @@ async def _remind(user_id: int, uid: str):
msg = f"你的树脂都溢出 {custom_overflow_resin} 个了!浪费可耻!" msg = f"你的树脂都溢出 {custom_overflow_resin} 个了!浪费可耻!"
else: else:
next_time = now + timedelta(minutes=40 * 8 + random.randint(5, 50)) next_time = now + timedelta(minutes=40 * 8 + random.randint(5, 50))
if not user_manager.exists(uid) and current_resin >= max_resin - 40: if not user_manager.exists(uid) and current_resin >= max_resin - 40:
if current_resin == max_resin: if current_resin == max_resin:
user_manager.append(uid) user_manager.append(uid)
@@ -187,6 +188,7 @@ async def _remind(user_id: int, uid: str):
) )
except ActionFailed as e: except ActionFailed as e:
logger.error(f"树脂提醒推送发生错误 {type(e)}:{e}") logger.error(f"树脂提醒推送发生错误 {type(e)}:{e}")
if not next_time: if not next_time:
if user_manager.check(uid) and Config.get_config("resin_remind", "AUTO_CLOSE_QUERY_FAIL_RESIN_REMIND"): if user_manager.check(uid) and Config.get_config("resin_remind", "AUTO_CLOSE_QUERY_FAIL_RESIN_REMIND"):
await Genshin.set_resin_remind(int(uid), False) await Genshin.set_resin_remind(int(uid), False)
@@ -197,10 +199,13 @@ async def _remind(user_id: int, uid: str):
user_manager.remove_error_count(uid) user_manager.remove_error_count(uid)
await Genshin.set_user_resin_recovery_time(int(uid), next_time) await Genshin.set_user_resin_recovery_time(int(uid), next_time)
scheduler.add_job( scheduler.add_job(
_remind,
_remind, _remind,
"date", "date",
run_date=next_time, run_date=next_time,
id=f"genshin_resin_remind_{uid}_{user_id}", id=f"genshin_resin_remind_{uid}_{user_id}",
args=[user_id, uid], args=[user_id, uid],
) )
logger.info(
f"genshin_resin_remind add_job:USER:{user_id} UID:{uid} "
f"{next_time} 原神树脂提醒"
)
+2 -2
View File
@@ -1,6 +1,7 @@
from nonebot import on_command, on_notice from nonebot import on_command, on_notice
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
ActionFailed,
GroupMessageEvent, GroupMessageEvent,
PokeNotifyEvent, PokeNotifyEvent,
Message Message
@@ -24,7 +25,6 @@ from nonebot.rule import to_me
from datetime import datetime, timedelta from datetime import datetime, timedelta
from configs.config import NICKNAME from configs.config import NICKNAME
from apscheduler.jobstores.base import JobLookupError from apscheduler.jobstores.base import JobLookupError
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.params import CommandArg from nonebot.params import CommandArg
import random import random
import time import time
@@ -124,7 +124,7 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
redbag_data[event.group_id]["amount"] redbag_data[event.group_id]["amount"]
- redbag_data[event.group_id]["open_amount"] - redbag_data[event.group_id]["open_amount"]
) )
await return_gold(event.user_id, event.group_id, amount) await return_gold(redbag_data[event.group_id]["user_id"], event.group_id, amount)
await gold_redbag.send( await gold_redbag.send(
f'{redbag_data[event.group_id]["nickname"]}的红包过时未开完,退还{amount}金币...' f'{redbag_data[event.group_id]["nickname"]}的红包过时未开完,退还{amount}金币...'
) )
+7 -6
View File
@@ -61,22 +61,23 @@ async def generate_open_redbag_pic(user_id: int, send_user_nickname: str, amount
async def _generate_open_redbag_pic(user_id: int, send_user_nickname: str, amount: int, text: str): async def _generate_open_redbag_pic(user_id: int, send_user_nickname: str, amount: int, text: str):
send_user_nickname += '的红包' send_user_nickname += '的红包'
amount = str(amount) amount = str(amount)
head = BuildImage(1000, 980, font_size=30, background=f'{IMAGE_PATH}/prts/redbag_12.png') random_redbag = random.choice(os.listdir(f"{IMAGE_PATH}/prts/redbag_1"))
head = BuildImage(1000, 980, font_size=30, background=f'{IMAGE_PATH}/prts/redbag_1/{random_redbag}')
size = BuildImage(0, 0, font_size=50).getsize(send_user_nickname) size = BuildImage(0, 0, font_size=50).getsize(send_user_nickname)
# QQ头像 # QQ头像
ava_bk = BuildImage(100 + size[0], 66, color='white', font_size=50) ava_bk = BuildImage(100 + size[0], 66, is_alpha=True, font_size=50)
ava = BuildImage(66, 66, background=BytesIO(await get_user_avatar(user_id))) ava = BuildImage(66, 66, is_alpha=True, background=BytesIO(await get_user_avatar(user_id)))
ava_bk.paste(ava) ava_bk.paste(ava)
ava_bk.text((100, 7), send_user_nickname) ava_bk.text((100, 7), send_user_nickname)
# ava_bk.show() # ava_bk.show()
ava_bk_w, ava_bk_h = ava_bk.size ava_bk_w, ava_bk_h = ava_bk.size
head.paste(ava_bk, (int((1000 - ava_bk_w) / 2), 300)) head.paste(ava_bk, (int((1000 - ava_bk_w) / 2), 300), alpha=True)
# 金额 # 金额
size = BuildImage(0, 0, font_size=150).getsize(amount) size = BuildImage(0, 0, font_size=150).getsize(amount)
price = BuildImage(size[0], size[1], font_size=150) price = BuildImage(size[0], size[1], is_alpha=True, font_size=150)
price.text((0, 0), amount, fill=(209, 171, 108)) price.text((0, 0), amount, fill=(209, 171, 108))
# 金币中文 # 金币中文
head.paste(price, (int((1000 - size[0]) / 2) - 50, 460)) head.paste(price, (int((1000 - size[0]) / 2) - 50, 460), alpha=True)
head.text((int((1000 - size[0]) / 2 + size[0]) - 50, 500 + size[1] - 70), '金币', fill=(209, 171, 108)) head.text((int((1000 - size[0]) / 2 + size[0]) - 50, 500 + size[1] - 70), '金币', fill=(209, 171, 108))
# 剩余数量和金额 # 剩余数量和金额
head.text((350, 900), text, (198, 198, 198)) head.text((350, 900), text, (198, 198, 198))
@@ -36,7 +36,7 @@ __plugin_settings__ = {
"limit_superuser": False, "limit_superuser": False,
"cmd": ["发送图片"] + Config.get_config("image_management", "IMAGE_DIR_LIST"), "cmd": ["发送图片"] + Config.get_config("image_management", "IMAGE_DIR_LIST"),
} }
__plugin_resources__ = {"pa": IMAGE_PATH} __plugin_resources__ = {"pa": IMAGE_PATH / "pa"}
Config.add_plugin_config( Config.add_plugin_config(
"_task", "_task",
+14 -11
View File
@@ -1,8 +1,7 @@
from nonebot import on_message, on_command from nonebot import on_message, on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message, ActionFailed
from nonebot.adapters.onebot.v11.permission import GROUP from nonebot.adapters.onebot.v11.permission import GROUP
from utils.utils import is_number, get_message_img, get_message_text from utils.utils import is_number, get_message_img, get_message_text
from nonebot.adapters.onebot.v11.exception import ActionFailed
from configs.path_config import DATA_PATH, TEMP_PATH from configs.path_config import DATA_PATH, TEMP_PATH
from utils.image_utils import get_img_hash from utils.image_utils import get_img_hash
from services.log import logger from services.log import logger
@@ -72,9 +71,7 @@ def save_data():
async def download_img_and_hash(url, group_id) -> str: async def download_img_and_hash(url, group_id) -> str:
if await AsyncHttpx.download_file( if await AsyncHttpx.download_file(url, TEMP_PATH / f"mute_{group_id}_img.jpg"):
url, TEMP_PATH / f"mute_{group_id}_img.jpg"
):
return str(get_img_hash(TEMP_PATH / f"mute_{group_id}_img.jpg")) return str(get_img_hash(TEMP_PATH / f"mute_{group_id}_img.jpg"))
return "" return ""
@@ -133,11 +130,19 @@ async def _(bot: Bot, event: GroupMessageEvent):
@mute_setting.handle() @mute_setting.handle()
async def _(event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()): async def _(
event: GroupMessageEvent,
cmd: Tuple[str, ...] = Command(),
arg: Message = CommandArg(),
):
global mute_data global mute_data
group_id = str(event.group_id) group_id = str(event.group_id)
if not mute_data.get(group_id): if not mute_data.get(group_id):
mute_data[group_id] = {"count": Config.get_config("mute", "MUTE_DEFAULT_COUNT"), "time": Config.get_config("mute", "MUTE_DEFAULT_TIME"), "duration": Config.get_config("mute", "MUTE_DEFAULT_DURATION")} mute_data[group_id] = {
"count": Config.get_config("mute", "MUTE_DEFAULT_COUNT"),
"time": Config.get_config("mute", "MUTE_DEFAULT_TIME"),
"duration": Config.get_config("mute", "MUTE_DEFAULT_DURATION"),
}
msg = arg.extract_plain_text().strip() msg = arg.extract_plain_text().strip()
if cmd[0] == "刷屏检测设置": if cmd[0] == "刷屏检测设置":
await mute_setting.finish( await mute_setting.finish(
@@ -157,8 +162,6 @@ async def _(event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Mes
if cmd[0] == "设置刷屏禁言时长": if cmd[0] == "设置刷屏禁言时长":
mute_data[group_id]["duration"] = int(msg) mute_data[group_id]["duration"] = int(msg)
msg += " 分钟" msg += " 分钟"
await mute_setting.send(f'刷屏检测:{cmd[0]}为 {msg}') await mute_setting.send(f"刷屏检测:{cmd[0]}为 {msg}")
logger.info( logger.info(f"USER {event.user_id} GROUP {group_id} {cmd[0]}:{msg}")
f'USER {event.user_id} GROUP {group_id} {cmd[0]}:{msg}'
)
save_data() save_data()
+4 -4
View File
@@ -211,16 +211,16 @@ update_price = on_command("更新开箱价格", priority=1, permission=SUPERUSER
@update_price.handle() @update_price.handle()
async def _( event: MessageEvent): async def _(event: MessageEvent, arg: Message = CommandArg()):
await update_price.send(await util_get_buff_price(str(event.get_message()))) await update_price.send(await util_get_buff_price(arg.extract_plain_text().strip() or "狂牙大行动"))
update_img = on_command("更新开箱图片", priority=1, permission=SUPERUSER, block=True) update_img = on_command("更新开箱图片", priority=1, permission=SUPERUSER, block=True)
@update_img.handle() @update_img.handle()
async def _(event: MessageEvent): async def _(event: MessageEvent, arg: Message = CommandArg()):
await update_img.send(await util_get_buff_img(str(event.get_message()))) await update_img.send(await util_get_buff_img(arg.extract_plain_text().strip() or "狂牙大行动"))
# 重置开箱 # 重置开箱
+1 -1
View File
@@ -7,7 +7,7 @@ from .models.open_cases_user import OpenCasesUser
from services.log import logger from services.log import logger
from utils.utils import get_bot, cn2py from utils.utils import get_bot, cn2py
from asyncio.exceptions import TimeoutError from asyncio.exceptions import TimeoutError
from nonebot.adapters.onebot.v11.exception import ActionFailed from nonebot.adapters.onebot.v11 import ActionFailed
from configs.config import Config from configs.config import Config
from utils.manager import group_manager from utils.manager import group_manager
from .config import * from .config import *
+1 -2
View File
@@ -1,10 +1,9 @@
# from nonebot import on_message # from nonebot import on_message
# from services.log import logger # from services.log import logger
# from nonebot.adapters.onebot.v11 import GroupMessageEvent # from nonebot.adapters.onebot.v11 import GroupMessageEvent, ActionFailed
# from utils.utils import get_message_json, get_local_proxy, is_number, get_message_text # from utils.utils import get_message_json, get_local_proxy, is_number, get_message_text
# from nonebot.adapters.onebot.v11.permission import GROUP # from nonebot.adapters.onebot.v11.permission import GROUP
# from utils.message_builder import image # from utils.message_builder import image
# from nonebot.adapters.onebot.v11.exception import ActionFailed
# from utils.image_utils import BuildImage # from utils.image_utils import BuildImage
# from utils.browser import get_browser # from utils.browser import get_browser
# from configs.path_config import IMAGE_PATH # from configs.path_config import IMAGE_PATH
+2 -1
View File
@@ -4,7 +4,7 @@ from asyncio.locks import Semaphore
from asyncio.exceptions import TimeoutError from asyncio.exceptions import TimeoutError
from ._model.pixiv import Pixiv from ._model.pixiv import Pixiv
from typing import List, Optional from typing import List, Optional
from utils.utils import change_pixiv_image_links from utils.utils import change_pixiv_image_links, change_img_md5
from utils.image_utils import BuildImage from utils.image_utils import BuildImage
from utils.http_utils import AsyncHttpx from utils.http_utils import AsyncHttpx
from services.log import logger from services.log import logger
@@ -238,6 +238,7 @@ async def get_image(img_url: str, user_id: int) -> Optional[str]:
TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg", "wb" TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg", "wb"
) as f: ) as f:
await f.write(response.content) await f.write(response.content)
change_img_md5(TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg")
return TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg" return TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg"
except TimeoutError: except TimeoutError:
logger.warning(f"PIX:{img_url} 图片下载超时...") logger.warning(f"PIX:{img_url} 图片下载超时...")
@@ -139,15 +139,14 @@ class OmegaPixivIllusts(db.Model):
data = await cls.select('pid').gino.all() data = await cls.select('pid').gino.all()
return [x[0] for x in data] return [x[0] for x in data]
@classmethod # async def test(cls, nsfw_tag: int = 1):
async def test(cls, nsfw_tag: int = 1): # if nsfw_tag is not None:
if nsfw_tag is not None: # query = cls.query.where(cls.nsfw_tag == nsfw_tag)
query = cls.query.where(cls.nsfw_tag == nsfw_tag) # else:
else: # query = cls.query
query = cls.query # query = query.where((cls.width - cls.height) < 50)
query = query.where((cls.width - cls.height) < 50) # for x in await query.gino.all():
for x in await query.gino.all(): # print(x.pid)
print(x.pid)
+20 -6
View File
@@ -18,7 +18,13 @@ usage:
查看 pix 好康图库 查看 pix 好康图库
指令: 指令:
pix ?*[tags]: 通过 tag 获取相似图片,不含tag时随机抽取 pix ?*[tags]: 通过 tag 获取相似图片,不含tag时随机抽取
pid [uid]: 通过uid获取图片
pix pid[pid]: 查看图库中指定pid图片 pix pid[pid]: 查看图库中指定pid图片
示例:pix 萝莉 白丝
示例:pix 萝莉 白丝 10 (10为数量)
示例:pix #02 (当tag只有1个tag且为数字时,使用#标记,否则将被判定为数量)
示例:pix 34582394 (查询指定uid图片)
示例:pix pid:12323423 (查询指定pid图片)
""".strip() """.strip()
__plugin_superuser_usage__ = """ __plugin_superuser_usage__ = """
usage: usage:
@@ -49,7 +55,9 @@ __plugin_configs__ = {
"value": None, "value": None,
"help": "单次发送的图片数量达到指定值时转发为合并消息", "help": "单次发送的图片数量达到指定值时转发为合并消息",
"default_value": None, "default_value": None,
} },
"ALLOW_GROUP_SETU": {"value": False, "help": "允许非超级用户使用-s参数", "default_value": False},
"ALLOW_GROUP_R18": {"value": False, "help": "允许非超级用户使用-r参数", "default_value": False},
} }
@@ -80,11 +88,17 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
nsfw_tag = 2 nsfw_tag = 2
else: else:
nsfw_tag = 0 nsfw_tag = 0
if nsfw_tag != 0 and str(event.user_id) not in bot.config.superusers: if str(event.user_id) not in bot.config.superusers:
await pix.finish("你不能看这些噢,这些都是是留给管理员看的...") if (nsfw_tag == 1 and not Config.get_config("pix", "ALLOW_GROUP_SETU")) or (
if n := len(x) == 1 and is_number(x[0]): nsfw_tag == 2 and not Config.get_config("pix", "ALLOW_GROUP_R18")
num = int(x[-1]) ):
keyword = "" await pix.finish("你不能看这些噢,这些都是是留给管理员看的...")
if (n := len(x)) == 1:
if is_number(x[0]) and int(x[0]) < 100:
num = int(x[0])
keyword = ""
elif x[0].startswith("#"):
keyword = x[0][1:]
elif n > 1: elif n > 1:
if is_number(x[-1]): if is_number(x[-1]):
num = int(x[-1]) num = int(x[-1])
+11 -5
View File
@@ -1,11 +1,10 @@
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message, NetworkError
from nonebot.matcher import Matcher from nonebot.matcher import Matcher
from nonebot.params import CommandArg from nonebot.params import CommandArg
from nonebot import on_command from nonebot import on_command
from utils.utils import is_number from utils.utils import is_number
from .data_source import get_pixiv_urls, download_pixiv_imgs, search_pixiv_urls from .data_source import get_pixiv_urls, download_pixiv_imgs, search_pixiv_urls
from services.log import logger from services.log import logger
from nonebot.adapters.onebot.v11.exception import NetworkError
from asyncio.exceptions import TimeoutError from asyncio.exceptions import TimeoutError
from utils.message_builder import custom_forward_msg from utils.message_builder import custom_forward_msg
from configs.config import Config from configs.config import Config
@@ -44,6 +43,8 @@ usage:
搜图 樱岛麻衣 搜图 樱岛麻衣
搜图 樱岛麻衣 5 搜图 樱岛麻衣 5
搜图 樱岛麻衣 5 r18 搜图 樱岛麻衣 5 r18
搜图 樱岛麻衣#1000users 5
【多个关键词用#分割】
【默认为 热度排序】 【默认为 热度排序】
【注意空格!!】【在线搜索会较慢】【数量可能不符?可能该页数量不够,也可能被R-18屏蔽】 【注意空格!!】【在线搜索会较慢】【数量可能不符?可能该页数量不够,也可能被R-18屏蔽】
""".strip() """.strip()
@@ -69,6 +70,11 @@ __plugin_configs__ = {
"value": 20, "value": 20,
"help": "作品最大页数限制,超过的作品会被略过", "help": "作品最大页数限制,超过的作品会被略过",
"default_value": 20 "default_value": 20
},
"ALLOW_GROUP_R18": {
"value": False,
"help": "允许群聊中使用 r18 参数",
"default_value": False
} }
} }
Config.add_plugin_config( Config.add_plugin_config(
@@ -152,7 +158,7 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()): async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip() msg = arg.extract_plain_text().strip()
if isinstance(event, GroupMessageEvent): if isinstance(event, GroupMessageEvent):
if "r18" in msg.lower(): if "r18" in msg.lower() and not Config.get_config("pixiv_rank_search", "ALLOW_GROUP_R18"):
await pixiv_keyword.finish("(脸红#) 你不会害羞的 八嘎!", at_sender=True) await pixiv_keyword.finish("(脸红#) 你不会害羞的 八嘎!", at_sender=True)
r18 = 0 if "r18" in msg else 1 r18 = 0 if "r18" in msg else 1
msg = msg.replace("r18", "").strip().split() msg = msg.replace("r18", "").strip().split()
@@ -161,8 +167,8 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
info_list = None info_list = None
num = 10 num = 10
page = 1 page = 1
if (n := len(msg)) == 1: if (n := len(msg)) > 0:
keyword = msg[0] keyword = msg[0].replace("#"," ")
if n > 1: if n > 1:
if not is_number(msg[1]): if not is_number(msg[1]):
await pixiv_keyword.finish("图片数量必须是数字!", at_sender=True) await pixiv_keyword.finish("图片数量必须是数字!", at_sender=True)
+2
View File
@@ -1,5 +1,6 @@
from configs.path_config import IMAGE_PATH from configs.path_config import IMAGE_PATH
from utils.message_builder import image from utils.message_builder import image
from utils.utils import change_img_md5
from asyncio.exceptions import TimeoutError from asyncio.exceptions import TimeoutError
from configs.config import Config from configs.config import Config
from utils.http_utils import AsyncHttpx from utils.http_utils import AsyncHttpx
@@ -143,6 +144,7 @@ async def download_pixiv_imgs(
file, file,
timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"), timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"),
): ):
change_img_md5(file)
if forward_msg_index is not None: if forward_msg_index is not None:
result += image( result += image(
f"{user_id}_{forward_msg_index}_{index}_pixiv.jpg", f"{user_id}_{forward_msg_index}_{index}_pixiv.jpg",
+4 -4
View File
@@ -62,12 +62,12 @@ async def _poke_event(event: PokeNotifyEvent):
rst = "气死我了!" rst = "气死我了!"
await poke_.finish(rst + random.choice(poke__reply), at_sender=True) await poke_.finish(rst + random.choice(poke__reply), at_sender=True)
rand = random.random() rand = random.random()
if rand <= 0.3: path = random.choice(["luoli", "meitu"])
path = random.choice(["luoli", "meitu"]) if rand <= 0.3 and len(os.listdir(IMAGE_PATH / "image_management" / path)) > 0:
index = random.randint(0, len(os.listdir(IMAGE_PATH / "image_management" / path))) index = random.randint(0, len(os.listdir(IMAGE_PATH / "image_management" / path)) - 1)
result = f"id:{index}" + image(f"{index}.jpg", "image_management/" + path) result = f"id:{index}" + image(f"{index}.jpg", "image_management/" + path)
await poke_.send(result) await poke_.send(result)
logger.info(f"USER {event.user_id} 戳了戳我 回复: {result} \n {result}") logger.info(f"USER {event.user_id} 戳了戳我 回复: {result} {result}")
elif 0.3 < rand < 0.6: elif 0.3 < rand < 0.6:
voice = random.choice(os.listdir(RECORD_PATH / "dinggong")) voice = random.choice(os.listdir(RECORD_PATH / "dinggong"))
result = record(voice, "dinggong") result = record(voice, "dinggong")
+15 -8
View File
@@ -1,3 +1,4 @@
from services import logger
from utils.http_utils import AsyncHttpx from utils.http_utils import AsyncHttpx
from configs.config import Config from configs.config import Config
from configs.path_config import TEMP_PATH from configs.path_config import TEMP_PATH
@@ -39,12 +40,18 @@ async def get_saucenao_image(url: str) -> Union[str, List[str]]:
): ):
msg_list.append(image(TEMP_PATH / f"saucenao_search_{index}.jpg")) msg_list.append(image(TEMP_PATH / f"saucenao_search_{index}.jpg"))
for info in data: for info in data:
similarity = info["header"]["similarity"] try:
tmp = f"相似度:{similarity}%\n" similarity = info["header"]["similarity"]
for x in info["data"].keys(): tmp = f"相似度:{similarity}%\n"
if x != "ext_urls": for x in info["data"].keys():
tmp += f"{x}:{info['data'][x]}\n" if x != "ext_urls":
if "source" not in info["data"].keys(): tmp += f"{x}:{info['data'][x]}\n"
tmp += f'source:{info["data"]["ext_urls"][0]}\n' try:
msg_list.append(tmp[:-1]) if "source" not in info["data"].keys():
tmp += f'source:{info["data"]["ext_urls"][0]}\n'
except KeyError:
tmp += f'source:{info["header"]["thumbnail"]}\n'
msg_list.append(tmp[:-1])
except Exception as e:
logger.warning(f"识图获取图片信息发生错误 {type(e)}:{e}")
return msg_list return msg_list
+12 -5
View File
@@ -13,6 +13,7 @@ from utils.utils import (
from nonebot.typing import T_State from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
ActionFailed,
MessageEvent, MessageEvent,
GroupMessageEvent, GroupMessageEvent,
PrivateMessageEvent, PrivateMessageEvent,
@@ -30,7 +31,6 @@ from .data_source import (
add_data_to_database, add_data_to_database,
get_setu_count, get_setu_count,
) )
from nonebot.adapters.onebot.v11.exception import ActionFailed
from configs.config import Config, NICKNAME from configs.config import Config, NICKNAME
from utils.manager import withdraw_message_manager from utils.manager import withdraw_message_manager
from nonebot.params import CommandArg, Command, RegexGroup from nonebot.params import CommandArg, Command, RegexGroup
@@ -97,6 +97,7 @@ __plugin_configs__ = {
}, },
"TIMEOUT": {"value": 10, "help": "色图下载超时限制(秒)", "default_value": 10}, "TIMEOUT": {"value": 10, "help": "色图下载超时限制(秒)", "default_value": 10},
"SHOW_INFO": {"value": True, "help": "是否显示色图的基本信息,如PID等", "default_value": True}, "SHOW_INFO": {"value": True, "help": "是否显示色图的基本信息,如PID等", "default_value": True},
"ALLOW_GROUP_R18": {"value": False, "help": "在群聊中启用R18权限", "default_value": False},
} }
Config.add_plugin_config("pixiv", "PIXIV_NGINX_URL", "i.pixiv.re", help_="Pixiv反向代理") Config.add_plugin_config("pixiv", "PIXIV_NGINX_URL", "i.pixiv.re", help_="Pixiv反向代理")
@@ -148,10 +149,16 @@ async def _(
if cmd[0] == "色图r" and isinstance(event, PrivateMessageEvent): if cmd[0] == "色图r" and isinstance(event, PrivateMessageEvent):
r18 = 1 r18 = 1
num = 10 num = 10
elif cmd[0] == "色图r" and isinstance(event, GroupMessageEvent): elif (
await setu.finish( cmd[0] == "色图r"
random.choice(["这种不好意思的东西怎么可能给这么多人看啦", "羞羞脸!给我滚出克私聊!", "变态变态变态变态大变态!"]) and isinstance(event, GroupMessageEvent)
) ):
if not Config.get_config("send_setu", "ALLOW_GROUP_R18"):
await setu.finish(
random.choice(["这种不好意思的东西怎么可能给这么多人看啦", "羞羞脸!给我滚出克私聊!", "变态变态变态变态大变态!"])
)
else:
r18 = 1
# 有 数字 的话先尝试本地色图id # 有 数字 的话先尝试本地色图id
if msg and is_number(msg): if msg and is_number(msg):
setu_list, code = await get_setu_list(int(msg), r18=r18) setu_list, code = await get_setu_list(int(msg), r18=r18)
@@ -2,6 +2,7 @@ from configs.path_config import IMAGE_PATH, TEMP_PATH
from utils.message_builder import image from utils.message_builder import image
from services.log import logger from services.log import logger
from utils.image_utils import get_img_hash, compressed_image from utils.image_utils import get_img_hash, compressed_image
from utils.utils import change_img_md5
from asyncpg.exceptions import UniqueViolationError from asyncpg.exceptions import UniqueViolationError
from asyncio.exceptions import TimeoutError from asyncio.exceptions import TimeoutError
from typing import List, Optional from typing import List, Optional
@@ -111,6 +112,7 @@ async def search_online_setu(
path_ / f"{index}.jpg", path_ / f"{index}.jpg",
) )
logger.info(f"下载 lolicon 图片 {url_} 成功, id:{index}") logger.info(f"下载 lolicon 图片 {url_} 成功, id:{index}")
change_img_md5(path_ / file_name)
return image(path_ / file_name), index return image(path_ / file_name), index
except TimeoutError: except TimeoutError:
pass pass
@@ -128,6 +130,7 @@ async def check_local_exists_or_download(setu_image: Setu) -> "MessageSegment, i
path_ = r18_path if setu_image.is_r18 else path path_ = r18_path if setu_image.is_r18 else path
file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg" file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg"
if file.exists(): if file.exists():
change_img_md5(file)
return image(f"{setu_image.local_id}.jpg", path_), 200 return image(f"{setu_image.local_id}.jpg", path_), 200
return await search_online_setu(setu_image.img_url, id_, path_) return await search_online_setu(setu_image.img_url, id_, path_)
+4 -5
View File
@@ -24,6 +24,8 @@ from io import BytesIO
import asyncio import asyncio
import random import random
import nonebot import nonebot
import time
import locale
import os import os
@@ -260,15 +262,12 @@ def _generate_card(
today_data.text((0, 25), f"金币 + {gold}") today_data.text((0, 25), f"金币 + {gold}")
_type = "sign" _type = "sign"
current_date = datetime.now() current_date = datetime.now()
week = current_date.isoweekday() current_datetime_str = current_date.strftime("%Y-%m-%d %a %H:%M:%S")
data = current_date.date() data = current_date.date()
hour = current_date.hour
minute = current_date.minute
second = current_date.second
data_img = BuildImage( data_img = BuildImage(
0, 0,
0, 0,
plain_text=f"时间:{data} {weekdays[week]} {hour}:{minute}:{second}", plain_text=f"时间:{current_datetime_str}",
color=(255, 255, 255, 0), color=(255, 255, 255, 0),
font_size=20, font_size=20,
) )
+1 -1
View File
@@ -16,7 +16,7 @@ async def translate_msg(language_type, msg):
} }
data = (await AsyncHttpx.post(url, data=data)).json() data = (await AsyncHttpx.post(url, data=data)).json()
if data["errorCode"] == 0: if data["errorCode"] == 0:
return f'原文:{msg}\n翻译{data["translateResult"][0][0]["tgt"]}' return f'原文:{msg}\n翻译:{data["translateResult"][0][0]["tgt"]}'
return "翻译惜败.." return "翻译惜败.."
+1 -1
View File
@@ -232,7 +232,7 @@ async def _(
result += image(b64=pic2b64(img)) result += image(b64=pic2b64(img))
if method in ["模糊效果", "6"]: if method in ["模糊效果", "6"]:
for i in range(index): for i in range(index):
img = Image.open(TEMP_PATH / f"temp/{event.user_id}_{i}_update.png").filter( img = Image.open(TEMP_PATH / f"{event.user_id}_{i}_update.png").filter(
ImageFilter.BLUR ImageFilter.BLUR
) )
result += image(b64=pic2b64(img)) result += image(b64=pic2b64(img))
+78 -70
View File
@@ -1,70 +1,78 @@
from nonebot import on_command from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg from nonebot.params import CommandArg
from services.log import logger from services.log import logger
from ._data_source import get_data, gen_wbtop_pic from .data_source import gen_wbtop_pic,get_wbtop
from utils.utils import is_number from utils.utils import is_number
from configs.path_config import IMAGE_PATH from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncPlaywright from utils.http_utils import AsyncPlaywright
import asyncio import asyncio
import datetime
__zx_plugin_name__ = "微博热搜" __zx_plugin_name__ = "微博热搜"
__plugin_usage__ = """ __plugin_usage__ = """
usage: usage:
在QQ上吃个瓜 在QQ上吃个瓜
指令: 指令:
微博热搜:发送实时热搜 微博热搜:发送实时热搜
微博热搜 [id]:截图该热搜页面 微博热搜 [id]:截图该热搜页面
示例:微博热搜 5 示例:微博热搜 5
""".strip() """.strip()
__plugin_des__ = "刚买完瓜,在吃瓜现场" __plugin_des__ = "刚买完瓜,在吃瓜现场"
__plugin_cmd__ = ["微博热搜", "微博热搜 [id]"] __plugin_cmd__ = ["微博热搜", "微博热搜 [id]"]
__plugin_version__ = 0.1 __plugin_version__ = 0.2
__plugin_author__ = "HibiKier" __plugin_author__ = "HibiKier & yajiwa"
__plugin_settings__ = { __plugin_settings__ = {
"level": 5, "level": 5,
"default_status": True, "default_status": True,
"limit_superuser": False, "limit_superuser": False,
"cmd": ["微博热搜"], "cmd": ["微博热搜"],
} }
wbtop = on_command("wbtop", aliases={"微博热搜"}, priority=5, block=True) wbtop = on_command("wbtop", aliases={"微博热搜"}, priority=5, block=True)
wbtop_url = "https://v2.alapi.cn/api/new/wbtop" wbtop_url = "https://weibo.com/ajax/side/hotSearch"
wbtop_data = [] wbtop_data = []
@wbtop.handle() @wbtop.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()): async def _(event: MessageEvent, arg: Message = CommandArg()):
global wbtop_data global wbtop_data
msg = arg.extract_plain_text().strip() msg = arg.extract_plain_text().strip()
if not wbtop_data or not msg: if not wbtop_data or not msg:
data, code = await get_data(wbtop_url) if wbtop_data:
if code != 200: now_time = datetime.datetime.now()
await wbtop.finish(data, at_sender=True) if now_time > wbtop_data["time"] + datetime.timedelta(minutes=5):
wbtop_data = data["data"] data, code = await get_wbtop(wbtop_url)
if not msg: if code != 200:
img = await asyncio.get_event_loop().run_in_executor( await wbtop.finish(data, at_sender=True)
None, gen_wbtop_pic, wbtop_data wbtop_data = data
) else:
await wbtop.send(img) data, code = await get_wbtop(wbtop_url)
logger.info( if code != 200:
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" await wbtop.finish(data, at_sender=True)
f" 查询微博热搜" wbtop_data = data
) if not msg:
if is_number(msg) and 0 < int(msg) <= 50: img = await asyncio.get_event_loop().run_in_executor(
url = wbtop_data[int(msg) - 1]["url"] None, gen_wbtop_pic, wbtop_data["data"]
await wbtop.send("开始截取数据...") )
img = await AsyncPlaywright.screenshot( await wbtop.send(img)
url, logger.info(
f"{IMAGE_PATH}/temp/wbtop_{event.user_id}.png", f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
"#pl_feed_main", f" 查询微博热搜"
wait_time=12 )
) if is_number(msg) and 0 < int(msg) <= 50:
if img: url = wbtop_data["data"][int(msg) - 1]["url"]
await wbtop.send(img) await wbtop.send("开始截取数据...")
else: img = await AsyncPlaywright.screenshot(
await wbtop.send("发生了一些错误.....") url,
f"{IMAGE_PATH}/temp/wbtop_{event.user_id}.png",
"#pl_feed_main",
wait_time=12
)
if img:
await wbtop.send(img)
else:
await wbtop.send("发生了一些错误.....")
+62
View File
@@ -0,0 +1,62 @@
from nonebot.adapters.onebot.v11 import MessageSegment
from utils.image_utils import BuildImage
from utils.message_builder import image
from configs.path_config import IMAGE_PATH
from typing import Tuple, Union
from utils.http_utils import AsyncHttpx
import datetime
async def get_wbtop(url: str) -> Tuple[Union[dict, str], int]:
"""
:param url: 请求链接
"""
n = 0
while True:
try:
data = []
get_response = (await AsyncHttpx.get(url, timeout=20))
if get_response.status_code == 200:
data_json = get_response.json()['data']['realtime']
for data_item in data_json:
# 如果是广告,则不添加
if 'is_ad' in data_item:
continue
dic = {
'hot_word': data_item['note'],
'hot_word_num': str(data_item['num']),
'url': 'https://s.weibo.com/weibo?q=%23' + data_item['word'] + '%23',
}
data.append(dic)
if not data:
return "没有搜索到...", 997
return {'data': data, 'time': datetime.datetime.now()}, 200
else:
if n > 2:
return f'获取失败,请十分钟后再试', 999
else:
n += 1
continue
except TimeoutError:
return "超时了....", 998
def gen_wbtop_pic(data: dict) -> MessageSegment:
"""
生成微博热搜图片
:param data: 微博热搜数据
"""
bk = BuildImage(700, 32 * 50 + 280, 700, 32, color="#797979")
wbtop_bk = BuildImage(700, 280, background=f"{IMAGE_PATH}/other/webtop.png")
bk.paste(wbtop_bk)
text_bk = BuildImage(700, 32 * 50, 700, 32, color="#797979")
for i, data in enumerate(data):
title = f"{i + 1}. {data['hot_word']}"
hot = str(data["hot_word_num"])
img = BuildImage(700, 30, font_size=20)
w, h = img.getsize(title)
img.text((10, int((30 - h) / 2)), title)
img.text((580, int((30 - h) / 2)), hot)
text_bk.paste(img)
bk.paste(text_bk, (0, 280))
return image(b64=bk.pic2bs4())
+25 -15
View File
@@ -1,20 +1,30 @@
from configs.config import Config as gConfig from configs.config import Config as gConfig
from .api import * from .api import *
from .auth import * from .auth import *
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, IgnoredException
gConfig.add_plugin_config( from utils.manager import plugins2settings_manager
"web-ui", from nonebot.typing import T_State
"username", from nonebot.adapters.onebot.v11 import (
"admin", Bot,
name="web-ui", MessageEvent
help_="前端管理用户名"
) )
gConfig.add_plugin_config(
"web-ui", gConfig.add_plugin_config("web-ui", "username", "admin", name="web-ui", help_="前端管理用户名")
"password",
None, gConfig.add_plugin_config("web-ui", "password", None, name="web-ui", help_="前端管理密码")
name="web-ui",
help_="前端管理密码"
) # 使用webui访问api后plugins2settings中的cmd字段将从list变为str
# 暂时找不到原因
# 先使用hook修复
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
for module in plugins2settings_manager.keys():
if isinstance(plugins2settings_manager.get_plugin_data(module).get("cmd"), str):
plugins2settings_manager.set_module_data(
module,
"cmd",
plugins2settings_manager.get_plugin_data(module).get("cmd").split(","),
)
+1 -1
View File
@@ -58,4 +58,4 @@ async def _(group: GroupResult, user: User = Depends(token_to_user)) -> Result:
group_manager.turn_on_group_bot_status(group_id) group_manager.turn_on_group_bot_status(group_id)
else: else:
group_manager.shutdown_group_bot_status(group_id) group_manager.shutdown_group_bot_status(group_id)
return Result(code=200) return Result(code=200, data="修改成功!")
+20 -2
View File
@@ -1,3 +1,5 @@
from pydantic import ValidationError
from configs.config import Config from configs.config import Config
from services.log import logger from services.log import logger
from utils.manager import (plugins2block_manager, plugins2cd_manager, from utils.manager import (plugins2block_manager, plugins2cd_manager,
@@ -85,6 +87,10 @@ def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
id_ += 1 id_ += 1
data["plugin_config"] = tmp data["plugin_config"] = tmp
plugin_list.append(Plugin(**data)) plugin_list.append(Plugin(**data))
except (AttributeError, ValidationError) as e:
logger.error(
f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}"
)
except Exception as e: except Exception as e:
logger.error( logger.error(
f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}" f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}"
@@ -108,7 +114,7 @@ def _(plugin: Plugin, user: User = Depends(token_to_user)) -> Result:
if str(c.value).lower() in ["true", "false"] and ( if str(c.value).lower() in ["true", "false"] and (
c.default_value is None or isinstance(c.default_value, bool) c.default_value is None or isinstance(c.default_value, bool)
): ):
c.value = True if str(c.value).lower() == "true" else False c.value = str(c.value).lower() == "true"
elif isinstance( elif isinstance(
Config.get_config(plugin.model, c.key, c.value), int Config.get_config(plugin.model, c.key, c.value), int
) or isinstance(c.default_value, int): ) or isinstance(c.default_value, int):
@@ -121,12 +127,24 @@ def _(plugin: Plugin, user: User = Depends(token_to_user)) -> Result:
isinstance(Config.get_config(plugin.model, c.key, c.value), list) isinstance(Config.get_config(plugin.model, c.key, c.value), list)
or isinstance(c.default_value, list) or isinstance(c.default_value, list)
): ):
default_value = Config.get_config(plugin.model, c.key, c.value)
c.value = c.value.split(",") c.value = c.value.split(",")
if default_value and isinstance(default_value[0], int):
c.value = [int(x) for x in c.value]
elif default_value and isinstance(default_value[0], float):
c.value = [float(x) for x in c.value]
elif default_value and isinstance(default_value[0], bool):
temp = []
for x in c.value:
temp.append(x.lower() == "true")
c.value = temp
Config.set_config(plugin.model, c.key, c.value) Config.set_config(plugin.model, c.key, c.value)
Config.save(None, True) Config.save(None, True)
else: else:
if plugin.plugin_settings: if plugin.plugin_settings:
for key, value in plugin.plugin_settings: for key, value in plugin.plugin_settings:
if key == "cmd":
value = value.split(",")
plugins2settings_manager.set_module_data(plugin.model, key, value) plugins2settings_manager.set_module_data(plugin.model, key, value)
if plugin.plugin_manager: if plugin.plugin_manager:
for key, value in plugin.plugin_manager: for key, value in plugin.plugin_manager:
@@ -139,4 +157,4 @@ def _(plugin: Plugin, user: User = Depends(token_to_user)) -> Result:
code=500, code=500,
data=f"WEB_UI POST /webui/plugins model:{plugin.model} 发生错误 {type(e)}:{e}", data=f"WEB_UI POST /webui/plugins model:{plugin.model} 发生错误 {type(e)}:{e}",
) )
return Result(code=200) return Result(code=200, data="修改成功!")
+1 -1
View File
@@ -34,7 +34,7 @@ async def _(parma: RequestParma, user: User = Depends(token_to_user)) -> Result:
操作请求 操作请求
:param parma: 参数 :param parma: 参数
""" """
result = "ok" result = "操作成功!"
flag = 3 flag = 3
if bot := get_bot(): if bot := get_bot():
if parma.handle == "approve": if parma.handle == "approve":
+5 -5
View File
@@ -29,7 +29,7 @@ disk_data = {"data": []}
@app.get("/webui/system") @app.get("/webui/system")
async def _(user: User = Depends(token_to_user)) -> Result: async def _() -> Result:
return await get_system_data() return await get_system_data()
@@ -74,7 +74,7 @@ async def _(user: User = Depends(token_to_user)) -> Result:
) )
async def get_system_data(): async def get_system_data(user: User = Depends(token_to_user)):
""" """
说明: 说明:
获取系统信息,资源文件大小,网络状态等 获取系统信息,资源文件大小,网络状态等
@@ -92,7 +92,7 @@ async def get_system_data():
logger.warning(f"访问Google失败... {type(e)}: {e}") logger.warning(f"访问Google失败... {type(e)}: {e}")
google = 404 google = 404
network = SystemNetwork(baidu=baidu, google=google) network = SystemNetwork(baidu=baidu, google=google)
disk = await asyncio.get_event_loop().run_in_executor(None, _get_system_disk) disk = await asyncio.get_event_loop().run_in_executor(None, _get_system_disk, None)
status = await asyncio.get_event_loop().run_in_executor(None, _get_system_status) status = await asyncio.get_event_loop().run_in_executor(None, _get_system_status)
return Result( return Result(
code=200, code=200,
@@ -105,7 +105,7 @@ async def get_system_data():
) )
def _get_system_status() -> SystemStatus: def _get_system_status(user: User = Depends(token_to_user)) -> SystemStatus:
""" """
说明: 说明:
获取系统信息等 获取系统信息等
@@ -123,7 +123,7 @@ def _get_system_status() -> SystemStatus:
def _get_system_disk( def _get_system_disk(
type_: Optional[str], type_: Optional[str], user: User = Depends(token_to_user)
) -> Union[SystemFolderSize, Dict[str, Union[float, datetime]]]: ) -> Union[SystemFolderSize, Dict[str, Union[float, datetime]]]:
""" """
说明: 说明:
+27 -9
View File
@@ -1,4 +1,6 @@
import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from configs.path_config import DATA_PATH
from typing import Optional from typing import Optional
from starlette import status from starlette import status
from fastapi import Depends, HTTPException from fastapi import Depends, HTTPException
@@ -8,6 +10,8 @@ from configs.config import Config
from jose import JWTError, jwt from jose import JWTError, jwt
import nonebot import nonebot
from ..config import Result
app = nonebot.get_app() app = nonebot.get_app()
@@ -18,6 +22,13 @@ ACCESS_TOKEN_EXPIRE_MINUTES = 30
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="webui/login") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="webui/login")
token_file = DATA_PATH / "web_ui" / "token.json"
token_file.parent.mkdir(parents=True, exist_ok=True)
token_data = {"token": []}
if token_file.exists():
token_data = json.load(open(token_file, 'r', encoding='utf8'))
class User(BaseModel): class User(BaseModel):
username: str username: str
password: str password: str
@@ -62,6 +73,11 @@ async def login_get_token(form_data: OAuth2PasswordRequestForm = Depends()):
if not user or user.password != form_data.password: if not user or user.password != form_data.password:
raise form_exception raise form_exception
access_token = create_token(user=user, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)) access_token = create_token(user=user, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
token_data["token"].append(access_token)
if len(token_data["token"]) > 3:
token_data["token"] = token_data["token"][1:]
with open(token_file, 'w', encoding="utf8") as f:
json.dump(token_data, f, ensure_ascii=False, indent=4)
return {"access_token": access_token, "token_type": "bearer"} return {"access_token": access_token, "token_type": "bearer"}
@@ -72,16 +88,18 @@ credentials_exception = HTTPException(
) )
@app.post("/webui/auth")
def token_to_user(token: str = Depends(oauth2_scheme)): def token_to_user(token: str = Depends(oauth2_scheme)):
try: if token not in token_data["token"]:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) try:
username, expire = payload.get("sub"), payload.get("exp") payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user = get_user(username) username, expire = payload.get("sub"), payload.get("exp")
if user is None: user = get_user(username)
raise JWTError if user is None:
except JWTError: raise JWTError
raise credentials_exception except JWTError:
return user return Result(code=401)
return Result(code=200, data="ok")
if __name__ == '__main__': if __name__ == '__main__':
+2 -2
View File
@@ -7,7 +7,7 @@ import nonebot
app = nonebot.get_app() app = nonebot.get_app()
origins = ["http://localhost"] origins = ["*"]
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
@@ -45,7 +45,7 @@ class CountLimit(BaseModel):
""" """
max_count: int max_count: int
status: bool status: bool
limit_type: bool limit_type: str
rst: Optional[str] rst: Optional[str]
+1 -1
View File
@@ -61,7 +61,7 @@ async def _(event: MessageEvent, arg: Message = CommandArg()):
msg_sp = msg.split("<|>") msg_sp = msg.split("<|>")
w, h = w2b.size w, h = w2b.size
add_h, font_size = init_h_font_size(h) add_h, font_size = init_h_font_size(h)
bg = BuildImage(w, h + add_h, color="black", font_size=font_size) bg = BuildImage(w, h + add_h, color="black", font_size=int(font_size))
bg.paste(w2b) bg.paste(w2b)
chinese_msg = formalization_msg(msg) chinese_msg = formalization_msg(msg)
if not bg.check_font_size(chinese_msg): if not bg.check_font_size(chinese_msg):
+6 -8
View File
@@ -1,20 +1,18 @@
import re import re
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Event
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Event
from utils.utils import get_message_img_file from utils.utils import get_message_img_file
from nonebot.typing import T_State
from .model import WordBank from .model import WordBank
async def check(bot: Bot, event: Event, state: T_State) -> bool: async def check(event: Event) -> bool:
if isinstance(event, GroupMessageEvent): if isinstance(event, GroupMessageEvent):
msg = event.raw_message msg = event.raw_message
list_img = get_message_img_file(event.json()) list_img = get_message_img_file(event.json())
if list_img: if list_img:
for img_file in list_img: for img_file in list_img:
strinfo = re.compile(f"{img_file},subType=\d*]") strinfo = re.compile(f"{img_file},.*?]")
msg = strinfo.sub(f'{img_file}]', msg) msg = strinfo.sub(f'{img_file}]', msg)
return bool( strinfo_face = re.compile(f",type=sticker]")
await WordBank.check(event.group_id, msg, event.is_tome()) msg = strinfo_face.sub(f']', msg)
) return bool(await WordBank.check(event.group_id, msg,))
return False return False
+29 -11
View File
@@ -1,9 +1,10 @@
from utils.message_builder import image, at from utils.message_builder import image, at, face
from typing import Tuple
from ._rule import check from ._rule import check
from .model import WordBank from .model import WordBank
from configs.path_config import DATA_PATH from configs.path_config import DATA_PATH
from nonebot.adapters.onebot.v11 import GroupMessageEvent from nonebot.adapters.onebot.v11 import GroupMessageEvent
from utils.utils import get_message_at, get_message_img from utils.utils import get_message_at, get_message_img, change_img_md5
from nonebot import on_message from nonebot import on_message
from models.group_member_info import GroupInfoUser from models.group_member_info import GroupInfoUser
from utils.utils import get_message_img_file, is_number from utils.utils import get_message_img_file, is_number
@@ -23,16 +24,16 @@ async def _(event: GroupMessageEvent):
list_img = get_message_img_file(event.json()) list_img = get_message_img_file(event.json())
if list_img: if list_img:
for img_file in list_img: for img_file in list_img:
strinfo = re.compile(f"{img_file},subType=\d*]") strinfo = re.compile(f"{img_file},.*?]")
msg = strinfo.sub(f'{img_file}]', msg) msg = strinfo.sub(f'{img_file}]', msg)
q = await WordBank.check( strinfo_face = re.compile(f",type=sticker]")
event.group_id, msg, event.is_tome() msg = strinfo_face.sub(f']', msg)
) q = await WordBank.check(event.group_id, msg, )
await message_handle.send(await get_one_answer(event, q.format, q.answer)) await message_handle.send(await get_one_answer(event, q.format, q.answer))
# 处理单条回答 # 处理单条回答
async def get_one_answer(event, format, _answer, all=1): async def get_one_answer(event, format: str, _answer: str, all: bool = True) -> str:
path = data_dir / f"{event.group_id}" path = data_dir / f"{event.group_id}"
placeholder_list = ( placeholder_list = (
[ [
@@ -50,12 +51,13 @@ async def get_one_answer(event, format, _answer, all=1):
else: else:
for idx, placeholder in placeholder_list: for idx, placeholder in placeholder_list:
if placeholder.endswith("jpg"): if placeholder.endswith("jpg"):
change_img_md5(path / placeholder)
answer += _a[: _a.find(f"[__placeholder_{idx}]")] + image( answer += _a[: _a.find(f"[__placeholder_{idx}]")] + image(
path / placeholder path / placeholder
) )
else: else:
if all == 1: if all:
answer += _a[: _a.find(f"[__placeholder_{idx}]")] + at(placeholder) answer += _a[: _a.find(f"[__placeholder_{idx}]")] + at(int(placeholder))
else: else:
q = await GroupInfoUser.get_member_info( q = await GroupInfoUser.get_member_info(
int(placeholder), event.group_id) int(placeholder), event.group_id)
@@ -65,7 +67,7 @@ async def get_one_answer(event, format, _answer, all=1):
# 处理单条问题 # 处理单条问题
async def get_one_problem(event, problem): async def get_one_problem(event, problem: str, ) -> Tuple[str, str]:
strinfo = re.compile(f",subType=\d") strinfo = re.compile(f",subType=\d")
problem = strinfo.sub('', problem) problem = strinfo.sub('', problem)
_problem = problem _problem = problem
@@ -93,7 +95,7 @@ async def get_one_problem(event, problem):
# 显示单条数据库问题 # 显示单条数据库问题
async def get_one_image_problem(event, problem): async def get_one_image_problem(event, problem: str) -> str:
path = data_dir / f"{event.group_id}" / "problem" path = data_dir / f"{event.group_id}" / "problem"
placeholder_list = [] placeholder_list = []
idx = 0 idx = 0
@@ -127,3 +129,19 @@ async def get_one_image_problem(event, problem):
_p = _p[_p.find(f"[__placeholder_{idx}]") + len(f"[__placeholder_{idx}]"):] _p = _p[_p.find(f"[__placeholder_{idx}]") + len(f"[__placeholder_{idx}]"):]
return problem + _p return problem + _p
# 替换cq码
async def replace_cq(group_id, msg: str, is_face: bool = True) -> str:
strinfo_img = re.compile(f"\[CQ:image.*?]")
msg = strinfo_img.sub('[图片]', msg)
at_list = re.findall(rf"\[CQ:at,qq=(.*?)]", msg)
if at_list:
for ats in at_list:
q = await GroupInfoUser.get_member_info(
int(ats), group_id)
msg = msg.replace(f'[CQ:at,qq={ats}]', "@" + q.user_name)
if is_face:
strinfo_face = re.compile(f"\[CQ:face,id=.*?]")
msg = strinfo_face.sub('[表情]', msg)
return msg
+22 -42
View File
@@ -1,9 +1,7 @@
from services.db_context import db from services.db_context import db
from typing import Optional, List, Union, Tuple from typing import Optional, List, Union, Tuple
from datetime import datetime from datetime import datetime
from pathlib import Path
from configs.path_config import DATA_PATH from configs.path_config import DATA_PATH
import re
import random import random
from configs.config import Config from configs.config import Config
@@ -125,58 +123,40 @@ class WordBank(db.Model):
q.sort() q.sort()
_tmp = [] _tmp = []
for problem in q: for problem in q:
if "[_to_me" in problem:
r = re.search(r"\[_to_me\|(.*?)](.*)", problem)
if r:
bot_name = r.group(1)
problem = problem.replace(f"[_to_me|{bot_name}]", bot_name)
_tmp.append(problem) _tmp.append(problem)
return list(set(_tmp)) return list(set(_tmp))
@classmethod @classmethod
async def check(cls, group_id: int, problem: str, is_tome: bool = False) -> Optional["WordBank"]: async def check(cls, group_id: int, problem: str) -> Optional["WordBank"]:
""" """
检测词条并随机返回 检测词条并随机返回
:param group_id: 群号 :param group_id: 群号
:param problem: 问题 :param problem: 问题
:param is_tome:是否at真寻
""" """
if is_tome: if problem:
FUZZY = Config.get_config("word_bank", "WORD_BANK_FUZZY")
KEY = Config.get_config("word_bank", "WORD_BANK_KEY")
q = await cls.query.where( q = await cls.query.where(
(cls.group_id == group_id) (cls.group_id == group_id) & (cls.problem == problem)
).gino.all() ).gino.all()
q = [x for x in q if "[_to_me" in x.problem] if KEY and FUZZY:
if q: q_fuzzy = await cls.query.where(
for x in q: (cls.group_id == group_id) & (cls.search_type == 2) & (
r = re.search(r"\[_to_me\|(.*?)](.*)", x.problem) cls.problem.contains(f'{problem}'))).gino.all()
if r and r.group(2) == problem: q_key = await cls.query.where((cls.group_id == group_id) & (cls.search_type == 1)).gino.all()
return x q_key = [x for x in q_key if str(x.problem) in (problem)]
return None q += q_fuzzy + q_key
elif FUZZY:
q_fuzzy = await cls.query.where(
(cls.group_id == group_id) & (cls.search_type == 2) & (
cls.problem.contains(f'{problem}'))).gino.all()
q += q_fuzzy
elif KEY:
q_key = await cls.query.where((cls.group_id == group_id) & (cls.search_type == 1)).gino.all()
q_key = [x for x in q_key if str(x.problem) in (problem)]
q += q_key
else: else:
if problem: return None
FUZZY = Config.get_config("word_bank", "WORD_BANK_FUZZY")
KEY = Config.get_config("word_bank", "WORD_BANK_KEY")
q = await cls.query.where(
(cls.group_id == group_id) & (cls.problem == problem)
).gino.all()
if KEY and FUZZY:
q_fuzzy = await cls.query.where(
(cls.group_id == group_id) & (cls.search_type == 2) & (
cls.problem.contains(f'{problem}'))).gino.all()
q_key = await cls.query.where((cls.group_id == group_id) & (cls.search_type == 1)).gino.all()
q_key = [x for x in q_key if str(x.problem) in (problem)]
q += q_fuzzy + q_key
elif FUZZY:
q_fuzzy = await cls.query.where(
(cls.group_id == group_id) & (cls.search_type == 2) & (
cls.problem.contains(f'{problem}'))).gino.all()
q += q_fuzzy
elif KEY:
q_key = await cls.query.where((cls.group_id == group_id) & (cls.search_type == 1)).gino.all()
q_key = [x for x in q_key if str(x.problem) in (problem)]
q += q_key
else:
return None
return random.choice(q) if q else None return random.choice(q) if q else None
+20 -27
View File
@@ -6,14 +6,13 @@ from utils.http_utils import AsyncHttpx
from ._data_source import WordBankBuilder from ._data_source import WordBankBuilder
from utils.message_builder import image from utils.message_builder import image
from utils.image_utils import text2image from utils.image_utils import text2image
from .message_handle import get_one_answer, get_one_problem, get_one_image_problem from .message_handle import get_one_answer, get_one_problem, get_one_image_problem, replace_cq
from .model import WordBank from .model import WordBank
from nonebot.adapters.onebot.v11 import ( from nonebot.adapters.onebot.v11 import (
Bot, Bot,
GroupMessageEvent, GroupMessageEvent,
Message Message
) )
from nonebot.typing import T_State
from nonebot import on_command from nonebot import on_command
import random import random
import os import os
@@ -69,7 +68,7 @@ show_word = on_command("显示词条", aliases={"查看词条"}, priority=5, blo
@add_word.handle() @add_word.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = CommandArg()): async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
msg = str(arg) msg = str(arg)
r = re.search(r"问(.+)\s?答([\s\S]*)", msg) r = re.search(r"问(.+)\s?答([\s\S]*)", msg)
if not r: if not r:
@@ -81,12 +80,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = C
if not answer: if not answer:
await add_word.finish("未检测到词条回答...") await add_word.finish("未检测到词条回答...")
idx = 0 idx = 0
for n in bot.config.nickname: _problem = problem
if n and problem.startswith(n):
_problem = f"[_to_me|{n}]" + problem[len(n):]
break
else:
_problem = problem
search_type = 0 search_type = 0
if re.search("^关键字|词(.*)", msg): if re.search("^关键字|词(.*)", msg):
search_type = 1 search_type = 1
@@ -94,7 +88,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = C
search_type = 2 search_type = 2
_builder = await get__builder(event, _problem, answer, idx) _builder = await get__builder(event, _problem, answer, idx)
if await _builder.save(search_type): if await _builder.save(search_type):
logger.info(f"已保存词条 问:{_builder.problem} 答:{msg}") logger.info(f"已保存词条 问:{_builder.problem} 答:{answer}")
await add_word.send("已保存词条:" + _builder.problem) await add_word.send("已保存词条:" + _builder.problem)
else: else:
await delete_word.send("保存失败,可能是回答重复") await delete_word.send("保存失败,可能是回答重复")
@@ -102,7 +96,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = C
@delete_word.handle() @delete_word.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()): async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
msg = str(arg).strip() msg = str(arg)
if not msg: if not msg:
await delete_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") await delete_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
index = None index = None
@@ -124,7 +118,10 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
if answer := await WordBank.delete_problem_answer( if answer := await WordBank.delete_problem_answer(
event.user_id, event.group_id, _problem, index event.user_id, event.group_id, _problem, index
): ):
await delete_word.send("删除词条成功:" + problem + f"\n回答:\n{answer}")
await delete_word.send(Message(
"删除词条成功:\n问" + await replace_cq(event.group_id, problem, False) + f"\n回答:\n" + await replace_cq(
event.group_id, answer, False) + "\n"))
logger.info( logger.info(
f"(USER {event.user_id}, GROUP " f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})" f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
@@ -137,7 +134,7 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
@update_word.handle() @update_word.handle()
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()): async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
msg = str(arg) msg = str(arg)
if not msg: if not msg:
await update_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看") await update_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
@@ -157,12 +154,7 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
else: else:
await update_word.finish("此命令之后需要跟随修改内容") await update_word.finish("此命令之后需要跟随修改内容")
idx = 0 idx = 0
for n in bot.config.nickname: _problem = problem
if n and problem.startswith(n):
_problem = f"[_to_me|{n}]" + problem[len(n):]
break
else:
_problem = problem
_builder = await get__builder(event, _problem, new_answer, idx) _builder = await get__builder(event, _problem, new_answer, idx)
try: try:
@@ -185,8 +177,8 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
if not msg: if not msg:
_problem_list = await WordBank.get_group_all_problem(event.group_id) _problem_list = await WordBank.get_group_all_problem(event.group_id)
if not _problem_list: if not _problem_list:
await show_word.finish("该群未收录任何词条..") await show_word.finish("该群未收录任replace_cq何词条..")
_problem_list = [f"\t{i}. {x}" for i, x in enumerate(_problem_list)] _problem_list = [f"\t{i}. {await replace_cq(event.group_id, x)}" for i, x in enumerate(_problem_list)]
long_problem_list = len(_problem_list) long_problem_list = len(_problem_list)
max_line = Config.get_config("word_bank", "WORD_BANK_MIX") max_line = Config.get_config("word_bank", "WORD_BANK_MIX")
if long_problem_list > max_line: if long_problem_list > max_line:
@@ -245,10 +237,11 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
else: else:
# 解析图片和@ # 解析图片和@
_answer_img_nu_list = [await get_one_answer(event, format, answer, 0) for answer, format in _answer_list] _answer_img_nu_list = [await get_one_answer(event, format, answer, False) for answer, format in
_answer_list]
word_nu = len(_answer_img_nu_list) word_nu = len(_answer_img_nu_list)
img_nu = 0 img_nu = 0
answer = "词条" + msg + "回答:" answer = "词条" + msg + "\n回答:"
for i, x, in enumerate(_answer_img_nu_list): for i, x, in enumerate(_answer_img_nu_list):
r = re.findall(rf"\[CQ:image,file=", str(x)) r = re.findall(rf"\[CQ:image,file=", str(x))
if r: if r:
@@ -265,7 +258,7 @@ async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
# await show_word.send(f"词条 {msg} 回答:\n" + "\n".join(_answer_list)) # await show_word.send(f"词条 {msg} 回答:\n" + "\n".join(_answer_list))
async def get__builder(event, _problem, answer, idx): async def get__builder(event, _problem: str, answer: str, idx: int):
(data_dir / f"{event.group_id}").mkdir(exist_ok=True, parents=True) (data_dir / f"{event.group_id}").mkdir(exist_ok=True, parents=True)
(data_dir / f"{event.group_id}" / "problem").mkdir(exist_ok=True, parents=True) (data_dir / f"{event.group_id}" / "problem").mkdir(exist_ok=True, parents=True)
_builder = WordBankBuilder(event.user_id, event.group_id, _problem) _builder = WordBankBuilder(event.user_id, event.group_id, _problem)
@@ -293,16 +286,16 @@ async def get__builder(event, _problem, answer, idx):
if f"__placeholder_{rand}_{idx}.jpg" not in os.listdir(data_dir / f"{event.group_id}"): if f"__placeholder_{rand}_{idx}.jpg" not in os.listdir(data_dir / f"{event.group_id}"):
break break
rand = random.randint(1, 10000) + random.randint(1, 114514) rand = random.randint(1, 10000) + random.randint(1, 114514)
strinfo = re.compile(f"\[CQ:image,file={r.group(1)},url={_x_list[0]}\?{_x_list[1]},subType=\d*?]") strinfo = re.compile(f"\[CQ:image,file={r.group(1)},.*url={_x_list[0]}\?{_x_list[1]}.*?]")
answer = strinfo.sub(f"[__placeholder_{idx}]", answer) answer = strinfo.sub(f"[__placeholder_{idx}]", answer)
await AsyncHttpx.download_file( await AsyncHttpx.download_file(
img, data_dir / f"{event.group_id}" / f"__placeholder_{rand}_{idx}.jpg" img, data_dir / f"{event.group_id}" / f"__placeholder_{rand}_{idx}.jpg"
) )
_builder.set_placeholder(idx, f"__placeholder_{rand}_{idx}.jpg") _builder.set_placeholder(idx, f"__placeholder_{rand}_{idx}.jpg")
idx += 1 idx += 1
r_problem = re.search(rf"\[CQ:image,file=(.*?),url={_x}.*?]", _p) r_problem = re.search(rf"\[CQ:image,file=(.*?)(,subType=\d)?,url={_x}.*?]", _p)
if r_problem: if r_problem:
strinfo = re.compile(f",url={_x_list[0]}\?{_x_list[1]},subType=\d*?]") strinfo = re.compile(f"(,subType=\d)?,url={_x_list[0]}\?{_x_list[1]}.*?]")
_problem = strinfo.sub(f"]", _problem) _problem = strinfo.sub(f"]", _problem)
_p = strinfo.sub(f"]", _p) _p = strinfo.sub(f"]", _p)
problem += _p[: _p.find(f"[CQ:image,file={r_problem.group(1)}]")] + image(img) problem += _p[: _p.find(f"[CQ:image,file={r_problem.group(1)}]")] + image(img)
+19 -11
View File
@@ -12,6 +12,7 @@ import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from io import BytesIO from io import BytesIO
from configs.path_config import IMAGE_PATH, FONT_PATH from configs.path_config import IMAGE_PATH, FONT_PATH
from services import logger
from utils.http_utils import AsyncHttpx from utils.http_utils import AsyncHttpx
from models.chat_history import ChatHistory from models.chat_history import ChatHistory
from configs.config import Config from configs.config import Config
@@ -19,10 +20,11 @@ from configs.config import Config
async def pre_precess(msg: List[str], config) -> str: async def pre_precess(msg: List[str], config) -> str:
return await asyncio.get_event_loop().run_in_executor( return await asyncio.get_event_loop().run_in_executor(
None, _pre_precess, msg,config) None, _pre_precess, msg, config
)
def _pre_precess(msg: List[str],config) -> str: def _pre_precess(msg: List[str], config) -> str:
"""对消息进行预处理""" """对消息进行预处理"""
# 过滤掉命令 # 过滤掉命令
command_start = tuple([i for i in config.command_start if i]) command_start = tuple([i for i in config.command_start if i])
@@ -46,7 +48,6 @@ def _pre_precess(msg: List[str],config) -> str:
return msg return msg
async def draw_word_cloud(messages, config): async def draw_word_cloud(messages, config):
wordcloud_dir = IMAGE_PATH / "wordcloud" wordcloud_dir = IMAGE_PATH / "wordcloud"
wordcloud_dir.mkdir(exist_ok=True, parents=True) wordcloud_dir.mkdir(exist_ok=True, parents=True)
@@ -57,19 +58,21 @@ async def draw_word_cloud(messages, config):
url = "https://ghproxy.com/https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/resources/image/wordcloud/default.png" url = "https://ghproxy.com/https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/resources/image/wordcloud/default.png"
try: try:
await AsyncHttpx.download_file(url, zx_logo_path) await AsyncHttpx.download_file(url, zx_logo_path)
except: except Exception as e:
logger.error(f"词云图片资源下载发生错误 {type(e)}:{e}")
return False return False
if not wordcloud_ttf.exists(): if not wordcloud_ttf.exists():
ttf_url = 'https://ghproxy.com/https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/resources/font/STKAITI.TTF' ttf_url = "https://ghproxy.com/https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/resources/font/STKAITI.TTF"
try: try:
await AsyncHttpx.download_file(ttf_url, wordcloud_ttf) await AsyncHttpx.download_file(ttf_url, wordcloud_ttf)
except: except Exception as e:
logger.error(f"词云字体资源下载发生错误 {type(e)}:{e}")
return False return False
topK = min(int(len(messages)), 100000) topK = min(int(len(messages)), 100000)
read_name = jieba.analyse.extract_tags(await pre_precess(messages, config), topK=topK, read_name = jieba.analyse.extract_tags(
withWeight=True, await pre_precess(messages, config), topK=topK, withWeight=True, allowPOS=()
allowPOS=()) )
name = [] name = []
value = [] value = []
for t in read_name: for t in read_name:
@@ -79,10 +82,11 @@ async def draw_word_cloud(messages, config):
name[i] = str(name[i]) name[i] = str(name[i])
dic = dict(zip(name, value)) dic = dict(zip(name, value))
if Config.get_config("word_clouds", "WORD_CLOUDS_TEMPLATE") == 1: if Config.get_config("word_clouds", "WORD_CLOUDS_TEMPLATE") == 1:
def random_pic(base_path: str) -> str: def random_pic(base_path: str) -> str:
path_dir = os.listdir(base_path) path_dir = os.listdir(base_path)
path = random.sample(path_dir, 1)[0] path = random.sample(path_dir, 1)[0]
return (str(base_path) + "/" + str(path)) return str(base_path) + "/" + str(path)
mask = np.array(IMG.open(random_pic(wordcloud_dir))) mask = np.array(IMG.open(random_pic(wordcloud_dir)))
wc = WordCloud( wc = WordCloud(
@@ -113,7 +117,11 @@ async def draw_word_cloud(messages, config):
async def get_list_msg(user_id, group_id, days): async def get_list_msg(user_id, group_id, days):
messages_list = await ChatHistory()._get_msg(uid=user_id, gid=group_id, type_="group", days=days).gino.all() messages_list = (
await ChatHistory()
._get_msg(uid=user_id, gid=group_id, type_="group", days=days)
.gino.all()
)
if messages_list: if messages_list:
messages = [i.text for i in messages_list] messages = [i.text for i in messages_list]
return messages return messages
Generated
+115 -4
View File
@@ -325,6 +325,22 @@ type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple" url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali" reference = "ali"
[[package]]
name = "commonmark"
version = "0.9.1"
description = "Python parser for the CommonMark Markdown spec"
category = "main"
optional = false
python-versions = "*"
[package.extras]
test = ["flake8 (==3.7.8)", "hypothesis (==3.55.3)"]
[package.source]
type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali"
[[package]] [[package]]
name = "cycler" name = "cycler"
version = "0.11.0" version = "0.11.0"
@@ -423,7 +439,7 @@ reference = "ali"
[[package]] [[package]]
name = "feedparser" name = "feedparser"
version = "6.0.9" version = "6.0.10"
description = "Universal feed parser, handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds" description = "Universal feed parser, handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds"
category = "main" category = "main"
optional = false optional = false
@@ -988,6 +1004,19 @@ type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple" url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali" reference = "ali"
[[package]]
name = "pygments"
version = "2.12.0"
description = "Pygments is a syntax highlighting package written in Python."
category = "main"
optional = false
python-versions = ">=3.6"
[package.source]
type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali"
[[package]] [[package]]
name = "pygtrie" name = "pygtrie"
version = "2.4.2" version = "2.4.2"
@@ -1173,6 +1202,29 @@ type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple" url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali" reference = "ali"
[[package]]
name = "requests"
version = "2.27.1"
description = "Python HTTP for Humans."
category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"
[package.dependencies]
certifi = ">=2017.4.17"
charset-normalizer = {version = ">=2.0.0,<2.1.0", markers = "python_version >= \"3\""}
idna = {version = ">=2.5,<4", markers = "python_version >= \"3\""}
urllib3 = ">=1.21.1,<1.27"
[package.extras]
socks = ["PySocks (>=1.5.6,!=1.5.7)", "win-inet-pton"]
use_chardet_on_py3 = ["chardet (>=3.0.2,<5)"]
[package.source]
type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali"
[[package]] [[package]]
name = "retrying" name = "retrying"
version = "1.3.3" version = "1.3.3"
@@ -1208,6 +1260,27 @@ type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple" url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali" reference = "ali"
[[package]]
name = "rich"
version = "12.4.4"
description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
category = "main"
optional = false
python-versions = ">=3.6.3,<4.0.0"
[package.dependencies]
commonmark = ">=0.9.0,<0.10.0"
pygments = ">=2.6.0,<3.0.0"
typing-extensions = {version = ">=4.0.0,<5.0", markers = "python_version < \"3.9\""}
[package.extras]
jupyter = ["ipywidgets (>=7.5.1,<8.0.0)"]
[package.source]
type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali"
[[package]] [[package]]
name = "rsa" name = "rsa"
version = "4.8" version = "4.8"
@@ -1478,6 +1551,24 @@ type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple" url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali" reference = "ali"
[[package]]
name = "urllib3"
version = "1.26.9"
description = "HTTP library with thread-safe connection pooling, file post, and more."
category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4"
[package.extras]
brotli = ["brotlicffi (>=0.8.0)", "brotli (>=1.0.9)", "brotlipy (>=0.6.0)"]
secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "ipaddress"]
socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"]
[package.source]
type = "legacy"
url = "https://mirrors.aliyun.com/pypi/simple"
reference = "ali"
[[package]] [[package]]
name = "uvicorn" name = "uvicorn"
version = "0.17.6" version = "0.17.6"
@@ -1620,7 +1711,7 @@ reference = "ali"
[metadata] [metadata]
lock-version = "1.1" lock-version = "1.1"
python-versions = "^3.8" python-versions = "^3.8"
content-hash = "1890d2859d3ad815037187b8ec867636f4d3f5e2b13088c110747ace41358ca4" content-hash = "e6353cc684e80bdf86462ed0aee02a19fab99d22c8bb6b08204ecb4ffc2e940d"
[metadata.files] [metadata.files]
aiofiles = [ aiofiles = [
@@ -1790,6 +1881,10 @@ colorama = [
{file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"}, {file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"},
{file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"}, {file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"},
] ]
commonmark = [
{file = "commonmark-0.9.1-py2.py3-none-any.whl", hash = "sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9"},
{file = "commonmark-0.9.1.tar.gz", hash = "sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60"},
]
cycler = [ cycler = [
{file = "cycler-0.11.0-py3-none-any.whl", hash = "sha256:3a27e95f763a428a739d2add979fa7494c912a32c17c4c38c4d5f082cad165a3"}, {file = "cycler-0.11.0-py3-none-any.whl", hash = "sha256:3a27e95f763a428a739d2add979fa7494c912a32c17c4c38c4d5f082cad165a3"},
{file = "cycler-0.11.0.tar.gz", hash = "sha256:9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f"}, {file = "cycler-0.11.0.tar.gz", hash = "sha256:9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f"},
@@ -1810,8 +1905,8 @@ fastapi = [
{file = "fastapi-0.78.0.tar.gz", hash = "sha256:3233d4a789ba018578658e2af1a4bb5e38bdd122ff722b313666a9b2c6786a83"}, {file = "fastapi-0.78.0.tar.gz", hash = "sha256:3233d4a789ba018578658e2af1a4bb5e38bdd122ff722b313666a9b2c6786a83"},
] ]
feedparser = [ feedparser = [
{file = "feedparser-6.0.9-py3-none-any.whl", hash = "sha256:a522b2b81f3914a74ae44161a341940f74811bd29be5b4c2a689e6e6be51cd39"}, {file = "feedparser-6.0.10-py3-none-any.whl", hash = "sha256:79c257d526d13b944e965f6095700587f27388e50ea16fd245babe4dfae7024f"},
{file = "feedparser-6.0.9.tar.gz", hash = "sha256:dad42e7beaec55f99c08b2b0cf7288bc7cfd24b6f72c8ef85478bcb55648cd42"}, {file = "feedparser-6.0.10.tar.gz", hash = "sha256:27da485f4637ce7163cdeab13a80312b93b7d0c1b775bef4a47629a3110bca51"},
] ]
fonttools = [ fonttools = [
{file = "fonttools-4.33.3-py3-none-any.whl", hash = "sha256:f829c579a8678fa939a1d9e9894d01941db869de44390adb49ce67055a06cc2a"}, {file = "fonttools-4.33.3-py3-none-any.whl", hash = "sha256:f829c579a8678fa939a1d9e9894d01941db869de44390adb49ce67055a06cc2a"},
@@ -2338,6 +2433,10 @@ pyee = [
{file = "pyee-8.1.0-py2.py3-none-any.whl", hash = "sha256:383973b63ad7ed5e3c0311f8b179c52981f9e7b3eaea0e9a830d13ec34dde65f"}, {file = "pyee-8.1.0-py2.py3-none-any.whl", hash = "sha256:383973b63ad7ed5e3c0311f8b179c52981f9e7b3eaea0e9a830d13ec34dde65f"},
{file = "pyee-8.1.0.tar.gz", hash = "sha256:92dacc5bd2bdb8f95aa8dd2585d47ca1c4840e2adb95ccf90034d64f725bfd31"}, {file = "pyee-8.1.0.tar.gz", hash = "sha256:92dacc5bd2bdb8f95aa8dd2585d47ca1c4840e2adb95ccf90034d64f725bfd31"},
] ]
pygments = [
{file = "Pygments-2.12.0-py3-none-any.whl", hash = "sha256:dc9c10fb40944260f6ed4c688ece0cd2048414940f1cea51b8b226318411c519"},
{file = "Pygments-2.12.0.tar.gz", hash = "sha256:5eb116118f9612ff1ee89ac96437bb6b49e8f04d8a13b514ba26f620208e26eb"},
]
pygtrie = [ pygtrie = [
{file = "pygtrie-2.4.2.tar.gz", hash = "sha256:43205559d28863358dbbf25045029f58e2ab357317a59b11f11ade278ac64692"}, {file = "pygtrie-2.4.2.tar.gz", hash = "sha256:43205559d28863358dbbf25045029f58e2ab357317a59b11f11ade278ac64692"},
] ]
@@ -2511,6 +2610,10 @@ regex = [
{file = "regex-2022.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:9efa41d1527b366c88f265a227b20bcec65bda879962e3fc8a2aee11e81266d7"}, {file = "regex-2022.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:9efa41d1527b366c88f265a227b20bcec65bda879962e3fc8a2aee11e81266d7"},
{file = "regex-2022.3.2.tar.gz", hash = "sha256:79e5af1ff258bc0fe0bdd6f69bc4ae33935a898e3cbefbbccf22e88a27fa053b"}, {file = "regex-2022.3.2.tar.gz", hash = "sha256:79e5af1ff258bc0fe0bdd6f69bc4ae33935a898e3cbefbbccf22e88a27fa053b"},
] ]
requests = [
{file = "requests-2.27.1-py2.py3-none-any.whl", hash = "sha256:f22fa1e554c9ddfd16e6e41ac79759e17be9e492b3587efa038054674760e72d"},
{file = "requests-2.27.1.tar.gz", hash = "sha256:68d7c56fd5a8999887728ef304a6d12edc7be74f1cfa47714fc8b414525c9a61"},
]
retrying = [ retrying = [
{file = "retrying-1.3.3.tar.gz", hash = "sha256:08c039560a6da2fe4f2c426d0766e284d3b736e355f8dd24b37367b0bb41973b"}, {file = "retrying-1.3.3.tar.gz", hash = "sha256:08c039560a6da2fe4f2c426d0766e284d3b736e355f8dd24b37367b0bb41973b"},
] ]
@@ -2518,6 +2621,10 @@ rfc3986 = [
{file = "rfc3986-1.5.0-py2.py3-none-any.whl", hash = "sha256:a86d6e1f5b1dc238b218b012df0aa79409667bb209e58da56d0b94704e712a97"}, {file = "rfc3986-1.5.0-py2.py3-none-any.whl", hash = "sha256:a86d6e1f5b1dc238b218b012df0aa79409667bb209e58da56d0b94704e712a97"},
{file = "rfc3986-1.5.0.tar.gz", hash = "sha256:270aaf10d87d0d4e095063c65bf3ddbc6ee3d0b226328ce21e036f946e421835"}, {file = "rfc3986-1.5.0.tar.gz", hash = "sha256:270aaf10d87d0d4e095063c65bf3ddbc6ee3d0b226328ce21e036f946e421835"},
] ]
rich = [
{file = "rich-12.4.4-py3-none-any.whl", hash = "sha256:d2bbd99c320a2532ac71ff6a3164867884357da3e3301f0240090c5d2fdac7ec"},
{file = "rich-12.4.4.tar.gz", hash = "sha256:4c586de507202505346f3e32d1363eb9ed6932f0c2f63184dea88983ff4971e2"},
]
rsa = [ rsa = [
{file = "rsa-4.8-py3-none-any.whl", hash = "sha256:95c5d300c4e879ee69708c428ba566c59478fd653cc3a22243eeb8ed846950bb"}, {file = "rsa-4.8-py3-none-any.whl", hash = "sha256:95c5d300c4e879ee69708c428ba566c59478fd653cc3a22243eeb8ed846950bb"},
{file = "rsa-4.8.tar.gz", hash = "sha256:5c6bd9dc7a543b7fe4304a631f8a8a3b674e2bbfc49c2ae96200cdbe55df6b17"}, {file = "rsa-4.8.tar.gz", hash = "sha256:5c6bd9dc7a543b7fe4304a631f8a8a3b674e2bbfc49c2ae96200cdbe55df6b17"},
@@ -2705,6 +2812,10 @@ ujson = [
{file = "ujson-5.3.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:a68d5a8a46712ffe86db8ae1b4311714db534725521c71fd4c9e1cd062dae9a4"}, {file = "ujson-5.3.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:a68d5a8a46712ffe86db8ae1b4311714db534725521c71fd4c9e1cd062dae9a4"},
{file = "ujson-5.3.0.tar.gz", hash = "sha256:ab938777b3ac0372231ee654a7f6a13787e587b1ca268d8aa7e6fb6846e477d0"}, {file = "ujson-5.3.0.tar.gz", hash = "sha256:ab938777b3ac0372231ee654a7f6a13787e587b1ca268d8aa7e6fb6846e477d0"},
] ]
urllib3 = [
{file = "urllib3-1.26.9-py2.py3-none-any.whl", hash = "sha256:44ece4d53fb1706f667c9bd1c648f5469a2ec925fcf3a776667042d645472c14"},
{file = "urllib3-1.26.9.tar.gz", hash = "sha256:aabaf16477806a5e1dd19aa41f8c2b7950dd3c746362d7e3223dbe6de6ac448e"},
]
uvicorn = [ uvicorn = [
{file = "uvicorn-0.17.6-py3-none-any.whl", hash = "sha256:19e2a0e96c9ac5581c01eb1a79a7d2f72bb479691acd2b8921fce48ed5b961a6"}, {file = "uvicorn-0.17.6-py3-none-any.whl", hash = "sha256:19e2a0e96c9ac5581c01eb1a79a7d2f72bb479691acd2b8921fce48ed5b961a6"},
{file = "uvicorn-0.17.6.tar.gz", hash = "sha256:5180f9d059611747d841a4a4c4ab675edf54c8489e97f96d0583ee90ac3bfc23"}, {file = "uvicorn-0.17.6.tar.gz", hash = "sha256:5180f9d059611747d841a4a4c4ab675edf54c8489e97f96d0583ee90ac3bfc23"},
+1
View File
@@ -42,6 +42,7 @@ python-multipart = "^0.0.5"
bilireq = "^0.1.2" bilireq = "^0.1.2"
emoji = "^1.7.0" emoji = "^1.7.0"
wordcloud = "^1.8.1" wordcloud = "^1.8.1"
rich = "^12.4.3"
[tool.poetry.dev-dependencies] [tool.poetry.dev-dependencies]
Binary file not shown.

After

Width:  |  Height:  |  Size: 600 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 614 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 534 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 466 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 479 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 501 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 518 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 709 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 747 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 653 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 543 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 587 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 738 KiB

Some files were not shown because too many files have changed in this diff Show More