mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-09-30 01:00:02 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8381858742 | ||
|
|
1040bd0d58 | ||
|
|
404e47332e | ||
|
|
3db128785e | ||
|
|
2189ea11df | ||
|
|
49b9bd65b0 | ||
|
|
b3fdb1ff58 | ||
|
|
c79e3fdcf0 | ||
|
|
d7509f7030 | ||
|
|
5c99b55502 | ||
|
|
fd255f022b | ||
|
|
41642589ae | ||
|
|
619fef3bff | ||
|
|
38c0da0cf8 | ||
|
|
b241a58e84 | ||
|
|
35c9585b22 | ||
|
|
d2fe95cc05 | ||
|
|
92e60ba141 | ||
|
|
2356527791 | ||
|
|
cab0f7b522 | ||
|
|
02743d5955 | ||
|
|
a7ffebea35 | ||
|
|
c511ef50a2 | ||
|
|
82902e0cde | ||
|
|
1de5ae09bc | ||
|
|
8b735f1cb5 | ||
|
|
33d1334174 | ||
|
|
324b58c21b | ||
|
|
b7b1651709 | ||
|
|
b5a4a6a9ff | ||
|
|
fe2c82b03c | ||
|
|
81e4bca9ef | ||
|
|
c0d055b825 | ||
|
|
188ae38525 | ||
|
|
86a8fe7096 | ||
|
|
0bb2b45f5c | ||
|
|
a17d8731c8 | ||
|
|
9cdd2326c8 | ||
|
|
d75653631d | ||
|
|
e234c8906e | ||
|
|
57baea18b5 | ||
|
|
0f3efe29c4 | ||
|
|
89b87a38b3 | ||
|
|
c52b7ca2e9 | ||
|
|
371b55dc9e | ||
|
|
53e572353c | ||
|
|
3ae71c74e9 | ||
|
|
cb643c04f7 | ||
|
|
faf9ee159b | ||
|
|
ffb3b2d73e | ||
|
|
ffcc327089 | ||
|
|
dfd5a6a86a | ||
|
|
d43f89b067 | ||
|
|
f15c3ab6a2 | ||
|
|
e27809298e | ||
|
|
4b3e28e14b | ||
|
|
71ce9153ed | ||
|
|
25d63966de | ||
|
|
98afbb54b6 | ||
|
|
03a51ca5dd | ||
|
|
428481b2d5 | ||
|
|
f87c60e6db | ||
|
|
6d824e38bc | ||
|
|
f0fd5bfb9e | ||
|
|
33374df671 | ||
|
|
c035b1b19c | ||
|
|
b3b09ed666 | ||
|
|
8029c00a02 | ||
|
|
a2c0921013 | ||
|
|
31cdabc229 | ||
|
|
1059a0aae0 | ||
|
|
e6576e7f40 | ||
|
|
5837144095 | ||
|
|
d30a5c4207 | ||
|
|
7d169b0e5e | ||
|
|
1f54226673 | ||
|
|
901a90ff13 | ||
|
|
56573d1d34 | ||
|
|
b0ab78340a | ||
|
|
93539be492 | ||
|
|
c551e21766 | ||
|
|
ed342af97d | ||
|
|
17b87a2cb1 | ||
|
|
69ca02834d | ||
|
|
6cb4099a2e | ||
|
|
e75a4966b2 | ||
|
|
d55cba49bd | ||
|
|
0215abac30 | ||
|
|
2dcac5f009 | ||
|
|
0d8c64f7d1 | ||
|
|
55626645fb | ||
|
|
f7925fa259 | ||
|
|
c814ae08b1 | ||
|
|
24666368f7 | ||
|
|
a77e85b62d | ||
|
|
6319c7fce1 | ||
|
|
a45b95d5d4 | ||
|
|
188f6f0f99 | ||
|
|
a72f126d8f | ||
|
|
33eb1b83a8 | ||
|
|
2d9ebe2e6d | ||
|
|
262b098dec | ||
|
|
79d88065aa | ||
|
|
0f59895c3b | ||
|
|
610d588e34 | ||
|
|
f99abb2f98 | ||
|
|
b2b7560d05 | ||
|
|
07c16e5238 | ||
|
|
1741ea7d26 | ||
|
|
b5ce4fab31 | ||
|
|
062e4c2062 | ||
|
|
0adb66a8bf | ||
|
|
2aad517112 | ||
|
|
14d1512b1e | ||
|
|
3f533516af | ||
|
|
f1354308fd | ||
|
|
c06248e46b | ||
|
|
9c8eaed938 | ||
|
|
2081302e32 | ||
|
|
678fc19f2d | ||
|
|
adc2757e8e | ||
|
|
82a1261371 |
@@ -142,7 +142,5 @@ test.py
|
||||
server_ip.py
|
||||
member_activity_handle.py
|
||||
Yu-Gi-Oh/
|
||||
search_image/
|
||||
black_word/
|
||||
csgo/
|
||||
fantasy_card/
|
||||
|
||||
@@ -18,10 +18,6 @@
|
||||
## 声明
|
||||
此项目仅用于学习交流,请勿用于非法用途
|
||||
|
||||
## Gitee
|
||||
|
||||
# [Gitee](https://gitee.com/two_Dimension/zhenxun_bot)
|
||||
|
||||
## 未完成的文档
|
||||
|
||||
# [传送门](https://hibikier.github.io/zhenxun_bot/)
|
||||
@@ -32,6 +28,12 @@
|
||||
## 普通帮助图片
|
||||

|
||||
|
||||
## Web UI
|
||||
[zhenxun_bot_webui](https://github.com/HibiKier/zhenxun_bot_webui)
|
||||
|
||||
## 一键安装脚本
|
||||
[zhenxun_bot-deploy](https://github.com/AkashiCoin/zhenxun_bot-deploy)
|
||||
|
||||
## 提供符合真寻标准的插件仓库
|
||||
|
||||
[AkashiCoin/nonebot_plugins_zhenxun_bot](https://github.com/AkashiCoin/nonebot_plugins_zhenxun_bot)
|
||||
@@ -236,6 +238,151 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
|
||||
|
||||
## 更新
|
||||
|
||||
### 2022/5/23 \[v1.5.6]
|
||||
|
||||
* 修复"清除已删除插件数据" [@pull/545](https://github.com/HibiKier/zhenxun_bot/pull/545)
|
||||
* 修复有置顶的up主B站动态获取失败 [@pull/552](https://github.com/HibiKier/zhenxun_bot/pull/552)
|
||||
* 添加pixiv搜图多关键词支持;修复p站搜图数量参数问题 [@pull/441](https://github.com/HibiKier/zhenxun_bot/pull/441)
|
||||
* 修复开箱更新价格错误传参
|
||||
* 修复pix无法正确查询uid
|
||||
* 新增色图插件添加配置项ALLOW_GROUP_R18:允许群聊中使用色图r
|
||||
* 新增PIX插件添加配置项ALLOW_GROUP_SETU:允许非超级用户使用-s参数
|
||||
* 新增PIX插件添加配置项ALLOW_GROUP_R18:允许非超级用户使用-r参数
|
||||
|
||||
### 2022/5/22 \[v0.1.5.4]
|
||||
|
||||
* 使用action自动更新poetry.lock [@pull/515](https://github.com/HibiKier/zhenxun_bot/pull/515)
|
||||
* fix(bilibili_sub): card is None and timeout [@pull/516](https://github.com/HibiKier/zhenxun_bot/pull/516)
|
||||
* 修复了epic有时获取新免费游戏消息时获取不到图片
|
||||
* 修复好感度满时签到出错(虽然是不可能满的
|
||||
* 修复原神资源图标下载路径错误
|
||||
* 修复自动更新群组可能失败
|
||||
|
||||
### 2022/5/21
|
||||
|
||||
* 修复搜番无结果时报错无正确反馈
|
||||
* 解锁了windows上无法使用playwright的限制
|
||||
* 修复p搜对应pid有多张图时出错,改为连续发送图片
|
||||
* 修复p搜对数字的错误判断
|
||||
* 修复添加商品折扣无法正确添加
|
||||
* 修复了bilibili订阅直播间订阅up名称不一致的问题
|
||||
* 修复原神玩家查询没开地图时报错
|
||||
* 最低priority修改为 999
|
||||
* 修复刷屏检测失效
|
||||
* 修复刷屏检测设置命令无法生效
|
||||
* 优化刷屏显示设置禁言时长显示,并改为分钟
|
||||
* 修复了多连开箱无法指定武器箱
|
||||
* 修复识番链接无法正确获取
|
||||
* 新增真寻入群时即刻刷新权限
|
||||
* 提高了微博热搜截图的等待时间
|
||||
|
||||
### 2022/5/19
|
||||
|
||||
* fix: mihoyo bbs api changed [@pull/357](https://github.com/HibiKier/zhenxun_bot/pull/357)
|
||||
* Add word_clouds [@pull/265](https://github.com/HibiKier/zhenxun_bot/pull/265)
|
||||
* Fix wrong live streamer name [@pull/284](https://github.com/HibiKier/zhenxun_bot/pull/284)
|
||||
|
||||
### 2022/5/16
|
||||
|
||||
* 词条支持图片和@问题 [@pull/160](https://github.com/HibiKier/zhenxun_bot/pull/160)
|
||||
|
||||
### 2022/5/15
|
||||
|
||||
* 修复了商店商品无法正确添加
|
||||
* 修复了多张色图无法正确发送
|
||||
|
||||
### 2022/5/14
|
||||
|
||||
* 修复B站动态生成失败的问题 [@pull/159](https://github.com/HibiKier/zhenxun_bot/pull/159)
|
||||
|
||||
### 2022/5/11
|
||||
|
||||
* fix: 更改p搜api,解决p搜无法使用的问题 [@pull/155](https://github.com/HibiKier/zhenxun_bot/pull/155)
|
||||
|
||||
### 2022/5/9 \[v0.1.5.3]
|
||||
|
||||
* 替换了疫情API
|
||||
* 修复了私聊.ban/.unban出错
|
||||
|
||||
### 2022/5/5
|
||||
|
||||
* 修改bilibili_sub插件在windows平台下报错 [@pull/153](https://github.com/HibiKier/zhenxun_bot/pull/153)
|
||||
|
||||
### 2022/5/3 \[v0.1.5.2]
|
||||
|
||||
* 商品使用函数可以添加特定参数,例如:user_id, group_id, ShopParam等以及自己提供的参数
|
||||
* 添加商品注册装饰器shop_register
|
||||
* 修复商品函数kwargs无法获取参数值
|
||||
|
||||
|
||||
### 2022/5/1
|
||||
|
||||
* 删除了`group_last_chat`插件(该功能可由`chat_history`替代
|
||||
* 新增敏感词检测(全新反击系统,是时候重拳出击了
|
||||
|
||||
### 2022/4/26
|
||||
|
||||
* 修复了群白名单无法正确添加
|
||||
* 优化了管理员帮助图片,背景图层将位于最下层
|
||||
* 修复了树脂140时不断提醒(未测试
|
||||
* 新增了消息记录的消息排行
|
||||
* WebUI新增CPU,内存,磁盘监控
|
||||
* WebUI新增资源文件夹统计可视化
|
||||
|
||||
### 2022/4/12
|
||||
|
||||
* 修复b了命令私聊出错
|
||||
|
||||
### 2022/4/10 \[v0.1.4.7]
|
||||
|
||||
* 新增消息记录模块
|
||||
* 丰富处理请求操作提示
|
||||
* web ui新增配置项修改
|
||||
|
||||
### 2022/4/9
|
||||
|
||||
* fix: 更新问题,戳一戳图片路径问题 [@pull/144](https://github.com/HibiKier/zhenxun_bot/pull/144)
|
||||
|
||||
### 2022/4/8
|
||||
|
||||
* 修复原神玩家查询
|
||||
|
||||
### 2022/4/6
|
||||
|
||||
* update search_type [@pull/143](https://github.com/HibiKier/zhenxun_bot/pull/143)
|
||||
|
||||
### 2022/4/5 \[v0.1.4.6]
|
||||
|
||||
* 修复web修改插件后帮助图片生成错误
|
||||
|
||||
### 2022/4/4 \[v0.1.4.5]
|
||||
|
||||
* 替换了bt搜索URL
|
||||
* 优化使用playwright的相关代码
|
||||
* 原神玩家查询新增层岩巨渊探索
|
||||
* 修复原神便笺角色头像黑框
|
||||
* 修复同意群聊请求错误
|
||||
* 提供webui方面的api
|
||||
* 新增web-ui(前端简易管理页面插件)插件
|
||||
|
||||
### 2022/3/21
|
||||
|
||||
* 修复statistics_handle.py乱码
|
||||
|
||||
### 2022/3/18 \[v0.1.4.4]
|
||||
|
||||
* 修复戳一戳无法功能关闭与ban禁用
|
||||
* 新增图片搜索 search_image
|
||||
|
||||
### 2022/3/7
|
||||
|
||||
* 优化增删权限插件
|
||||
|
||||
### 2022/3/6
|
||||
|
||||
* 修复树脂提醒无法开启
|
||||
* 修复p搜图片路径错误
|
||||
|
||||
### 2022/3/3 \[v0.1.4.3]
|
||||
|
||||
* 修复手动同意群聊请求依旧退出
|
||||
@@ -292,7 +439,6 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
|
||||
|
||||
* 适配nonebot.beta2
|
||||
* 删除图片搜索 nonebot_plugin_picsearcher
|
||||
* 新增图片搜索 search_image
|
||||
* 替换cos api
|
||||
* 原神签到树脂提醒新增绑定群里,在某群绑定uid就会在某群发送提醒信息(有好友则私聊,需要重新绑定uid
|
||||
* 修改update_info.json
|
||||
@@ -301,15 +447,15 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
|
||||
* epic restful 替换 [@pull/119](https://github.com/HibiKier/zhenxun_bot/pull/119)
|
||||
* fix: 修复远古时期残留的epic推送问题 [@pull/122](https://github.com/HibiKier/zhenxun_bot/pull/122)
|
||||
|
||||
### 2021/2/11
|
||||
### 2022/2/11
|
||||
|
||||
* 修复pix不使用反代无法下载图片
|
||||
|
||||
### 2021/2/10 \[v0.1.1]
|
||||
### 2022/2/10 \[v0.1.1]
|
||||
|
||||
* 修复购买道具出错
|
||||
|
||||
### 2021/2/9 \[v0.1]
|
||||
### 2022/2/9 \[v0.1]
|
||||
|
||||
* 新增原神自动签到和手动签到
|
||||
* 新增原神树脂提醒
|
||||
@@ -319,7 +465,7 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
|
||||
* 修复修改商品时限制时间出错
|
||||
* 修复超时商品依旧可以被购买
|
||||
|
||||
### 2021/1/16 \[v0.0.9.0]
|
||||
### 2022/1/16 \[v0.0.9.0]
|
||||
|
||||
* Ai提供文本敏感词过滤器
|
||||
* 疫情插件适配新版腾讯API
|
||||
@@ -338,7 +484,7 @@ __Docker 最新版本由 [Sakuracio](https://github.com/Sakuracio) 提供__
|
||||
* “send_success_msg”(发送成功的交互信息->即:使用道具 {name} {num} 次成功)
|
||||
* “_max_num_limit”(该道具单次使用的最多个数,默认1)
|
||||
|
||||
### 2021/1/5 \[v0.0.8.2]
|
||||
### 2022/1/5 \[v0.0.8.2]
|
||||
|
||||
* 提供金币消费hook,可在plugins2settings.yaml中配置该功能需要消费的金币
|
||||
* 商店插件将作为内置插件移动至basic_plugins
|
||||
@@ -409,4 +555,4 @@ __..... 更多更新信息请查看文档__
|
||||
[NothAmor / nonebot2_luxun_says](https://github.com/NothAmor/nonebot2_luxun_says) :基于nonebot2机器人框架的鲁迅说插件
|
||||
[Kyomotoi / AnimeThesaurus](https://github.com/Kyomotoi/AnimeThesaurus) :一个~~特二刺螈~~(文爱)的适用于任何bot的词库
|
||||
[Ailitonia / omega-miya](https://github.com/Ailitonia/omega-miya) :基于nonebot2的qq机器人
|
||||
[KimigaiiWuyi / GenshinUID]("https://github.com/KimigaiiWuyi/GenshinUID") :一个基于HoshinoBot/NoneBot2的原神UID查询插件
|
||||
[KimigaiiWuyi / GenshinUID](https://github.com/KimigaiiWuyi/GenshinUID) :一个基于HoshinoBot/NoneBot2的原神UID查询插件
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__: v0.1.4.3
|
||||
__version__: v0.1.5.6
|
||||
@@ -232,10 +232,7 @@ async def update_member_info(group_id: int, remind_superuser: bool = False) -> b
|
||||
_exist_member_list = []
|
||||
# try:
|
||||
for user_info in _group_user_list:
|
||||
if user_info["card"] == "":
|
||||
nickname = user_info["nickname"]
|
||||
else:
|
||||
nickname = user_info["card"]
|
||||
nickname = user_info["card"] or user_info["nickname"]
|
||||
async with db.transaction():
|
||||
# 更新权限
|
||||
if (
|
||||
@@ -321,3 +318,4 @@ def set_group_bot_status(group_id: int, status: bool) -> str:
|
||||
# for x in group_manager.get_task_data():
|
||||
# group_manager.close_group_task(group_id, x)
|
||||
return "那我先睡觉了..."
|
||||
|
||||
|
||||
@@ -24,11 +24,17 @@ def switch_rule(event: Event) -> bool:
|
||||
_data = plugins2settings_manager.get_data()
|
||||
for key in _data:
|
||||
try:
|
||||
for x in _data[key]["cmd"]:
|
||||
cmd.append(f"开启{x}")
|
||||
cmd.append(f"关闭{x}")
|
||||
cmd.append(f"开启 {x}")
|
||||
cmd.append(f"关闭 {x}")
|
||||
if isinstance(_data[key]["cmd"], list):
|
||||
for x in _data[key]["cmd"]:
|
||||
cmd.append(f"开启{x}")
|
||||
cmd.append(f"关闭{x}")
|
||||
cmd.append(f"开启 {x}")
|
||||
cmd.append(f"关闭 {x}")
|
||||
else:
|
||||
cmd.append(f"开启{key}")
|
||||
cmd.append(f"关闭{key}")
|
||||
cmd.append(f"开启 {key}")
|
||||
cmd.append(f"关闭 {key}")
|
||||
except KeyError:
|
||||
pass
|
||||
msg = get_message_text(event.json()).split()
|
||||
|
||||
@@ -2,6 +2,7 @@ from nonebot import on_command, on_notice
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, GROUP, GroupIncreaseNoticeEvent
|
||||
from ._data_source import update_member_info
|
||||
|
||||
|
||||
__zx_plugin_name__ = "更新群组成员列表 [Admin]"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
|
||||
@@ -5,7 +5,6 @@ from utils.utils import get_matchers
|
||||
from utils.manager import group_manager
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from nonebot import Driver
|
||||
import asyncio
|
||||
import nonebot
|
||||
|
||||
|
||||
@@ -27,12 +26,10 @@ async def create_help_image():
|
||||
"""
|
||||
创建管理员帮助图片
|
||||
"""
|
||||
await asyncio.get_event_loop().run_in_executor(
|
||||
None, _create_help_image
|
||||
)
|
||||
await _create_help_image()
|
||||
|
||||
|
||||
def _create_help_image():
|
||||
async def _create_help_image():
|
||||
"""
|
||||
创建管理员帮助图片
|
||||
"""
|
||||
@@ -85,9 +82,9 @@ def _create_help_image():
|
||||
height = len(help_str.split("\n")) * 33
|
||||
A = BuildImage(width, height, font_size=24)
|
||||
_background = BuildImage(width, height, background=background)
|
||||
A.text((150, 110), help_str)
|
||||
A.paste(_background, alpha=True)
|
||||
A.save(admin_help_image)
|
||||
await A.apaste(_background, alpha=True)
|
||||
await A.atext((150, 110), help_str)
|
||||
await A.asave(admin_help_image)
|
||||
logger.info(f'已成功加载 {len(_plugin_name_list)} 条管理员命令')
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent, MessageEvent, Message, Bot
|
||||
from nonebot.params import CommandArg, Command
|
||||
from nonebot import on_command
|
||||
from typing import Tuple
|
||||
|
||||
from configs.config import NICKNAME, Config
|
||||
from models.ban_user import BanUser
|
||||
from models.level_user import LevelUser
|
||||
from typing import Tuple
|
||||
from utils.utils import get_message_at, is_number
|
||||
from configs.config import NICKNAME, Config
|
||||
from nonebot import on_command
|
||||
from nonebot.adapters.onebot.v11 import (Bot, GroupMessageEvent, Message,
|
||||
MessageEvent, PrivateMessageEvent)
|
||||
from nonebot.params import Command, CommandArg
|
||||
from nonebot.permission import SUPERUSER
|
||||
from .data_source import parse_ban_time, a_ban
|
||||
from services.log import logger
|
||||
from utils.utils import get_message_at, is_number
|
||||
|
||||
from .data_source import a_ban, parse_ban_time
|
||||
|
||||
__zx_plugin_name__ = "封禁Ban用户 [Admin]"
|
||||
__plugin_usage__ = """
|
||||
@@ -34,19 +36,19 @@ usage:
|
||||
示例:b了 1234567
|
||||
示例:.ban 12345567
|
||||
""".strip()
|
||||
__plugin_des__ = '你被逮捕了!丢进小黑屋!'
|
||||
__plugin_cmd__ = ['.ban [at] ?[小时] ?[分钟]', '.unban [at]', 'b了 [at] [_superuser]']
|
||||
__plugin_des__ = "你被逮捕了!丢进小黑屋!"
|
||||
__plugin_cmd__ = [".ban [at] ?[小时] ?[分钟]", ".unban [at]", "b了 [at] [_superuser]"]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = 'HibiKier'
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"admin_level": Config.get_config("ban", "BAN_LEVEL"),
|
||||
"cmd": ['.ban', '.unban', 'ban', 'unban']
|
||||
"cmd": [".ban", ".unban", "ban", "unban"],
|
||||
}
|
||||
__plugin_configs__ = {
|
||||
"BAN_LEVEL [LEVEL]": {
|
||||
"value": 5,
|
||||
"help": "ban/unban所需要的管理员权限等级",
|
||||
"default_value": 5
|
||||
"default_value": 5,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,18 +60,23 @@ ban = on_command(
|
||||
block=True,
|
||||
)
|
||||
|
||||
super_ban = on_command('b了', permission=SUPERUSER, priority=5, block=True)
|
||||
super_ban = on_command("b了", permission=SUPERUSER, priority=5, block=True)
|
||||
|
||||
|
||||
@ban.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
async def _(
|
||||
bot: Bot,
|
||||
event: GroupMessageEvent,
|
||||
cmd: Tuple[str, ...] = Command(),
|
||||
arg: Message = CommandArg(),
|
||||
):
|
||||
cmd = cmd[0]
|
||||
result = ""
|
||||
qq = get_message_at(event.json())
|
||||
if qq:
|
||||
qq = qq[0]
|
||||
user_name = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
|
||||
user_name = user_name['card'] or user_name['nickname']
|
||||
user_name = user_name["card"] or user_name["nickname"]
|
||||
msg = arg.extract_plain_text().strip()
|
||||
time = parse_ban_time(msg)
|
||||
if isinstance(time, str):
|
||||
@@ -108,49 +115,58 @@ async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command()
|
||||
|
||||
|
||||
@ban.handle()
|
||||
async def _(bot: Bot, event: PrivateMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
async def _(
|
||||
bot: Bot,
|
||||
event: PrivateMessageEvent,
|
||||
cmd: Tuple[str, ...] = Command(),
|
||||
arg: Message = CommandArg(),
|
||||
):
|
||||
cmd = cmd[0]
|
||||
msg = arg.extract_plain_text().strip()
|
||||
if msg:
|
||||
if str(event.user_id) in bot.config.superusers:
|
||||
if is_number(arg.extract_plain_text().strip().split()[0]):
|
||||
qq = int(msg[0])
|
||||
msg = msg[1:]
|
||||
msg_splt = msg.split()
|
||||
if is_number(msg_splt[0]):
|
||||
|
||||
qq = int(msg_splt[0])
|
||||
msg = msg_splt[1:]
|
||||
if cmd in [".ban", "/ban"]:
|
||||
time = parse_ban_time(msg)
|
||||
time = parse_ban_time(" ".join(msg))
|
||||
if isinstance(time, str):
|
||||
await ban.finish(time)
|
||||
result = await a_ban(qq, time, str(qq), event, 9)
|
||||
else:
|
||||
if await BanUser.unban(qq):
|
||||
logger.info(
|
||||
f"USER {event.user_id} 将 USER {qq} 解禁"
|
||||
)
|
||||
logger.info(f"USER {event.user_id} 将 USER {qq} 解禁")
|
||||
result = f"已经把 {qq} 从黑名单中删除了!"
|
||||
else:
|
||||
result = f"{qq} 不在黑名单!"
|
||||
await ban.send(result)
|
||||
else:
|
||||
await ban.finish('qq号必须是数字!\n格式:.ban [qq] [hour]? [minute]?', at_sender=True)
|
||||
await ban.finish(
|
||||
"qq号必须是数字!\n格式:.ban [qq] [hour]? [minute]?", at_sender=True
|
||||
)
|
||||
|
||||
|
||||
@super_ban.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
user_name = ""
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
qq = get_message_at(event.json())
|
||||
if qq:
|
||||
qq = qq[0]
|
||||
user = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
|
||||
user_name = user["card"] or user["nickname"]
|
||||
else:
|
||||
qq = arg.extract_plain_text().strip()
|
||||
if not is_number(qq):
|
||||
await super_ban.finish("对象qq必须为纯数字...")
|
||||
qq = [qq]
|
||||
qq = int(qq)
|
||||
user_name = qq
|
||||
if qq:
|
||||
qq = qq[0]
|
||||
user = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
|
||||
user_name = user['card'] or user['nickname']
|
||||
if not await BanUser.ban(qq, 10, 99999999):
|
||||
await BanUser.unban(qq)
|
||||
await BanUser.ban(qq, 10, 99999999)
|
||||
await ban.send(f"已将 {user_name} 拉入黑名单!")
|
||||
else:
|
||||
await super_ban.send('需要添加被super ban的对象,可以使用at或者指定qq..')
|
||||
|
||||
await super_ban.send("需要添加被super ban的对象,可以使用at或者指定qq..")
|
||||
|
||||
@@ -25,7 +25,9 @@ def parse_ban_time(msg: str) -> Union[int, str]:
|
||||
return int(msg[0]) * 60 * 60 + int(msg[1]) * 60
|
||||
|
||||
|
||||
async def a_ban(qq: int, time: int, user_name: str, event: MessageEvent, ban_level: int = None) -> str:
|
||||
async def a_ban(
|
||||
qq: int, time: int, user_name: str, event: MessageEvent, ban_level: int = None
|
||||
) -> str:
|
||||
"""
|
||||
ban
|
||||
:param qq: qq
|
||||
@@ -38,7 +40,8 @@ async def a_ban(qq: int, time: int, user_name: str, event: MessageEvent, ban_lev
|
||||
ban_level = await LevelUser.get_user_level(event.user_id, event.group_id)
|
||||
if await BanUser.ban(qq, ban_level, time):
|
||||
logger.info(
|
||||
f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 封禁 时长 {time / 60} 分钟"
|
||||
f"USER {event.user_id} GROUP"
|
||||
f" {event.group_id if isinstance(event, GroupMessageEvent) else ''} 将 USER {qq} 封禁 时长 {time / 60} 分钟"
|
||||
)
|
||||
result = f"已经将 {user_name} 加入{NICKNAME}的黑名单了!"
|
||||
if time != -1:
|
||||
@@ -57,13 +60,3 @@ async def a_ban(qq: int, time: int, user_name: str, event: MessageEvent, ban_lev
|
||||
time += " 分钟"
|
||||
result = f"{user_name} 已在黑名单!预计 {time}后解封"
|
||||
return result
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import nonebot
|
||||
|
||||
nonebot.load_plugins("basic_plugins/chat_history")
|
||||
@@ -0,0 +1,6 @@
|
||||
from nonebot.adapters.onebot.v11 import Event, MessageEvent
|
||||
from configs.config import Config
|
||||
|
||||
|
||||
def rule(event: Event) -> bool:
|
||||
return Config.get_config("chat_history", "FLAG") and isinstance(event, MessageEvent)
|
||||
@@ -0,0 +1,39 @@
|
||||
from configs.config import Config
|
||||
from models.chat_history import ChatHistory
|
||||
from nonebot import on_message
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
|
||||
from utils.utils import get_message_text
|
||||
|
||||
from ._rule import rule
|
||||
|
||||
__zx_plugin_name__ = "消息存储 [Hidden]"
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
"chat_history", "FLAG", True, help_="是否开启消息自从存储", name="消息存储", default_value=True
|
||||
)
|
||||
|
||||
|
||||
chat_history = on_message(rule=rule, priority=1, block=False)
|
||||
|
||||
|
||||
@chat_history.handle()
|
||||
async def _(event: MessageEvent):
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
await ChatHistory.add_chat_msg(
|
||||
event.user_id, event.group_id, str(event.get_message()), get_message_text(event.json())
|
||||
)
|
||||
else:
|
||||
await ChatHistory.add_chat_msg(event.user_id, None, str(event.get_message()), get_message_text(event.json()))
|
||||
|
||||
|
||||
# @test.handle()
|
||||
# async def _(event: MessageEvent):
|
||||
# print(await ChatHistory.get_user_msg(event.user_id, "private"))
|
||||
# print(await ChatHistory.get_user_msg_count(event.user_id, "private"))
|
||||
# print(await ChatHistory.get_user_msg(event.user_id, "group"))
|
||||
# print(await ChatHistory.get_user_msg_count(event.user_id, "group"))
|
||||
# print(await ChatHistory.get_group_msg(event.group_id))
|
||||
# print(await ChatHistory.get_group_msg_count(event.group_id))
|
||||
@@ -0,0 +1,108 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytz
|
||||
from models.chat_history import ChatHistory
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from nonebot import on_regex
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from nonebot.params import RegexGroup
|
||||
from utils.image_utils import BuildImage, text2image
|
||||
from utils.utils import is_number
|
||||
from utils.message_builder import image
|
||||
from typing import Tuple, Any
|
||||
|
||||
|
||||
__zx_plugin_name__ = "消息统计"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
发言记录统计
|
||||
regex:(周|月)?消息排行(des|DES)?(n=[0-9]{1,2})?
|
||||
指令:
|
||||
消息统计?(des)?(n=?)
|
||||
周消息统计?(des)?(n=?)
|
||||
月消息统计?(des)?(n=?)
|
||||
示例:
|
||||
消息统计
|
||||
消息统计des
|
||||
消息统计DESn=15
|
||||
消息统计n=15
|
||||
""".strip()
|
||||
__plugin_des__ = "发言消息排行"
|
||||
__plugin_cmd__ = [
|
||||
"消息统计",
|
||||
"周消息统计",
|
||||
"月消息统计"
|
||||
]
|
||||
__plugin_type__ = ("数据统计", 1)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"cmd": ["消息统计"],
|
||||
}
|
||||
|
||||
|
||||
msg_handler = on_regex(r"^(周|月)?消息统计(des|DES)?(n=[0-9]{1,2})?$", priority=5, block=True)
|
||||
|
||||
|
||||
@msg_handler.handle()
|
||||
async def _(event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
gid = event.group_id
|
||||
date_scope = None
|
||||
date, order, num = reg_group
|
||||
num = num.split("=")[-1] if num else 10
|
||||
if num and is_number(num) and 10 < int(num) < 50:
|
||||
num = int(num)
|
||||
if date in ["周"]:
|
||||
date_scope = (datetime.now() - timedelta(days=7), datetime.now())
|
||||
elif date in ["月"]:
|
||||
date_scope = (datetime.now() - timedelta(days=30), datetime.now())
|
||||
if rank_data := await ChatHistory.get_group_msg_rank(
|
||||
gid, num, order or "DESC", date_scope
|
||||
):
|
||||
name = "昵称:\n\n"
|
||||
num_str = "发言次数:\n\n"
|
||||
idx = 1
|
||||
for uid, num in rank_data:
|
||||
try:
|
||||
user_name = (await GroupInfoUser.get_member_info(uid, gid)).user_name
|
||||
except AttributeError:
|
||||
user_name = uid
|
||||
name += f"\t{idx}.{user_name} \n\n"
|
||||
num_str += f"\t{num}\n\n"
|
||||
idx += 1
|
||||
name_img = await text2image(name.strip(), padding=10, color="#f9f6f2")
|
||||
num_img = await text2image(num_str.strip(), padding=10, color="#f9f6f2")
|
||||
if not date_scope:
|
||||
if date_scope := await ChatHistory.get_group_first_msg_datetime(gid):
|
||||
date_scope = date_scope.astimezone(
|
||||
pytz.timezone("Asia/Shanghai")
|
||||
).replace(microsecond=0)
|
||||
else:
|
||||
date_scope = datetime.now().replace(microsecond=0)
|
||||
date_str = f"日期:{date_scope} - 至今"
|
||||
else:
|
||||
date_str = f"日期:{date_scope[0].replace(microsecond=0)} - {date_scope[1].replace(microsecond=0)}"
|
||||
date_w = BuildImage(0, 0, font_size=15).getsize(date_str)[0]
|
||||
img_w = date_w if date_w > name_img.w + num_img.w else name_img.w + num_img.w
|
||||
A = BuildImage(
|
||||
img_w + 15,
|
||||
num_img.h + 30,
|
||||
color="#f9f6f2",
|
||||
font="CJGaoDeGuo.otf",
|
||||
font_size=15,
|
||||
)
|
||||
await A.atext((10, 10), date_str)
|
||||
await A.apaste(name_img, (0, 30))
|
||||
await A.apaste(num_img, (name_img.w, 30))
|
||||
await msg_handler.send(image(b64=A.pic2bs4()))
|
||||
|
||||
|
||||
# @test.handle()
|
||||
# async def _(event: MessageEvent):
|
||||
# print(await ChatHistory.get_user_msg(event.user_id, "private"))
|
||||
# print(await ChatHistory.get_user_msg_count(event.user_id, "private"))
|
||||
# print(await ChatHistory.get_user_msg(event.user_id, "group"))
|
||||
# print(await ChatHistory.get_user_msg_count(event.user_id, "group"))
|
||||
# print(await ChatHistory.get_group_msg(event.group_id))
|
||||
# print(await ChatHistory.get_group_msg_count(event.group_id))
|
||||
@@ -1,5 +1,6 @@
|
||||
from nonebot import on_notice, on_request
|
||||
from configs.path_config import IMAGE_PATH, DATA_PATH
|
||||
from models.level_user import LevelUser
|
||||
from utils.message_builder import image
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from datetime import datetime
|
||||
@@ -96,6 +97,23 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
|
||||
for plugin in data.keys():
|
||||
if not data[plugin]["default_status"]:
|
||||
group_manager.block_plugin(plugin, event.group_id)
|
||||
# 即刻刷新权限
|
||||
for user_info in await bot.get_group_member_list(group_id=event.group_id):
|
||||
if user_info["role"] in [
|
||||
"owner",
|
||||
"admin",
|
||||
] and not await LevelUser.is_group_flag(
|
||||
user_info["user_id"], event.group_id
|
||||
):
|
||||
await LevelUser.set_level(
|
||||
user_info["user_id"],
|
||||
user_info["group_id"],
|
||||
Config.get_config("admin_bot_manage", "ADMIN_DEFAULT_AUTH"),
|
||||
)
|
||||
if str(user_info["user_id"]) in bot.config.superusers:
|
||||
await LevelUser.set_level(
|
||||
user_info["user_id"], user_info["group_id"], 9
|
||||
)
|
||||
else:
|
||||
join_time = datetime.now()
|
||||
user_info = await bot.get_group_member_info(
|
||||
@@ -128,9 +146,7 @@ async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
|
||||
msg = msg.replace("[at]", "")
|
||||
at_flag = True
|
||||
if (DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg").exists():
|
||||
img = image(
|
||||
DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg"
|
||||
)
|
||||
img = image(DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg")
|
||||
if msg or img:
|
||||
msg = msg.strip() + img
|
||||
msg = "\n" + msg if at_flag else msg
|
||||
|
||||
@@ -56,6 +56,9 @@ def _create_help_img(
|
||||
for matcher in _matchers:
|
||||
plugin_name = None
|
||||
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
|
||||
if not _plugin:
|
||||
logger.warning(f"获取 功能:{matcher.plugin_name} 失败...")
|
||||
continue
|
||||
_module = _plugin.module
|
||||
try:
|
||||
plugin_name = _module.__getattribute__("__zx_plugin_name__")
|
||||
@@ -277,7 +280,7 @@ def _create_help_img(
|
||||
0,
|
||||
plain_text=msg,
|
||||
font_size=24,
|
||||
font="yuanshen.ttf",
|
||||
font="HYWenHei-85W.ttf",
|
||||
)
|
||||
B.paste(text, (w, h), True)
|
||||
h += 50
|
||||
@@ -289,7 +292,7 @@ def _create_help_img(
|
||||
0,
|
||||
plain_text="注: 红字代表功能被群管理员禁用,红线代表功能正在维护",
|
||||
font_size=24,
|
||||
font="yuanshen.ttf",
|
||||
font="HYWenHei-85W.ttf",
|
||||
font_color=(231, 74, 57)
|
||||
),
|
||||
(300, 10),
|
||||
|
||||
@@ -2,6 +2,10 @@ from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent
|
||||
from utils.manager import plugins2block_manager, StaticData
|
||||
import time
|
||||
|
||||
ignore_rst_module = ["ai", "poke", "dialogue"]
|
||||
|
||||
other_limit_plugins = ["poke"]
|
||||
|
||||
|
||||
class StatusMessageManager(StaticData):
|
||||
|
||||
|
||||
@@ -13,7 +13,12 @@ from utils.manager import (
|
||||
plugins2block_manager,
|
||||
plugins2count_manager,
|
||||
)
|
||||
from ._utils import set_block_limit_false, status_message_manager
|
||||
from ._utils import (
|
||||
set_block_limit_false,
|
||||
status_message_manager,
|
||||
ignore_rst_module,
|
||||
other_limit_plugins,
|
||||
)
|
||||
from nonebot.typing import T_State
|
||||
from typing import Optional
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
@@ -37,12 +42,10 @@ _flmt_g = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
_flmt_s = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
_flmt_c = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
|
||||
|
||||
ignore_rst_module = ["ai", "poke", "dialogue"]
|
||||
|
||||
|
||||
# 权限检测
|
||||
@run_preprocessor
|
||||
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
|
||||
module = matcher.plugin_name
|
||||
plugins2info_dict = plugins2settings_manager.get_data()
|
||||
# 功能的金币检测 #######################################
|
||||
@@ -64,7 +67,7 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
|
||||
try:
|
||||
if (
|
||||
(not isinstance(event, MessageEvent) and module != "poke")
|
||||
(not isinstance(event, MessageEvent) and module not in other_limit_plugins)
|
||||
or await BanUser.is_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
) or (
|
||||
@@ -88,7 +91,7 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
except AttributeError:
|
||||
pass
|
||||
# 群黑名单检测 群总开关检测
|
||||
if isinstance(event, GroupMessageEvent) or matcher.plugin_name == "poke":
|
||||
if isinstance(event, GroupMessageEvent) or matcher.plugin_name == other_limit_plugins:
|
||||
try:
|
||||
if (
|
||||
group_manager.get_group_level(event.group_id) < 0
|
||||
@@ -103,7 +106,7 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
raise IgnoredException("功能总开关关闭状态")
|
||||
except AttributeError:
|
||||
pass
|
||||
if module in admin_manager.keys() and matcher.priority not in [1, 9]:
|
||||
if module in admin_manager.keys() and matcher.priority not in [1, 999]:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
# 个人权限
|
||||
if (
|
||||
@@ -143,11 +146,9 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
if event.is_tome():
|
||||
status_message_manager.add(event.user_id)
|
||||
raise IgnoredException("权限不足")
|
||||
if module in plugins2info_dict.keys() and matcher.priority not in [1, 9]:
|
||||
if module in plugins2info_dict.keys() and matcher.priority not in [1, 999]:
|
||||
# 戳一戳单独判断
|
||||
if isinstance(event, GroupMessageEvent) or (
|
||||
isinstance(event, PokeNotifyEvent) and event.group_id
|
||||
):
|
||||
if isinstance(event, GroupMessageEvent) or isinstance(event, PokeNotifyEvent) or matcher.plugin_name in other_limit_plugins:
|
||||
if status_message_manager.get(event.group_id) is None:
|
||||
status_message_manager.delete(event.group_id)
|
||||
if plugins2info_dict[module]["level"] > group_manager.get_group_level(
|
||||
|
||||
@@ -4,13 +4,16 @@ from nonebot.adapters.onebot.v11.exception import ActionFailed
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
Bot,
|
||||
Event,
|
||||
MessageEvent,
|
||||
PokeNotifyEvent,
|
||||
GroupMessageEvent,
|
||||
)
|
||||
from configs.config import Config
|
||||
from models.ban_user import BanUser
|
||||
from utils.utils import is_number, static_flmt, FreqLimiter
|
||||
from utils.message_builder import at
|
||||
from ._utils import ignore_rst_module, other_limit_plugins
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
@@ -25,18 +28,19 @@ _flmt = FreqLimiter(300)
|
||||
|
||||
# 检查是否被ban
|
||||
@run_preprocessor
|
||||
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
try:
|
||||
if (
|
||||
await BanUser.is_super_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
):
|
||||
raise IgnoredException("用户处于超级黑名单中")
|
||||
except AttributeError:
|
||||
pass
|
||||
if not isinstance(event, MessageEvent):
|
||||
return
|
||||
if matcher.type == "message" and matcher.priority not in [1, 9]:
|
||||
async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
|
||||
if (
|
||||
(isinstance(event, MessageEvent) or isinstance(event, PokeNotifyEvent))
|
||||
and matcher.priority not in [1, 999]
|
||||
) or matcher.plugin_name in other_limit_plugins:
|
||||
try:
|
||||
if (
|
||||
await BanUser.is_super_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
):
|
||||
raise IgnoredException("用户处于超级黑名单中")
|
||||
except AttributeError:
|
||||
pass
|
||||
if (
|
||||
await BanUser.is_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
@@ -54,10 +58,14 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
if not static_flmt.check(event.user_id):
|
||||
raise IgnoredException("用户处于黑名单中")
|
||||
static_flmt.start_cd(event.user_id)
|
||||
if matcher.priority != 9:
|
||||
if matcher.priority != 999:
|
||||
try:
|
||||
ban_result = Config.get_config("hook", "BAN_RESULT")
|
||||
if ban_result and _flmt.check(event.user_id):
|
||||
if (
|
||||
ban_result
|
||||
and _flmt.check(event.user_id)
|
||||
and matcher.plugin_name not in ignore_rst_module
|
||||
):
|
||||
_flmt.start_cd(event.user_id)
|
||||
await bot.send_group_msg(
|
||||
group_id=event.group_id,
|
||||
@@ -71,10 +79,10 @@ async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
|
||||
if not static_flmt.check(event.user_id):
|
||||
raise IgnoredException("用户处于黑名单中")
|
||||
static_flmt.start_cd(event.user_id)
|
||||
if matcher.priority != 9:
|
||||
if matcher.priority != 999:
|
||||
try:
|
||||
ban_result = Config.get_config("hook", "BAN_RESULT")
|
||||
if ban_result:
|
||||
if ban_result and matcher.plugin_name not in ignore_rst_module:
|
||||
await bot.send_private_msg(
|
||||
user_id=event.user_id,
|
||||
message=at(event.user_id)
|
||||
|
||||
@@ -25,7 +25,7 @@ _blmt = BanCheckLimiter(
|
||||
async def _(matcher: Matcher, bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if not isinstance(event, MessageEvent):
|
||||
return
|
||||
if matcher.type == "message" and matcher.priority not in [1, 9]:
|
||||
if matcher.type == "message" and matcher.priority not in [1, 999]:
|
||||
if state["_prefix"]["raw_command"]:
|
||||
if _blmt.check(f'{event.user_id}{state["_prefix"]["raw_command"]}'):
|
||||
if await BanUser.ban(
|
||||
|
||||
@@ -10,7 +10,7 @@ async def handle_api_call(bot: Bot, api: str, data: Dict[str, Any]):
|
||||
r = None
|
||||
if (
|
||||
(
|
||||
(api == "send_msg" and data["message_type"] == "group")
|
||||
(api == "send_msg" and data.get("message_type") == "group")
|
||||
or api == "send_group_msg"
|
||||
)
|
||||
and (
|
||||
|
||||
@@ -20,26 +20,36 @@ def init_none_plugin_count_manager():
|
||||
"""
|
||||
清除已删除插件数据
|
||||
"""
|
||||
modules = [x.module for x in get_matchers()]
|
||||
for module in none_plugin_count_manager.keys():
|
||||
if module not in modules:
|
||||
none_plugin_count_manager.add_count(module)
|
||||
else:
|
||||
none_plugin_count_manager.reset(module)
|
||||
if none_plugin_count_manager.check(module):
|
||||
modules = [x.plugin_name for x in get_matchers()]
|
||||
plugins_manager_list = list(plugins_manager.keys())
|
||||
for module in plugins_manager_list:
|
||||
if module not in modules or none_plugin_count_manager.check(module):
|
||||
try:
|
||||
plugin_name = plugins_manager.get(module)["plugin_name"]
|
||||
except (AttributeError, KeyError):
|
||||
plugin_name = ""
|
||||
try:
|
||||
plugins2settings_manager.delete(module)
|
||||
plugins2count_manager.delete(module)
|
||||
plugins2cd_manager.delete(module)
|
||||
plugins2block_manager.delete(module)
|
||||
plugins_manager.delete(module)
|
||||
resources_manager.remove_resource(module)
|
||||
logger.info(f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据...")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据失败...{type(e)}:{e}"
|
||||
)
|
||||
if none_plugin_count_manager.check(module):
|
||||
try:
|
||||
plugins2settings_manager.delete(module)
|
||||
plugins2settings_manager.save()
|
||||
plugins2count_manager.delete(module)
|
||||
plugins2count_manager.save()
|
||||
plugins2cd_manager.delete(module)
|
||||
plugins2cd_manager.save()
|
||||
plugins2block_manager.delete(module)
|
||||
plugins2block_manager.save()
|
||||
plugins_manager.delete(module)
|
||||
plugins_manager.save()
|
||||
resources_manager.remove_resource(module)
|
||||
none_plugin_count_manager.delete(module)
|
||||
logger.info(f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据...")
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"{module}:{plugin_name} 插件疑似已删除,清除对应插件数据失败...{type(e)}:{e}")
|
||||
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()
|
||||
|
||||
@@ -74,7 +74,7 @@ def init_plugins_settings(data_path: str):
|
||||
if plugin_settings.get('cost_gold') is None:
|
||||
plugin_settings['cost_gold'] = 0
|
||||
if (
|
||||
plugin_settings["cmd"] is not None
|
||||
plugin_settings.get("cmd") is not None
|
||||
and plugin_name not in plugin_settings["cmd"]
|
||||
):
|
||||
plugin_settings["cmd"].append(plugin_name)
|
||||
|
||||
@@ -25,7 +25,7 @@ __plugin_configs__ = {
|
||||
|
||||
friend_req = on_request(priority=5, block=True)
|
||||
group_req = on_request(priority=5, block=True)
|
||||
x = on_message(priority=9, block=False)
|
||||
x = on_message(priority=999, block=False)
|
||||
|
||||
exists_data = {"private": {}, "group": {}}
|
||||
|
||||
|
||||
@@ -108,6 +108,10 @@ async def _():
|
||||
"ALTER TABLE genshin ADD bind_group Integer;",
|
||||
"genshin"
|
||||
), # 新增原神群号绑定字段
|
||||
(
|
||||
"ALTER TABLE chat_history ADD plain_text Text;",
|
||||
"chat_history"
|
||||
), # 新增纯文本
|
||||
]
|
||||
for sql in sql_str:
|
||||
try:
|
||||
|
||||
@@ -7,11 +7,13 @@ from typing import Optional, Union
|
||||
from configs.config import Config
|
||||
from nonebot import Driver
|
||||
from nonebot.plugin import require
|
||||
from utils.decorator.shop import shop_register
|
||||
import nonebot
|
||||
import time
|
||||
|
||||
driver: Driver = nonebot.get_driver()
|
||||
|
||||
|
||||
use = require("use")
|
||||
|
||||
|
||||
@@ -20,24 +22,26 @@ async def init_default_shop_goods():
|
||||
"""
|
||||
导入内置的三个商品
|
||||
"""
|
||||
async def sign_card(**kwargs):
|
||||
user_id = kwargs['user_id']
|
||||
group_id = kwargs['group_id']
|
||||
prob = kwargs["prob"]
|
||||
|
||||
@shop_register(
|
||||
name=("好感度双倍加持卡Ⅰ", "好感度双倍加持卡Ⅱ", "好感度双倍加持卡Ⅲ"),
|
||||
price=(30, 150, 250),
|
||||
des=(
|
||||
"下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)",
|
||||
"下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)",
|
||||
"下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)",
|
||||
),
|
||||
load_status=Config.get_config("shop", "IMPORT_DEFAULT_SHOP_GOODS"),
|
||||
** {"好感度双倍加持卡Ⅰ_prob": 0.1, "好感度双倍加持卡Ⅱ_prob": 0.2, "好感度双倍加持卡Ⅲ_prob": 0.3},
|
||||
)
|
||||
async def sign_card(user_id: int, group_id: int, prob: float):
|
||||
user = await SignGroupUser.ensure(user_id, group_id)
|
||||
await user.update(add_probability=prob).apply()
|
||||
|
||||
if Config.get_config("shop", "IMPORT_DEFAULT_SHOP_GOODS"):
|
||||
await register_goods(
|
||||
"好感度双倍加持卡Ⅰ", 30, "下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)"
|
||||
)
|
||||
use.register_use("好感度双倍加持卡Ⅰ", sign_card, **{"prob": 0.1})
|
||||
await register_goods("好感度双倍加持卡Ⅱ", 150, "下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)")
|
||||
use.register_use("好感度双倍加持卡Ⅱ", sign_card, **{"prob": 0.2})
|
||||
await register_goods(
|
||||
"好感度双倍加持卡Ⅲ", 250, "下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)"
|
||||
)
|
||||
use.register_use("好感度双倍加持卡Ⅲ", sign_card, **{"prob": 0.3})
|
||||
|
||||
@driver.on_bot_connect
|
||||
async def _():
|
||||
await shop_register.load_register()
|
||||
|
||||
|
||||
# 创建商店界面
|
||||
@@ -59,9 +63,7 @@ async def create_shop_help() -> str:
|
||||
A = BuildImage(1000, h, color="#f9f6f2")
|
||||
current_h = 0
|
||||
for goods in _list:
|
||||
bk = BuildImage(
|
||||
700, 80, font_size=15, color="#f9f6f2", font="CJGaoDeGuo.otf"
|
||||
)
|
||||
bk = BuildImage(700, 80, font_size=15, color="#f9f6f2", font="CJGaoDeGuo.otf")
|
||||
goods_image = BuildImage(
|
||||
600, 80, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
|
||||
)
|
||||
@@ -92,10 +94,18 @@ async def create_shop_help() -> str:
|
||||
await bk.apaste(goods_image, alpha=True)
|
||||
# 添加限时图标和时间
|
||||
if goods.goods_limit_time > 0:
|
||||
_limit_time_logo = BuildImage(40, 40, background=f"{IMAGE_PATH}/other/time.png")
|
||||
_limit_time_logo = BuildImage(
|
||||
40, 40, background=f"{IMAGE_PATH}/other/time.png"
|
||||
)
|
||||
await bk.apaste(_limit_time_logo, (600, 0), True)
|
||||
await bk.apaste(BuildImage(0, 0, plain_text="限时!", font_size=23, font="CJGaoDeGuo.otf"), (640, 10), True)
|
||||
limit_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(goods.goods_limit_time)).split()
|
||||
await bk.apaste(
|
||||
BuildImage(0, 0, plain_text="限时!", font_size=23, font="CJGaoDeGuo.otf"),
|
||||
(640, 10),
|
||||
True,
|
||||
)
|
||||
limit_time = time.strftime(
|
||||
"%Y-%m-%d %H:%M", time.localtime(goods.goods_limit_time)
|
||||
).split()
|
||||
y_m_d = limit_time[0]
|
||||
_h_m = limit_time[1].split(":")
|
||||
h_m = _h_m[0] + "时 " + _h_m[1] + "分"
|
||||
@@ -125,13 +135,12 @@ async def create_shop_help() -> str:
|
||||
|
||||
|
||||
async def register_goods(
|
||||
name: str,
|
||||
price: int,
|
||||
des: str,
|
||||
discount: Optional[float] = 1,
|
||||
limit_time: Optional[int] = 0,
|
||||
**kwargs,
|
||||
):
|
||||
name: str,
|
||||
price: int,
|
||||
des: str,
|
||||
discount: Optional[float] = 1,
|
||||
limit_time: Optional[int] = 0,
|
||||
) -> bool:
|
||||
"""
|
||||
添加商品
|
||||
例如: 折扣:可选参数↓ 限时时间:可选,单位为小时
|
||||
@@ -142,21 +151,20 @@ async def register_goods(
|
||||
:param des: 商品简介
|
||||
:param discount: 商品折扣
|
||||
:param limit_time: 商品限时销售时间,单位为小时
|
||||
:param kwargs: kwargs
|
||||
:return: 是否添加成功
|
||||
"""
|
||||
if kwargs:
|
||||
name = kwargs.get("name")
|
||||
price = kwargs.get("price")
|
||||
des = kwargs.get("des")
|
||||
discount = kwargs.get("discount")
|
||||
limit_time = kwargs.get("time_limit")
|
||||
limit_time = float(limit_time) if limit_time else limit_time
|
||||
discount = discount if discount is None else 1
|
||||
limit_time = int(time.time() + limit_time * 60 * 60) if limit_time is not None and limit_time != 0 else 0
|
||||
return await GoodsInfo.add_goods(
|
||||
name, int(price), des, float(discount), limit_time
|
||||
)
|
||||
if not await GoodsInfo.get_goods_info(name):
|
||||
limit_time = float(limit_time) if limit_time else limit_time
|
||||
discount = discount if discount is not None else 1
|
||||
limit_time = (
|
||||
int(time.time() + limit_time * 60 * 60)
|
||||
if limit_time is not None and limit_time != 0
|
||||
else 0
|
||||
)
|
||||
return await GoodsInfo.add_goods(
|
||||
name, int(price), des, float(discount), limit_time
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
# 删除商品
|
||||
@@ -230,7 +238,11 @@ async def update_goods(**kwargs) -> "str, str, int":
|
||||
int(price),
|
||||
des,
|
||||
float(discount),
|
||||
int(time.time() + limit_time * 60 * 60 if limit_time != 0 and new_time else 0),
|
||||
int(
|
||||
time.time() + limit_time * 60 * 60
|
||||
if limit_time != 0 and new_time
|
||||
else 0
|
||||
),
|
||||
),
|
||||
name,
|
||||
tmp[:-1],
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from pydantic import create_model
|
||||
from utils.models import ShopParam
|
||||
from typing import Optional, Union
|
||||
from types import MappingProxyType
|
||||
import inspect
|
||||
import asyncio
|
||||
|
||||
|
||||
@@ -30,24 +34,52 @@ class GoodsUseFuncManager:
|
||||
:param goods_name: 商品名称
|
||||
"""
|
||||
if self.exists(goods_name):
|
||||
return self._data[goods_name]["kwargs"]["_max_num_limit"]
|
||||
return self._data[goods_name]["kwargs"]["max_num_limit"]
|
||||
return 1
|
||||
|
||||
async def use(self, **kwargs) -> Optional[Union[str, MessageSegment]]:
|
||||
async def use(
|
||||
self, param: ShopParam, **kwargs
|
||||
) -> Optional[Union[str, MessageSegment]]:
|
||||
"""
|
||||
使用道具
|
||||
:param param: BaseModel
|
||||
:param kwargs: kwargs
|
||||
"""
|
||||
goods_name = kwargs.get("goods_name")
|
||||
def parse_args(args_: MappingProxyType):
|
||||
param_list_ = []
|
||||
_bot = param.bot
|
||||
param.bot = None
|
||||
param_json = param.dict()
|
||||
param_json["bot"] = _bot
|
||||
for par in args_.keys():
|
||||
if par in ["shop_param"]:
|
||||
param_list_.append(param)
|
||||
elif par not in ["args", "kwargs"]:
|
||||
param_list_.append(param_json.get(par))
|
||||
if kwargs.get(par) is not None:
|
||||
del kwargs[par]
|
||||
return param_list_
|
||||
goods_name = param.goods_name
|
||||
if self.exists(goods_name):
|
||||
if asyncio.iscoroutinefunction(self._data[goods_name]["func"]):
|
||||
return await self._data[goods_name]["func"](
|
||||
**kwargs,
|
||||
)
|
||||
args = inspect.signature(self._data[goods_name]["func"]).parameters
|
||||
if args and list(args.keys())[0] != "kwargs":
|
||||
if asyncio.iscoroutinefunction(self._data[goods_name]["func"]):
|
||||
return await self._data[goods_name]["func"](
|
||||
*parse_args(args)
|
||||
)
|
||||
else:
|
||||
return self._data[goods_name]["func"](
|
||||
*parse_args(args)
|
||||
)
|
||||
else:
|
||||
return self._data[goods_name]["func"](
|
||||
**kwargs,
|
||||
)
|
||||
if asyncio.iscoroutinefunction(self._data[goods_name]["func"]):
|
||||
return await self._data[goods_name]["func"](
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
return self._data[goods_name]["func"](
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def check_send_success_message(self, goods_name: str) -> bool:
|
||||
"""
|
||||
@@ -67,6 +99,18 @@ class GoodsUseFuncManager:
|
||||
return self._data[goods_name]["kwargs"]
|
||||
return {}
|
||||
|
||||
def init_model(self, goods_name: str, bot: Bot, event: GroupMessageEvent, num: int):
|
||||
return self._data[goods_name]["model"](
|
||||
**{
|
||||
"goods_name": goods_name,
|
||||
"bot": bot,
|
||||
"event": event,
|
||||
"user_id": event.user_id,
|
||||
"group_id": event.group_id,
|
||||
"num": num,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
func_manager = GoodsUseFuncManager()
|
||||
|
||||
@@ -83,22 +127,23 @@ async def effect(
|
||||
:return: 使用是否成功
|
||||
"""
|
||||
# 优先使用注册的商品插件
|
||||
try:
|
||||
if func_manager.exists(goods_name):
|
||||
_kwargs = func_manager.get_kwargs(goods_name)
|
||||
return await func_manager.use(
|
||||
**{
|
||||
**_kwargs,
|
||||
"_bot": bot,
|
||||
"event": event,
|
||||
"group_id": event.group_id,
|
||||
"user_id": event.user_id,
|
||||
"num": num,
|
||||
"goods_name": goods_name,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"use 商品生效函数effect 发生错误 {type(e)}:{e}")
|
||||
# try:
|
||||
if func_manager.exists(goods_name):
|
||||
_kwargs = func_manager.get_kwargs(goods_name)
|
||||
return await func_manager.use(
|
||||
func_manager.init_model(goods_name, bot, event, num),
|
||||
**{
|
||||
**_kwargs,
|
||||
"_bot": bot,
|
||||
"event": event,
|
||||
"group_id": event.group_id,
|
||||
"user_id": event.user_id,
|
||||
"num": num,
|
||||
"goods_name": goods_name,
|
||||
},
|
||||
)
|
||||
# except Exception as e:
|
||||
# logger.error(f"use 商品生效函数effect 发生错误 {type(e)}:{e}")
|
||||
return None
|
||||
|
||||
|
||||
@@ -112,10 +157,14 @@ def register_use(goods_name: str, func, **kwargs):
|
||||
if func_manager.exists(goods_name):
|
||||
raise ValueError("该商品使用函数已被注册!")
|
||||
# 发送使用成功信息
|
||||
if kwargs.get("send_success_msg") is None:
|
||||
kwargs["send_success_msg"] = True
|
||||
kwargs["_max_num_limit"] = (
|
||||
kwargs.get("_max_num_limit") if kwargs.get("_max_num_limit") else 1
|
||||
kwargs["send_success_msg"] = kwargs.get("send_success_msg", True)
|
||||
kwargs["max_num_limit"] = kwargs.get("max_num_limit", 1)
|
||||
func_manager.register_use(
|
||||
goods_name,
|
||||
**{
|
||||
"func": func,
|
||||
"model": create_model(f"{goods_name}_model", __base__=ShopParam, **kwargs),
|
||||
"kwargs": kwargs,
|
||||
},
|
||||
)
|
||||
func_manager.register_use(goods_name, **{"func": func, "kwargs": kwargs})
|
||||
logger.info(f"register_use 成功注册商品:{goods_name} 的使用函数")
|
||||
|
||||
@@ -82,15 +82,16 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
|
||||
if is_number(id_):
|
||||
id_ = int(id_)
|
||||
if cmd[:2] == "同意":
|
||||
if await requests_manager.approve(bot, id_, "private"):
|
||||
await friend_handle.send("同意好友请求成功..")
|
||||
else:
|
||||
await friend_handle.send("同意好友请求失败,可能是未找到此id的请求..")
|
||||
flag = await requests_manager.approve(bot, id_, "private")
|
||||
else:
|
||||
if await requests_manager.refused(bot, id_, "private"):
|
||||
await friend_handle.send("拒绝好友请求成功..")
|
||||
else:
|
||||
await friend_handle.send("拒绝好友请求失败,可能是未找到此id的请求..")
|
||||
flag = await requests_manager.refused(bot, id_, "private")
|
||||
if flag == 1:
|
||||
await friend_handle.send(f"{cmd[:2]}好友请求失败,该请求已失效..")
|
||||
requests_manager.delete_request(id_, "private")
|
||||
elif flag == 2:
|
||||
await friend_handle.send(f"{cmd[:2]}好友请求失败,未找到此id的请求..")
|
||||
else:
|
||||
await friend_handle.send(f"{cmd[:2]}好友请求成功!")
|
||||
else:
|
||||
await friend_handle.send("id必须为纯数字!")
|
||||
|
||||
@@ -99,12 +100,12 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
|
||||
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
cmd = cmd[0]
|
||||
id_ = arg.extract_plain_text().strip()
|
||||
flag = None
|
||||
if is_number(id_):
|
||||
id_ = int(id_)
|
||||
if cmd[:2] == "同意":
|
||||
rid = requests_manager.get_group_id(id_)
|
||||
if rid:
|
||||
await friend_handle.send("同意群聊请求成功..")
|
||||
if await GroupInfo.get_group_info(rid):
|
||||
await GroupInfo.set_group_flag(rid, 1)
|
||||
else:
|
||||
@@ -116,14 +117,18 @@ async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandAr
|
||||
group_info["member_count"],
|
||||
1
|
||||
)
|
||||
await requests_manager.approve(bot, id_, "group")
|
||||
flag = await requests_manager.approve(bot, id_, "group")
|
||||
else:
|
||||
await friend_handle.send("同意群聊请求失败,可能是未找到此id的请求..")
|
||||
await friend_handle.send("同意群聊请求失败,未找到此id的请求..")
|
||||
else:
|
||||
if await requests_manager.refused(bot, id_, "group"):
|
||||
await friend_handle.send("拒绝群聊请求成功..")
|
||||
else:
|
||||
await friend_handle.send("拒绝群聊请求失败,可能是未找到此id的请求..")
|
||||
flag = await requests_manager.refused(bot, id_, "group")
|
||||
if flag == 1:
|
||||
await friend_handle.send(f"{cmd[:2]}群聊请求失败,该请求已失效..")
|
||||
requests_manager.delete_request(id_, "group")
|
||||
elif flag == 2:
|
||||
await friend_handle.send(f"{cmd[:2]}群聊请求失败,未找到此id的请求..")
|
||||
else:
|
||||
await friend_handle.send(f"{cmd[:2]}群聊请求成功!")
|
||||
else:
|
||||
await friend_handle.send("id必须为纯数字!")
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
level = 0
|
||||
if not msg:
|
||||
await add_group_level.finish("用法:修改群权限 [group] [level]")
|
||||
msg = msg.split(" ")
|
||||
msg = msg.split()
|
||||
if len(msg) < 2:
|
||||
await add_group_level.finish("参数不完全..[group] [level]")
|
||||
if is_number(msg[0]) and is_number(msg[1]):
|
||||
@@ -136,7 +136,7 @@ async def _():
|
||||
@manager_group_whitelist.handle()
|
||||
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
cmd = cmd[0]
|
||||
msg = arg.extract_plain_text().strip()
|
||||
msg = arg.extract_plain_text().strip().split()
|
||||
all_group = [
|
||||
g["group_id"] for g in await bot.get_group_list()
|
||||
]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.permission import SUPERUSER
|
||||
from models.level_user import LevelUser
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message
|
||||
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, Message, GroupMessageEvent
|
||||
from utils.utils import get_message_at, is_number
|
||||
from services.log import logger
|
||||
from utils.message_builder import at
|
||||
@@ -37,41 +37,49 @@ super_cmd = on_command(
|
||||
|
||||
|
||||
@super_cmd.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
cmd = cmd[0]
|
||||
group_id = -1
|
||||
level = 0
|
||||
async def _(
|
||||
bot: Bot,
|
||||
event: MessageEvent,
|
||||
cmd: Tuple[str, ...] = Command(),
|
||||
arg: Message = CommandArg(),
|
||||
):
|
||||
group_id = event.group_id if isinstance(event, GroupMessageEvent) else -1
|
||||
level = None
|
||||
args = arg.extract_plain_text().strip().split()
|
||||
qq = get_message_at(event.json())
|
||||
flag = 2
|
||||
try:
|
||||
args = arg.extract_plain_text().strip().split()
|
||||
qq = get_message_at(event.json())
|
||||
flag = -1
|
||||
if not qq:
|
||||
if len(args) > 2:
|
||||
if is_number(args[0]) and is_number(args[1]) and is_number(args[2]):
|
||||
if qq:
|
||||
qq = qq[0]
|
||||
if cmd[0][:2] == "添加" and args and is_number(args[0]):
|
||||
level = int(args[0])
|
||||
else:
|
||||
if cmd[0][:2] == "添加":
|
||||
if (
|
||||
len(args) > 2
|
||||
and is_number(args[0])
|
||||
and is_number(args[1])
|
||||
and is_number(args[2])
|
||||
):
|
||||
qq = int(args[0])
|
||||
group_id = int(args[1])
|
||||
level = int(args[2])
|
||||
flag = 1
|
||||
else:
|
||||
await super_cmd.finish("所有参数必须是数字!", at_sender=True)
|
||||
else:
|
||||
await super_cmd.finish(
|
||||
"权限参数不完全\n\t格式:添加/删除权限 [at] [level]"
|
||||
"\n\t格式:添加/删除权限 [qq] [group_id] [level]",
|
||||
at_sender=True,
|
||||
)
|
||||
else:
|
||||
if not is_number(args[0]):
|
||||
await super_cmd.finish("所有参数必须是数字!", at_sender=True)
|
||||
level = int(args[0])
|
||||
qq = qq[0]
|
||||
group_id = event.group_id
|
||||
flag = 2
|
||||
if cmd[:2] == "添加":
|
||||
if len(args) > 1 and is_number(args[0]) and is_number(args[1]):
|
||||
qq = int(args[0])
|
||||
group_id = int(args[1])
|
||||
flag = 1
|
||||
level = -1 if cmd[0][:2] == "删除" else level
|
||||
if group_id == -1 or not level or not qq:
|
||||
raise IndexError()
|
||||
except IndexError:
|
||||
await super_cmd.finish(__plugin_usage__)
|
||||
try:
|
||||
if cmd[0][:2] == "添加":
|
||||
if await LevelUser.set_level(qq, group_id, level, 1):
|
||||
result = "添加管理成功, 权限: " + str(level)
|
||||
result = f"添加管理成功, 权限: {level}"
|
||||
else:
|
||||
result = "管理已存在, 更新权限: " + str(level)
|
||||
result = f"管理已存在, 更新权限: {level}"
|
||||
else:
|
||||
if await LevelUser.delete_level(qq, event.group_id):
|
||||
result = "删除管理成功!"
|
||||
@@ -82,7 +90,10 @@ async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command()
|
||||
elif flag == 1:
|
||||
await bot.send_group_msg(
|
||||
group_id=group_id,
|
||||
message=Message(f"{at(qq)}管理员修改了你的权限" f"\n--------\n你当前的权限等级:{level}"),
|
||||
message=Message(
|
||||
f"{at(qq)}管理员修改了你的权限"
|
||||
f"\n--------\n你当前的权限等级:{level if level != -1 else 0}"
|
||||
),
|
||||
)
|
||||
await super_cmd.send("修改成功")
|
||||
except Exception as e:
|
||||
|
||||
@@ -45,6 +45,7 @@ async def _():
|
||||
group_info["group_name"],
|
||||
group_info["max_member_count"],
|
||||
group_info["member_count"],
|
||||
1
|
||||
):
|
||||
num += 1
|
||||
logger.info(f"自动更新群组 {g} 信息成功")
|
||||
|
||||
@@ -11,14 +11,19 @@ class ConfigsManager:
|
||||
|
||||
def __init__(self, file: Path):
|
||||
self._data: dict = {}
|
||||
self._simple_data: dict = {}
|
||||
self._admin_level_data = []
|
||||
self._simple_file = Path() / "configs" / "config.yaml"
|
||||
if file:
|
||||
file.parent.mkdir(exist_ok=True, parents=True)
|
||||
self.file = file
|
||||
_yaml = YAML()
|
||||
if file.exists():
|
||||
_yaml = YAML()
|
||||
with open(file, "r", encoding="utf8") as f:
|
||||
self._data = _yaml.load(f)
|
||||
if self._simple_file.exists():
|
||||
with open(self._simple_file, "r", encoding="utf8") as f:
|
||||
self._simple_data = _yaml.load(f)
|
||||
|
||||
def add_plugin_config(
|
||||
self,
|
||||
@@ -71,6 +76,7 @@ class ConfigsManager:
|
||||
"""
|
||||
if module in self._data.keys():
|
||||
del self._data[module]
|
||||
self.save()
|
||||
|
||||
def set_config(self, module: str, key: str, value: str):
|
||||
"""
|
||||
@@ -80,8 +86,10 @@ class ConfigsManager:
|
||||
:param value: 值
|
||||
"""
|
||||
if module in self._data.keys():
|
||||
if self._data[module].get(key) is not None:
|
||||
if self._data[module].get(key) is not None and self._data[module][key] != value:
|
||||
self._data[module][key]["value"] = value
|
||||
self._simple_data[module][key] = value
|
||||
self.save()
|
||||
|
||||
def set_help(self, module: str, key: str, help_: str):
|
||||
"""
|
||||
@@ -93,6 +101,7 @@ class ConfigsManager:
|
||||
if module in self._data.keys():
|
||||
if self._data[module].get(key) is not None:
|
||||
self._data[module][key]["help"] = help_
|
||||
self.save()
|
||||
|
||||
def set_default_value(self, module: str, key: str, value: str):
|
||||
"""
|
||||
@@ -104,6 +113,7 @@ class ConfigsManager:
|
||||
if module in self._data.keys():
|
||||
if self._data[module].get(key) is not None:
|
||||
self._data[module][key]["default_value"] = value
|
||||
self.save()
|
||||
|
||||
def get_config(self, module: str, key: str, default: Optional[Any] = None) -> Optional[Any]:
|
||||
"""
|
||||
@@ -142,11 +152,17 @@ class ConfigsManager:
|
||||
if key in self._data.keys():
|
||||
return self._data[key]
|
||||
|
||||
def save(self, path: Union[str, Path] = None):
|
||||
def save(self, path: Union[str, Path] = None, save_simple_data: bool = False):
|
||||
"""
|
||||
保存数据
|
||||
:param path: 路径
|
||||
:param save_simple_data: 同时保存至config.yaml
|
||||
"""
|
||||
if save_simple_data:
|
||||
with open(self._simple_file, "w", encoding="utf8") as f:
|
||||
yaml.dump(
|
||||
self._simple_data, f, indent=2, Dumper=yaml.RoundTripDumper, allow_unicode=True
|
||||
)
|
||||
path = path if path else self.file
|
||||
with open(path, "w", encoding="utf8") as f:
|
||||
yaml.dump(
|
||||
|
||||
+1450
-155
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,214 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Literal, Optional, Tuple, Union
|
||||
|
||||
from services.db_context import db
|
||||
|
||||
|
||||
class ChatHistory(db.Model):
|
||||
__tablename__ = "chat_history"
|
||||
|
||||
id = db.Column(db.Integer(), primary_key=True)
|
||||
user_qq = db.Column(db.BigInteger(), nullable=False)
|
||||
group_id = db.Column(db.BigInteger())
|
||||
text = db.Column(db.Text())
|
||||
plain_text = db.Column(db.Text())
|
||||
create_time = db.Column(db.DateTime(timezone=True), nullable=False)
|
||||
|
||||
@classmethod
|
||||
async def add_chat_msg(cls, user_qq: int, group_id: Optional[int], text: str, plain_text: str):
|
||||
await cls.create(
|
||||
user_qq=user_qq, group_id=group_id, text=text, plain_text=plain_text, create_time=datetime.now()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def get_user_msg(
|
||||
cls,
|
||||
uid: int,
|
||||
msg_type: Optional[Literal["private", "group"]],
|
||||
days: Optional[int] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取用户消息
|
||||
参数:
|
||||
:param uid: 用户qq
|
||||
:param msg_type: 消息类型,私聊或群聊
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return await cls._get_msg(uid, None, "user", msg_type, days).gino.all()
|
||||
|
||||
@classmethod
|
||||
async def get_group_user_msg(
|
||||
cls,
|
||||
uid: int,
|
||||
gid: int,
|
||||
limit: int = 10,
|
||||
date_scope: Tuple[datetime, datetime] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取群聊指定用户聊天记录
|
||||
参数:
|
||||
:param uid: qq
|
||||
:param gid: 群号
|
||||
:param limit: 获取数量
|
||||
:param date_scope: 日期范围,默认None为全搜索
|
||||
"""
|
||||
return (
|
||||
await cls._get_msg(uid, gid, "group", days=date_scope)
|
||||
.limit(limit)
|
||||
.gino.all()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def get_group_user_msg_count(cls, uid: int, gid: int) -> Optional[int]:
|
||||
"""
|
||||
说明:
|
||||
查询群聊指定用户的聊天记录数量
|
||||
参数:
|
||||
:param uid: qq
|
||||
:param gid: 群号
|
||||
"""
|
||||
if x := await db.first(
|
||||
db.text(
|
||||
f"SELECT COUNT(id) as sum FROM public.chat_history WHERE user_qq = {uid} AND group_id = {gid}"
|
||||
)
|
||||
):
|
||||
return x[0]
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
async def get_group_msg_rank(
|
||||
cls,
|
||||
gid: int,
|
||||
limit: int = 10,
|
||||
order: str = "DESC",
|
||||
date_scope: Optional[Tuple[datetime, datetime]] = None,
|
||||
) -> Optional[Tuple[int, int]]:
|
||||
"""
|
||||
说明:
|
||||
获取排行数据
|
||||
参数:
|
||||
:param gid: 群号
|
||||
:param limit: 获取数量
|
||||
:param order: 排序类型,desc,des
|
||||
:param date_scope: 日期范围
|
||||
"""
|
||||
sql = f"SELECT user_qq, COUNT(id) as sum FROM public.chat_history WHERE group_id = {gid} "
|
||||
if date_scope:
|
||||
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}"
|
||||
return await db.all(db.text(sql))
|
||||
|
||||
@classmethod
|
||||
async def get_group_first_msg_datetime(cls, gid: int) -> Optional[datetime]:
|
||||
"""
|
||||
说明:
|
||||
获取群第一条记录消息时间
|
||||
参数:
|
||||
:param gid:
|
||||
"""
|
||||
if (
|
||||
msg := await cls.query.where(cls.group_id == gid)
|
||||
.order_by(cls.create_time)
|
||||
.gino.first()
|
||||
):
|
||||
return msg.create_time
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
async def get_user_msg_count(
|
||||
cls,
|
||||
uid: int,
|
||||
msg_type: Optional[Literal["private", "group"]],
|
||||
days: Optional[int] = None,
|
||||
) -> int:
|
||||
"""
|
||||
说明:
|
||||
获取用户消息数量
|
||||
参数:
|
||||
:param uid: 用户qq
|
||||
:param msg_type: 消息类型,私聊或群聊
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return (
|
||||
await cls._get_msg(uid, None, "user", msg_type, days, True).gino.first()
|
||||
)[0]
|
||||
|
||||
@classmethod
|
||||
async def get_group_msg(
|
||||
cls,
|
||||
gid: int,
|
||||
days: Optional[int] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取群聊消息
|
||||
参数:
|
||||
:param gid: 用户qq
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return await cls._get_msg(None, gid, "group", None, days).gino.all()
|
||||
|
||||
@classmethod
|
||||
async def get_group_msg_count(
|
||||
cls,
|
||||
gid: int,
|
||||
days: Optional[int] = None,
|
||||
) -> List["ChatHistory"]:
|
||||
"""
|
||||
说明:
|
||||
获取群聊消息数量
|
||||
参数:
|
||||
:param gid: 用户qq
|
||||
:param days: 限制日期
|
||||
"""
|
||||
return (await cls._get_msg(None, gid, "group", None, days, True).gino.first())[
|
||||
0
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def _get_msg(
|
||||
cls,
|
||||
uid: Optional[int],
|
||||
gid: Optional[int],
|
||||
type_: Literal["user", "group"],
|
||||
msg_type: Optional[Literal["private", "group"]] = None,
|
||||
days: Optional[Union[int, Tuple[datetime, datetime]]] = None,
|
||||
is_select_count: bool = False,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
获取消息查询query
|
||||
参数:
|
||||
:param uid: 用户qq
|
||||
:param gid: 群号
|
||||
:param type_: 类型,私聊或群聊
|
||||
:param msg_type: 消息类型,用户或群聊
|
||||
:param days: 限制日期
|
||||
"""
|
||||
if is_select_count:
|
||||
setattr(ChatHistory, "count", db.func.count(cls.id).label("count"))
|
||||
query = cls.select("count")
|
||||
else:
|
||||
query = cls.query
|
||||
if type_ == "user":
|
||||
query = query.where(cls.user_qq == uid)
|
||||
if msg_type == "private":
|
||||
query = query.where(cls.group_id == None)
|
||||
elif msg_type == "group":
|
||||
query = query.where(cls.group_id != None)
|
||||
else:
|
||||
query = query.where(cls.group_id == gid)
|
||||
if uid:
|
||||
query = query.where(cls.user_qq == uid)
|
||||
if days:
|
||||
if isinstance(days, int):
|
||||
query = query.where(
|
||||
cls.create_time >= datetime.now() - timedelta(days=days)
|
||||
)
|
||||
elif isinstance(days, tuple):
|
||||
query = query.where(cls.create_time >= days[0]).where(
|
||||
cls.create_time <= days[1]
|
||||
)
|
||||
return query
|
||||
@@ -114,8 +114,7 @@ class GoodsInfo(db.Model):
|
||||
参数:
|
||||
:param goods_name: 商品名称
|
||||
"""
|
||||
query = await cls.query.where(cls.goods_name == goods_name).gino.first()
|
||||
return query
|
||||
return await cls.query.where(cls.goods_name == goods_name).gino.first()
|
||||
|
||||
@classmethod
|
||||
async def get_all_goods(cls) -> List["GoodsInfo"]:
|
||||
|
||||
+15
-10
@@ -1,3 +1,5 @@
|
||||
from asyncpg import UniqueViolationError
|
||||
|
||||
from services.db_context import db
|
||||
|
||||
|
||||
@@ -44,16 +46,19 @@ class LevelUser(db.Model):
|
||||
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
|
||||
query = query.with_for_update()
|
||||
user = await query.gino.first()
|
||||
if user is None:
|
||||
await cls.create(
|
||||
user_qq=user_qq,
|
||||
group_id=group_id,
|
||||
user_level=level,
|
||||
group_flag=group_flag,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
await user.update(user_level=level, group_flag=group_flag).apply()
|
||||
try:
|
||||
if not user:
|
||||
await cls.create(
|
||||
user_qq=user_qq,
|
||||
group_id=group_id,
|
||||
user_level=level,
|
||||
group_flag=group_flag,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
await user.update(user_level=level, group_flag=group_flag).apply()
|
||||
return False
|
||||
except UniqueViolationError:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -37,7 +37,7 @@ Config.add_plugin_config(
|
||||
"alapi", "ALAPI_TOKEN", None, help_="在 https://admin.alapi.cn/user/login 登录后获取token"
|
||||
)
|
||||
|
||||
ai = on_message(rule=to_me(), priority=8)
|
||||
ai = on_message(rule=to_me(), priority=998)
|
||||
|
||||
|
||||
@ai.handle()
|
||||
@@ -76,6 +76,7 @@ async def _(bot: Bot, event: MessageEvent):
|
||||
f"问题:{msg} ---- 回答:{result}"
|
||||
)
|
||||
if result:
|
||||
result = str(result)
|
||||
for t in Config.get_config("ai", "TEXT_FILTER"):
|
||||
result = result.replace(t, "*")
|
||||
await ai.finish(Message(result))
|
||||
|
||||
+34
-30
@@ -57,7 +57,7 @@ async def get_chat_result(text: str, img_url: str, user_id: int, nickname: str)
|
||||
if random.random() < 0.2:
|
||||
if nickname.find("大人") == -1:
|
||||
nickname += "大~人~"
|
||||
rst = rst.replace("小主人", nickname).replace("小朋友", nickname)
|
||||
rst = str(rst).replace("小主人", nickname).replace("小朋友", nickname)
|
||||
ai_message_manager.add_result(user_id, rst)
|
||||
return rst
|
||||
|
||||
@@ -126,35 +126,39 @@ async def xie_ai(text: str) -> str:
|
||||
"""
|
||||
res = await AsyncHttpx.get(f"http://api.qingyunke.com/api.php?key=free&appid=0&msg={text}")
|
||||
content = ""
|
||||
data = json.loads(res.text)
|
||||
if data["result"] == 0:
|
||||
content = data["content"]
|
||||
if "菲菲" in content:
|
||||
content = content.replace("菲菲", NICKNAME)
|
||||
if "艳儿" in content:
|
||||
content = content.replace("艳儿", NICKNAME)
|
||||
if "公众号" in content:
|
||||
content = ""
|
||||
if "{br}" in content:
|
||||
content = content.replace("{br}", "\n")
|
||||
if "提示" in content:
|
||||
content = content[: content.find("提示")]
|
||||
if "淘宝" in content or "taobao.com" in content:
|
||||
return ""
|
||||
while True:
|
||||
r = re.search("{face:(.*)}", content)
|
||||
if r:
|
||||
id_ = r.group(1)
|
||||
content = content.replace(
|
||||
"{" + f"face:{id_}" + "}", str(face(int(id_)))
|
||||
)
|
||||
else:
|
||||
break
|
||||
return (
|
||||
content
|
||||
if not content and not Config.get_config("ai", "ALAPI_AI_CHECK")
|
||||
else await check_text(content)
|
||||
)
|
||||
try:
|
||||
data = json.loads(res.text)
|
||||
if data["result"] == 0:
|
||||
content = data["content"]
|
||||
if "菲菲" in content:
|
||||
content = content.replace("菲菲", NICKNAME)
|
||||
if "艳儿" in content:
|
||||
content = content.replace("艳儿", NICKNAME)
|
||||
if "公众号" in content:
|
||||
content = ""
|
||||
if "{br}" in content:
|
||||
content = content.replace("{br}", "\n")
|
||||
if "提示" in content:
|
||||
content = content[: content.find("提示")]
|
||||
if "淘宝" in content or "taobao.com" in content:
|
||||
return ""
|
||||
while True:
|
||||
r = re.search("{face:(.*)}", content)
|
||||
if r:
|
||||
id_ = r.group(1)
|
||||
content = content.replace(
|
||||
"{" + f"face:{id_}" + "}", str(face(int(id_)))
|
||||
)
|
||||
else:
|
||||
break
|
||||
return (
|
||||
content
|
||||
if not content and not Config.get_config("ai", "ALAPI_AI_CHECK")
|
||||
else await check_text(content)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ai xie_ai 发生错误 {type(e)}:{e}")
|
||||
return ""
|
||||
|
||||
|
||||
def hello() -> str:
|
||||
|
||||
@@ -23,6 +23,8 @@ async def get_data(url: str, params: Optional[dict] = None) -> Tuple[Union[dict,
|
||||
return "没有搜索到...", 997
|
||||
return data, 200
|
||||
else:
|
||||
if data["code"] == 101:
|
||||
return "缺失ALAPI TOKEN,请在配置文件中填写!", 999
|
||||
return f'发生了错误...code:{data["code"]}', 999
|
||||
except TimeoutError:
|
||||
return "超时了....", 998
|
||||
|
||||
+10
-10
@@ -56,15 +56,15 @@ async def _(event: MessageEvent, arg: Message = CommandArg()):
|
||||
)
|
||||
if is_number(msg) and 0 < int(msg) <= 50:
|
||||
url = wbtop_data[int(msg) - 1]["url"]
|
||||
try:
|
||||
await wbtop.send("开始截取数据...")
|
||||
img = await AsyncPlaywright.screenshot(
|
||||
url,
|
||||
f"{IMAGE_PATH}/temp/wbtop_{event.user_id}.png",
|
||||
"#pl_feedlist_index",
|
||||
sleep=5
|
||||
)
|
||||
await wbtop.send("开始截取数据...")
|
||||
img = await AsyncPlaywright.screenshot(
|
||||
url,
|
||||
f"{IMAGE_PATH}/temp/wbtop_{event.user_id}.png",
|
||||
"#pl_feed_main",
|
||||
wait_time=12
|
||||
)
|
||||
if img:
|
||||
await wbtop.send(img)
|
||||
except Exception as e:
|
||||
logger.error(f"微博热搜截图出错... {type(e)}: {e}")
|
||||
else:
|
||||
await wbtop.send("发生了一些错误.....")
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ usage:
|
||||
__plugin_des__ = "非常便利的B站订阅通知"
|
||||
__plugin_cmd__ = ["添加订阅 [主播/UP/番剧] [id/链接/番名]", "删除订阅 [id]", "查看订阅"]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_author__ = "HibiKier & NumberSir"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
@@ -211,7 +211,7 @@ async def _():
|
||||
await sub_manager.reload_sub_data()
|
||||
sub = await sub_manager.random_sub_data()
|
||||
if sub:
|
||||
logger.info(f"Bilibili订阅开始检测:{sub.sub_id}")
|
||||
logger.debug(f"Bilibili订阅开始检测:{sub.sub_id}")
|
||||
rst = await get_sub_status(sub.sub_id, sub.sub_type)
|
||||
await send_sub_msg(rst, sub, bot)
|
||||
if sub.sub_type == "live":
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
from bilibili_api.exceptions.ResponseCodeException import ResponseCodeException
|
||||
from bilireq.exceptions import ResponseCodeError
|
||||
from utils.manager import resources_manager
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from .model import BilibiliSub
|
||||
from bilibili_api.live import LiveRoom
|
||||
from bilibili_api import bangumi
|
||||
from bilireq.live import get_room_info_by_id
|
||||
from .utils import get_meta
|
||||
from utils.message_builder import image
|
||||
from bilibili_api.user import User
|
||||
from bilibili_api import user
|
||||
from bilireq.user import get_user_info
|
||||
from bilireq import dynamic
|
||||
from .utils import get_videos
|
||||
from typing import Optional
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from datetime import datetime
|
||||
@@ -36,9 +37,9 @@ async def add_live_sub(live_id: int, sub_user: str) -> str:
|
||||
try:
|
||||
async with db.transaction():
|
||||
try:
|
||||
live = LiveRoom(live_id)
|
||||
live_info = (await live.get_room_info())["room_info"]
|
||||
except ResponseCodeException:
|
||||
"""bilibili_api.live库的LiveRoom类中get_room_info改为bilireq.live库的get_room_info_by_id方法"""
|
||||
live_info = await get_room_info_by_id(live_id)
|
||||
except ResponseCodeError:
|
||||
return f"未找到房间号Id:{live_id} 的信息,请检查Id是否正确"
|
||||
uid = live_info["uid"]
|
||||
room_id = live_info["room_id"]
|
||||
@@ -78,16 +79,18 @@ async def add_up_sub(uid: int, sub_user: str) -> str:
|
||||
try:
|
||||
async with db.transaction():
|
||||
try:
|
||||
u = user.User(uid)
|
||||
user_info = await u.get_user_info()
|
||||
except ResponseCodeException:
|
||||
"""bilibili_api.user库中User类的get_user_info改为bilireq.user库的get_user_info方法"""
|
||||
user_info = await get_user_info(uid)
|
||||
except ResponseCodeError:
|
||||
return f"未找到UpId:{uid} 的信息,请检查Id是否正确"
|
||||
uname = user_info["name"]
|
||||
dynamic_info = await u.get_dynamics(0)
|
||||
"""bilibili_api.user库中User类的get_dynamics改为bilireq.dynamic库的get_user_dynamics方法"""
|
||||
dynamic_info = await dynamic.get_user_dynamics(uid)
|
||||
dynamic_upload_time = 0
|
||||
if dynamic_info.get("cards"):
|
||||
dynamic_upload_time = dynamic_info["cards"][0]["desc"]["timestamp"]
|
||||
video_info = await u.get_videos()
|
||||
"""bilibili_api.user库中User类的get_videos改为bilireq.user库的get_videos方法"""
|
||||
video_info = await get_videos(uid)
|
||||
latest_video_created = 0
|
||||
if video_info["list"].get("vlist"):
|
||||
latest_video_created = video_info["list"]["vlist"][0]["created"]
|
||||
@@ -117,8 +120,9 @@ async def add_season_sub(media_id: int, sub_user: str) -> str:
|
||||
try:
|
||||
async with db.transaction():
|
||||
try:
|
||||
season_info = await bangumi.get_meta(media_id)
|
||||
except ResponseCodeException:
|
||||
"""bilibili_api.bangumi库中get_meta改为bilireq.bangumi库的get_meta方法"""
|
||||
season_info = await get_meta(media_id)
|
||||
except ResponseCodeError:
|
||||
return f"未找到media_id:{media_id} 的信息,请检查Id是否正确"
|
||||
season_id = season_info["media"]["season_id"]
|
||||
season_current_episode = season_info["media"]["new_ep"]["index"]
|
||||
@@ -200,7 +204,7 @@ async def get_sub_status(id_: int, sub_type: str) -> Optional[str]:
|
||||
return await _get_up_status(id_)
|
||||
elif sub_type == "season":
|
||||
return await _get_season_status(id_)
|
||||
except ResponseCodeException:
|
||||
except ResponseCodeError:
|
||||
return f"Id:{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试..."
|
||||
# except Exception as e:
|
||||
# logger.error(f"获取订阅状态发生预料之外的错误 id_:{id_} {type(e)}:{e}")
|
||||
@@ -212,12 +216,12 @@ async def _get_live_status(id_: int) -> Optional[str]:
|
||||
获取直播订阅状态
|
||||
:param id_: 直播间 id
|
||||
"""
|
||||
live = LiveRoom(id_)
|
||||
live_info = (await live.get_room_info())["room_info"]
|
||||
"""bilibili_api.live库的LiveRoom类中get_room_info改为bilireq.live库的get_room_info_by_id方法"""
|
||||
live_info = await get_room_info_by_id(id_)
|
||||
title = live_info["title"]
|
||||
room_id = live_info["room_id"]
|
||||
live_status = live_info["live_status"]
|
||||
cover = live_info["cover"]
|
||||
cover = live_info["user_cover"]
|
||||
sub = await BilibiliSub.get_sub(id_)
|
||||
if sub.live_status != live_status:
|
||||
await BilibiliSub.update_sub_info(id_, live_status=live_status)
|
||||
@@ -238,15 +242,16 @@ async def _get_up_status(id_: int) -> Optional[str]:
|
||||
:return:
|
||||
"""
|
||||
_user = await BilibiliSub.get_sub(id_)
|
||||
u = user.User(_user.uid)
|
||||
user_info = await u.get_user_info()
|
||||
"""bilibili_api.user库中User类的get_user_info改为bilireq.user库的get_user_info方法"""
|
||||
user_info = await get_user_info(_user.uid)
|
||||
uname = user_info["name"]
|
||||
video_info = await u.get_videos()
|
||||
"""bilibili_api.user库中User类的get_videos改为bilireq.user库的get_videos方法"""
|
||||
video_info = await get_videos(id_)
|
||||
latest_video_created = 0
|
||||
video = None
|
||||
if _user.uname != uname:
|
||||
await BilibiliSub.update_sub_info(id_, uname=uname)
|
||||
dynamic_img, dynamic_upload_time = await get_user_dynamic(u, _user)
|
||||
dynamic_img, dynamic_upload_time = await get_user_dynamic(id_, _user)
|
||||
if video_info["list"].get("vlist"):
|
||||
video = video_info["list"]["vlist"][0]
|
||||
latest_video_created = video["created"]
|
||||
@@ -280,7 +285,8 @@ async def _get_season_status(id_) -> Optional[str]:
|
||||
获取 番剧 更新状态
|
||||
:param id_: 番剧 id
|
||||
"""
|
||||
season_info = await bangumi.get_meta(id_)
|
||||
"""bilibili_api.bangumi库中get_meta改为bilireq.bangumi库的get_meta方法"""
|
||||
season_info = await get_meta(id_)
|
||||
title = season_info["media"]["title"]
|
||||
_idx = (await BilibiliSub.get_sub(id_)).season_current_episode
|
||||
new_ep = season_info["media"]["new_ep"]["index"]
|
||||
@@ -297,42 +303,47 @@ async def _get_season_status(id_) -> Optional[str]:
|
||||
|
||||
|
||||
async def get_user_dynamic(
|
||||
u: User, local_user: BilibiliSub
|
||||
uid: int, local_user: BilibiliSub
|
||||
) -> "Optional[MessageSegment], int":
|
||||
"""
|
||||
获取用户动态
|
||||
:param u: 用户类
|
||||
:param uid: 用户uid
|
||||
:param local_user: 数据库存储的用户数据
|
||||
:return: 最新动态截图与时间
|
||||
"""
|
||||
dynamic_info = await u.get_dynamics(0)
|
||||
"""bilibili_api.user库中User类的get_dynamics改为bilireq.dynamic库的get_user_dynamics方法"""
|
||||
dynamic_info = await dynamic.get_user_dynamics(uid)
|
||||
browser = await get_browser()
|
||||
if dynamic_info.get("cards") and browser:
|
||||
dynamic_upload_time = dynamic_info["cards"][0]["desc"]["timestamp"]
|
||||
if local_user.dynamic_upload_time < dynamic_upload_time:
|
||||
page = await browser.new_page()
|
||||
await page.goto(
|
||||
f"https://space.bilibili.com/{local_user.uid}/dynamic",
|
||||
wait_until="networkidle",
|
||||
timeout=10000,
|
||||
)
|
||||
await page.set_viewport_size({"width": 2560, "height": 1080})
|
||||
# 删除置顶
|
||||
await page.evaluate(
|
||||
try:
|
||||
await page.goto(
|
||||
f"https://space.bilibili.com/{local_user.uid}/dynamic",
|
||||
wait_until="networkidle",
|
||||
timeout=10000,
|
||||
)
|
||||
await page.set_viewport_size({"width": 2560, "height": 1080, "timeout": 10000*20}) # timeout: 200s
|
||||
# 删除置顶
|
||||
await page.evaluate(
|
||||
"""
|
||||
xs = document.getElementsByClassName('bili-dyn-item__tag');
|
||||
for (x of xs) {
|
||||
x.parentNode.parentNode.remove();
|
||||
}
|
||||
"""
|
||||
xs = document.getElementsByClassName('first-card-with-title');
|
||||
for (x of xs) {
|
||||
x.remove();
|
||||
}
|
||||
"""
|
||||
)
|
||||
card = await page.query_selector(".card")
|
||||
# 截图并保存
|
||||
await card.screenshot(
|
||||
path=dynamic_path / f"{local_user.sub_id}_{dynamic_upload_time}.jpg",
|
||||
timeout=100000,
|
||||
)
|
||||
await page.close()
|
||||
)
|
||||
card = page.locator(".bili-dyn-list__item").first
|
||||
await card.wait_for()
|
||||
# 截图并保存
|
||||
await card.screenshot(
|
||||
path=dynamic_path / f"{local_user.sub_id}_{dynamic_upload_time}.jpg",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"B站订阅:获取用户动态 发送错误 {type(e)}:{e}")
|
||||
finally:
|
||||
await page.close()
|
||||
return (
|
||||
image(
|
||||
f"{local_user.sub_id}_{dynamic_upload_time}.jpg",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
from utils.image_utils import BuildImage
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from bilibili_api import user
|
||||
# from bilibili_api import user
|
||||
from bilireq.user import get_user_info
|
||||
from io import BytesIO
|
||||
|
||||
|
||||
@@ -28,8 +29,8 @@ async def create_live_des_image(uid: int, title: str, cover: str, tags: str, des
|
||||
:param des: 直播简介
|
||||
:return:
|
||||
"""
|
||||
u = user.User(uid)
|
||||
user_info = await u.get_user_info()
|
||||
|
||||
user_info = await get_user_info(uid)
|
||||
name = user_info["name"]
|
||||
sex = user_info["sex"]
|
||||
face = user_info["face"]
|
||||
@@ -37,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.circle()
|
||||
cover = BuildImage(470, 265, background=BytesIO(await get_pic(cover)))
|
||||
print()
|
||||
|
||||
|
||||
def _create_live_des_image(
|
||||
@@ -68,3 +68,47 @@ def _create_live_des_image(
|
||||
border_img = BuildImage(1772, 2657, background=border)
|
||||
bk = BuildImage(1772, 2657, font_size=30)
|
||||
bk.paste(cover, (0, 100), center_type="by_width")
|
||||
|
||||
|
||||
async def get_meta(media_id: int, auth=None, reqtype="both", **kwargs):
|
||||
"""
|
||||
根据番剧 ID 获取番剧元数据信息,
|
||||
作为bilibili_api和bilireq的替代品。
|
||||
如果bilireq.bangumi更新了,可以转为调用bilireq.bangumi的get_meta方法,两者完全一致。
|
||||
"""
|
||||
from bilireq.utils import get
|
||||
|
||||
BASE_URL = "https://api.bilibili.com"
|
||||
url = f"{BASE_URL}/pgc/review/user"
|
||||
params = {"media_id": media_id}
|
||||
raw_json = await get(url, raw=True, params=params, auth=auth, reqtype=reqtype, **kwargs)
|
||||
return raw_json['result']
|
||||
|
||||
|
||||
async def get_videos(
|
||||
uid: int, tid: int = 0, pn: int = 1, keyword: str = "", order: str = "pubdate",
|
||||
*, auth=None, reqtype="both", **kwargs
|
||||
):
|
||||
"""
|
||||
获取用户投该视频信息
|
||||
作为bilibili_api和bilireq的替代品。
|
||||
如果bilireq.user更新了,可以转为调用bilireq.user的get_videos方法,两者完全一致。
|
||||
|
||||
:param uid: 用户 UID
|
||||
:param tid: 分区 ID
|
||||
:param pn: 页码
|
||||
:param keyword: 搜索关键词
|
||||
:param order: 排序方式,可以为 “pubdate(上传日期从新到旧), stow(收藏从多到少), click(播放量从多到少)”
|
||||
"""
|
||||
from bilireq.utils import get
|
||||
BASE_URL = "https://api.bilibili.com"
|
||||
url = f"{BASE_URL}/x/space/arc/search"
|
||||
params = {
|
||||
"mid": uid,
|
||||
"ps": 30,
|
||||
"tid": tid,
|
||||
"pn": pn,
|
||||
"keyword": keyword,
|
||||
"order": order
|
||||
}
|
||||
return await get(url, params=params, auth=auth, reqtype=reqtype, **kwargs)
|
||||
@@ -0,0 +1,248 @@
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
Event,
|
||||
MessageEvent,
|
||||
GroupMessageEvent,
|
||||
Message,
|
||||
Bot,
|
||||
)
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.message import run_preprocessor
|
||||
from utils.image_utils import BuildImage
|
||||
from utils.utils import get_message_text, is_number
|
||||
from nonebot.params import RegexGroup, CommandArg
|
||||
from .utils import black_word_manager
|
||||
from nonebot import on_command, on_message, on_regex
|
||||
from configs.config import Config, NICKNAME
|
||||
from nonebot.permission import SUPERUSER
|
||||
from .data_source import show_black_text_image, set_user_punish
|
||||
from services.log import logger
|
||||
from models.ban_user import BanUser
|
||||
from datetime import datetime
|
||||
from utils.message_builder import image
|
||||
from .model import BlackWord
|
||||
from typing import Tuple, Any
|
||||
|
||||
|
||||
__zx_plugin_name__ = "敏感词检测"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
注意你的发言!
|
||||
指令:
|
||||
惩罚机制
|
||||
""".strip()
|
||||
__plugin_superuser_usage__ = """
|
||||
usage:
|
||||
查看和设置惩罚
|
||||
Regex:^记录名单(u:\d*)?(g:\d*)?(d[=><]\d*-\d{1,2}-\d{1,2})?$
|
||||
设置惩罚id需要通过 '记录名单u:xxxxxxxx' 获取
|
||||
指令:
|
||||
记录名单
|
||||
设置惩罚 [user_id] [id] [punish_level]
|
||||
示例:记录名单
|
||||
示例:记录名单u:12345678
|
||||
示例:设置惩罚 12345678 1 4
|
||||
""".strip()
|
||||
__plugin_des__ = "请注意你的发言!!"
|
||||
__plugin_type__ = ("其他",)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_cmd__ = ["惩罚机制", "记录名单 [_superuser]", "设置惩罚 [_superuser]"]
|
||||
__plugin_settings__ = {
|
||||
"cmd": ["敏感词检测"],
|
||||
}
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word", "CYCLE_DAYS", 30, name="敏感词检测与惩罚", help_="黑名单词汇记录周期", default_value=30
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"TOLERATE_COUNT",
|
||||
[5, 1, 1, 1, 1],
|
||||
help_="各个级别惩罚的容忍次数,依次为:1, 2, 3, 4, 5",
|
||||
default_value=[5, 1, 1, 1, 1],
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word", "AUTO_PUNISH", True, help_="是否启动自动惩罚机制", default_value=True
|
||||
)
|
||||
|
||||
# Config.add_plugin_config(
|
||||
# "black_word", "IGNORE_GROUP", [], help_="退出群聊惩罚中忽略的群聊,即不会退出的群聊", default_value=[]
|
||||
# )
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"BAN_4_DURATION",
|
||||
360,
|
||||
help_="Union[int, List[int, int]]Ban时长(分钟),四级惩罚,可以为指定数字或指定列表区间(随机),例如 [30, 360]",
|
||||
default_value=360,
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"BAN_3_DURATION",
|
||||
7,
|
||||
help_="Union[int, List[int, int]]Ban时长(天),三级惩罚,可以为指定数字或指定列表区间(随机),例如 [7, 30]",
|
||||
default_value=360,
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"WARNING_RESULT",
|
||||
f"请注意对{NICKNAME}的发言内容",
|
||||
help_="口头警告内容",
|
||||
default_value=f"请注意对{NICKNAME}的发言内容",
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"AUTO_ADD_PUNISH_LEVEL",
|
||||
True,
|
||||
help_="自动提级机制,当周期内处罚次数大于某一特定值就提升惩罚等级",
|
||||
default_value=True,
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"ADD_PUNISH_LEVEL_TO_COUNT",
|
||||
3,
|
||||
help_="在CYCLE_DAYS周期内触发指定惩罚次数后提升惩罚等级",
|
||||
default_value=3,
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"ALAPI_CHECK_FLAG",
|
||||
False,
|
||||
help_="当未检测到已收录的敏感词时,开启ALAPI文本检测并将疑似文本发送给超级用户",
|
||||
default_value=False,
|
||||
)
|
||||
|
||||
Config.add_plugin_config(
|
||||
"black_word",
|
||||
"CONTAIN_BLACK_STOP_PROPAGATION",
|
||||
True,
|
||||
help_="当文本包含任意敏感词时,停止向下级插件传递,即不触发ai",
|
||||
default_value=True,
|
||||
)
|
||||
|
||||
message_matcher = on_message(priority=1, block=False)
|
||||
|
||||
set_punish = on_command("设置惩罚", priority=1, permission=SUPERUSER, block=True)
|
||||
|
||||
show_black = on_regex(
|
||||
r"^记录名单(u:\d*)?(g:\d*)?(d[=><]\d*-\d{1,2}-\d{1,2})?$",
|
||||
priority=1,
|
||||
permission=SUPERUSER,
|
||||
block=True,
|
||||
)
|
||||
|
||||
show_punish = on_command("惩罚机制", aliases={"敏感词检测"}, priority=1, block=True)
|
||||
|
||||
|
||||
# 黑名单词汇检测
|
||||
@run_preprocessor
|
||||
async def _(
|
||||
bot: Bot,
|
||||
matcher: Matcher,
|
||||
event: Event,
|
||||
):
|
||||
if (
|
||||
isinstance(event, MessageEvent)
|
||||
and event.is_tome()
|
||||
and matcher.plugin_name == "black_word"
|
||||
and not await BanUser.is_ban(event.user_id)
|
||||
and str(event.user_id) not in bot.config.superusers
|
||||
):
|
||||
user_id = event.user_id
|
||||
group_id = event.group_id if isinstance(event, GroupMessageEvent) else None
|
||||
msg = get_message_text(event.json())
|
||||
if await black_word_manager.check(user_id, group_id, msg) and Config.get_config(
|
||||
"black_word", "CONTAIN_BLACK_STOP_PROPAGATION"
|
||||
):
|
||||
matcher.stop_propagation()
|
||||
|
||||
|
||||
@show_black.handle()
|
||||
async def _(bot: Bot, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
user_id, group_id, date = reg_group
|
||||
date_type = "="
|
||||
if date:
|
||||
date_type = date[1]
|
||||
date = date[2:]
|
||||
try:
|
||||
date = datetime.strptime(date, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
await show_black.finish("日期格式错误,需要:年-月-日")
|
||||
pic = await show_black_text_image(
|
||||
bot,
|
||||
int(user_id.split(":")[1]) if user_id else None,
|
||||
int(group_id.split(":")[1]) if group_id else None,
|
||||
date,
|
||||
date_type,
|
||||
)
|
||||
await show_black.send(image(b64=pic.pic2bs4()))
|
||||
|
||||
|
||||
@show_punish.handle()
|
||||
async def _():
|
||||
text = f"""
|
||||
** 惩罚机制 **
|
||||
|
||||
惩罚前包含容忍机制,在指定周期内会容忍偶尔少次数的敏感词只会进行警告提醒
|
||||
|
||||
多次触发同级惩罚会使惩罚等级提高,即惩罚自动提级机制
|
||||
|
||||
目前公开的惩罚等级:
|
||||
|
||||
1级:永久ban
|
||||
|
||||
2级:删除好友
|
||||
|
||||
3级:ban指定/随机天数
|
||||
|
||||
4级:ban指定/随机时长
|
||||
|
||||
5级:警告
|
||||
|
||||
备注:
|
||||
|
||||
该功能为测试阶段,如果你有被误封情况,请联系管理员,会从数据库中提取出你的数据进行审核后判断
|
||||
|
||||
目前该功能暂不完善,部分情况会由管理员鉴定,请注意对真寻的发言
|
||||
|
||||
关于敏感词:
|
||||
|
||||
记住不要骂{NICKNAME}就对了!
|
||||
""".strip()
|
||||
max_width = 0
|
||||
for m in text.split("\n"):
|
||||
max_width = len(m) * 20 if len(m) * 20 > max_width else max_width
|
||||
max_height = len(text.split("\n")) * 24
|
||||
A = BuildImage(
|
||||
max_width, max_height, font="CJGaoDeGuo.otf", font_size=24, color="#E3DBD1"
|
||||
)
|
||||
A.text((10, 10), text)
|
||||
await show_punish.send(image(b64=A.pic2bs4()))
|
||||
|
||||
|
||||
@set_punish.handle()
|
||||
async def _(event: MessageEvent, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip().split()
|
||||
if (
|
||||
len(msg) < 3
|
||||
or not is_number(msg[0])
|
||||
or not is_number(msg[1])
|
||||
or not is_number(msg[2])
|
||||
):
|
||||
await set_punish.finish("参数错误,请查看帮助...", at_sender=True)
|
||||
uid = int(msg[0])
|
||||
id_ = int(msg[1])
|
||||
punish_level = int(msg[2])
|
||||
rst = await set_user_punish(uid, id_, punish_level)
|
||||
await set_punish.send(rst)
|
||||
logger.info(
|
||||
f"USER {event.user_id} 设置惩罚 uid:{uid} id_:{id_} punish_level:{punish_level} --> {rst}"
|
||||
)
|
||||
@@ -0,0 +1,118 @@
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from utils.image_utils import BuildImage, text2image
|
||||
from services.log import logger
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from .model import BlackWord
|
||||
from .utils import _get_punish, Config
|
||||
|
||||
|
||||
async def show_black_text_image(
|
||||
bot: Bot,
|
||||
user: Optional[int],
|
||||
group_id: Optional[int],
|
||||
date: Optional[datetime],
|
||||
data_type: str = "=",
|
||||
) -> BuildImage:
|
||||
"""
|
||||
展示记录名单
|
||||
:param bot: bot
|
||||
:param user: 用户qq
|
||||
:param group_id: 群聊
|
||||
:param date: 日期
|
||||
:param data_type: 日期搜索类型
|
||||
:return:
|
||||
"""
|
||||
data = await BlackWord.get_black_data(user, group_id, date, data_type)
|
||||
A = BuildImage(0, 0, color="#f9f6f2", font_size=20)
|
||||
image_list = []
|
||||
friend_str = await bot.get_friend_list()
|
||||
id_str = ""
|
||||
uname_str = ""
|
||||
uid_str = ""
|
||||
gid_str = ""
|
||||
plant_text_str = ""
|
||||
black_word_str = ""
|
||||
punish_str = ""
|
||||
punish_level_str = ""
|
||||
create_time_str = ""
|
||||
for i, x in enumerate(data):
|
||||
try:
|
||||
if x.group_id:
|
||||
user_name = (
|
||||
await bot.get_group_member_info(
|
||||
group_id=x.group_id, user_id=x.user_qq
|
||||
)
|
||||
)["card"]
|
||||
else:
|
||||
user_name = [
|
||||
u["nickname"] for u in friend_str if u["user_id"] == x.user_qq
|
||||
][0]
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"show_black_text_image 获取 USER {x.user_qq} user_name 失败 {type(e)}:{e}"
|
||||
)
|
||||
user_name = x.user_qq
|
||||
id_str += f"{i}\n"
|
||||
uname_str += f"{user_name}\n"
|
||||
uid_str += f"{x.user_qq}\n"
|
||||
gid_str += f"{x.group_id}\n"
|
||||
plant_text = " ".join(x.plant_text.split("\n"))
|
||||
if A.getsize(plant_text)[0] > 200:
|
||||
plant_text = plant_text[:20] + "..."
|
||||
plant_text_str += f"{plant_text}\n"
|
||||
black_word_str += f"{x.black_word}\n"
|
||||
punish_str += f"{x.punish}\n"
|
||||
punish_level_str += f"{x.punish_level}\n"
|
||||
create_time_str += f"{x.create_time.replace(microsecond=0)}\n"
|
||||
_tmp_img = BuildImage(0, 0, font_size=35, font="CJGaoDeGuo.otf")
|
||||
for s, type_ in [
|
||||
(id_str, "Id"),
|
||||
(uname_str, "昵称"),
|
||||
(uid_str, "UID"),
|
||||
(gid_str, "GID"),
|
||||
(plant_text_str, "文本"),
|
||||
(black_word_str, "检测"),
|
||||
(punish_str, "惩罚"),
|
||||
(punish_level_str, "等级"),
|
||||
(create_time_str, "记录日期"),
|
||||
]:
|
||||
img = await text2image(s, color="#f9f6f2", _add_height=2.1)
|
||||
w = _tmp_img.getsize(type_)[0] if _tmp_img.getsize(type_)[0] > img.w else img.w
|
||||
A = BuildImage(w + 11, img.h + 50, color="#f9f6f2", font_size=35, font="CJGaoDeGuo.otf")
|
||||
await A.atext((10, 10), type_)
|
||||
await A.apaste(img, (0, 50))
|
||||
image_list.append(A)
|
||||
horizontal_line = []
|
||||
w, h = 0, 0
|
||||
for img in image_list:
|
||||
w += img.w + 20
|
||||
h = img.h if img.h > h else h
|
||||
horizontal_line.append(img.w)
|
||||
A = BuildImage(w, h, color="#f9f6f2")
|
||||
current_w = 0
|
||||
for img in image_list:
|
||||
await A.apaste(img, (current_w, 0))
|
||||
current_w += img.w + 20
|
||||
return A
|
||||
|
||||
|
||||
async def set_user_punish(user_id: int, id_: int, punish_level: int) -> str:
|
||||
"""
|
||||
设置惩罚
|
||||
:param user_id: 用户id
|
||||
:param id_: 记录下标
|
||||
:param punish_level: 惩罚等级
|
||||
"""
|
||||
result = await _get_punish(punish_level, user_id)
|
||||
punish = {
|
||||
1: "永久ban",
|
||||
2: "删除好友",
|
||||
3: f"ban {result} 天",
|
||||
4: f"ban {result} 分钟",
|
||||
5: "口头警告"
|
||||
}
|
||||
if await BlackWord.set_user_punish(user_id, punish[punish_level], id_=id_):
|
||||
return f"已对 USER {user_id} 进行 {punish[punish_level]} 处罚。"
|
||||
else:
|
||||
return "操作失败,可能未找到用户,id或敏感词"
|
||||
@@ -0,0 +1,148 @@
|
||||
from services.db_context import db
|
||||
from typing import Optional, List
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
class BlackWord(db.Model):
|
||||
__tablename__ = "black_word"
|
||||
|
||||
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
|
||||
user_qq = db.Column(db.BigInteger(), nullable=False, primary_key=True)
|
||||
group_id = db.Column(db.BigInteger())
|
||||
plant_text = db.Column(db.String())
|
||||
black_word = db.Column(db.String())
|
||||
punish = db.Column(db.String(), default="")
|
||||
punish_level = db.Column(db.Integer())
|
||||
create_time = db.Column(db.DateTime(timezone=True), nullable=False)
|
||||
|
||||
@classmethod
|
||||
async def add_user_black_word(
|
||||
cls,
|
||||
user_qq: int,
|
||||
group_id: Optional[int],
|
||||
black_word: str,
|
||||
plant_text: str,
|
||||
punish_level: int,
|
||||
):
|
||||
"""
|
||||
说明:
|
||||
添加用户发送的敏感词
|
||||
参数:
|
||||
:param user_qq: 用户id
|
||||
:param group_id: 群号
|
||||
:param black_word: 黑名单词汇
|
||||
:param plant_text: 消息文本
|
||||
:param punish_level: 惩罚等级
|
||||
"""
|
||||
await cls.create(
|
||||
user_qq=user_qq,
|
||||
group_id=group_id,
|
||||
plant_text=plant_text,
|
||||
black_word=black_word,
|
||||
punish_level=punish_level,
|
||||
create_time=datetime.now(),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def set_user_punish(
|
||||
cls,
|
||||
user_qq: int,
|
||||
punish: str,
|
||||
black_word: Optional[str] = None,
|
||||
id_: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
说明:
|
||||
设置处罚
|
||||
参数:
|
||||
:param user_qq: 用户id
|
||||
:param punish: 处罚
|
||||
:param black_word: 黑名单词汇
|
||||
:param id_: 记录下标
|
||||
"""
|
||||
user = None
|
||||
if (not black_word and not id_) or not punish:
|
||||
return False
|
||||
query = cls.query.where(cls.user_qq == user_qq).with_for_update()
|
||||
if black_word:
|
||||
user = await query.where(cls.black_word == black_word).order_by(cls.id.desc()).gino.first()
|
||||
elif id_:
|
||||
user_list = await query.gino.all()
|
||||
if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)):
|
||||
return False
|
||||
user = user_list[id_]
|
||||
if not user:
|
||||
return False
|
||||
await user.update(punish=cls.punish + punish + " ").apply()
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
async def get_user_count(
|
||||
cls, user_qq: int, days: int = 7, punish_level: Optional[int] = None
|
||||
) -> int:
|
||||
"""
|
||||
说明:
|
||||
获取用户规定周期内的犯事次数
|
||||
参数:
|
||||
:param user_qq: 用户qq
|
||||
:param days: 周期天数
|
||||
:param punish_level: 惩罚等级
|
||||
"""
|
||||
setattr(BlackWord, "count", db.func.count(cls.id).label("count"))
|
||||
query = cls.select("count").where(
|
||||
(cls.user_qq == user_qq)
|
||||
& (cls.punish_level != -1)
|
||||
& (cls.create_time > datetime.now() - timedelta(days=days))
|
||||
)
|
||||
if punish_level is not None:
|
||||
query = query.where(cls.punish_level == punish_level)
|
||||
return (await query.gino.first())[0]
|
||||
|
||||
@classmethod
|
||||
async def get_user_punish_level(cls, user_qq: int, days: int = 7) -> Optional[int]:
|
||||
"""
|
||||
说明:
|
||||
获取用户最近一次的惩罚记录等级
|
||||
参数:
|
||||
:param user_qq: 用户qq
|
||||
:param days: 周期天数
|
||||
"""
|
||||
if (
|
||||
query := await cls.query.where(cls.user_qq == user_qq)
|
||||
.where(cls.create_time > datetime.now() - timedelta(days=days))
|
||||
.order_by(cls.id.desc())
|
||||
.gino.first()
|
||||
):
|
||||
return query.punish_level
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
async def get_black_data(
|
||||
cls,
|
||||
user_qq: Optional[int],
|
||||
group_id: Optional[int],
|
||||
date: Optional[datetime],
|
||||
date_type: str = "=",
|
||||
) -> List["BlackWord"]:
|
||||
"""
|
||||
说明:
|
||||
通过指定条件查询数据
|
||||
参数:
|
||||
:param user_qq: 用户qq
|
||||
:param group_id: 群号
|
||||
:param date: 日期
|
||||
:param date_type: 日期查询类型
|
||||
"""
|
||||
query = cls.query
|
||||
if user_qq:
|
||||
query = query.where(cls.user_qq == user_qq)
|
||||
if group_id:
|
||||
query = query.where(cls.group_id == group_id)
|
||||
if date:
|
||||
if date_type == "=":
|
||||
query = query.where(cls.create_time == date)
|
||||
elif date_type == ">":
|
||||
query = query.where(cls.create_time > date)
|
||||
elif date_type == "<":
|
||||
query = query.where(cls.create_time < date)
|
||||
return await query.gino.all()
|
||||
@@ -0,0 +1,322 @@
|
||||
from utils.utils import cn2py, get_bot
|
||||
from configs.path_config import DATA_PATH
|
||||
from typing import Optional, Union, Tuple
|
||||
from .model import BlackWord
|
||||
from configs.config import Config
|
||||
from pathlib import Path
|
||||
from services.log import logger
|
||||
from models.ban_user import BanUser
|
||||
from nonebot.adapters.onebot.v11.exception import ActionFailed
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from utils.http_utils import AsyncHttpx
|
||||
import random
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
class BlackWordManager:
|
||||
|
||||
"""
|
||||
敏感词管理( 拒绝恶意
|
||||
"""
|
||||
|
||||
def __init__(self, word_file: Path, py_file: Path):
|
||||
self._word_list = {
|
||||
"1": [],
|
||||
"2": [],
|
||||
"3": [],
|
||||
"4": ["sb", "nmsl", "mdzz", "2b", "jb", "操", "废物", "憨憨", "cnm", "rnm"],
|
||||
"5": [],
|
||||
}
|
||||
self._py_list = {
|
||||
"1": [],
|
||||
"2": [],
|
||||
"3": [],
|
||||
"4": [
|
||||
"shabi",
|
||||
"wocaonima",
|
||||
"sima",
|
||||
"sabi",
|
||||
"zhizhang",
|
||||
"naocan",
|
||||
"caonima",
|
||||
"rinima",
|
||||
"simadongxi",
|
||||
"simawanyi",
|
||||
"hanbi",
|
||||
"hanpi",
|
||||
"laji",
|
||||
"fw"
|
||||
],
|
||||
"5": [],
|
||||
}
|
||||
word_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
if word_file.exists():
|
||||
# 清空默认配置
|
||||
with open(word_file, "r", encoding="utf8") as f:
|
||||
self._word_list = json.load(f)
|
||||
else:
|
||||
with open(word_file, "w", encoding="utf8") as f:
|
||||
json.dump(
|
||||
self._word_list,
|
||||
f,
|
||||
ensure_ascii=False,
|
||||
indent=4,
|
||||
)
|
||||
if py_file.exists():
|
||||
# 清空默认配置
|
||||
with open(py_file, "r", encoding="utf8") as f:
|
||||
self._py_list = json.load(f)
|
||||
else:
|
||||
with open(py_file, "w", encoding="utf8") as f:
|
||||
json.dump(
|
||||
self._py_list,
|
||||
f,
|
||||
ensure_ascii=False,
|
||||
indent=4,
|
||||
)
|
||||
|
||||
async def check(
|
||||
self, user_id: int, group_id: Optional[int], message: str
|
||||
) -> Optional[Union[str, bool]]:
|
||||
"""
|
||||
检查是否包含黑名单词汇
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
:param message: 消息
|
||||
"""
|
||||
if data := self._check(message):
|
||||
if data[0]:
|
||||
await _add_user_black_word(
|
||||
user_id, group_id, data[0], message, int(data[1])
|
||||
)
|
||||
return True
|
||||
if Config.get_config(
|
||||
"black_word", "ALAPI_CHECK_FLAG"
|
||||
) and not await check_text(message):
|
||||
await send_msg(
|
||||
0, None, f"USER {user_id} GROUP {group_id} ALAPI 疑似检测:{message}"
|
||||
)
|
||||
return False
|
||||
|
||||
def _check(self, message: str) -> Tuple[Optional[str], int]:
|
||||
"""
|
||||
检测文本是否违规
|
||||
:param message: 检测消息
|
||||
"""
|
||||
# 移除空格
|
||||
message = message.replace(" ", "")
|
||||
py_msg = cn2py(message).lower()
|
||||
# 完全匹配
|
||||
for x in [self._word_list, self._py_list]:
|
||||
for level in x:
|
||||
if message in x[level] or py_msg in x[level]:
|
||||
return message if message in x[level] else py_msg, level
|
||||
# 模糊匹配
|
||||
for x in [self._word_list, self._py_list]:
|
||||
for level in x:
|
||||
for m in x[level]:
|
||||
if m in message or m in py_msg:
|
||||
return m, -1
|
||||
return None, 0
|
||||
|
||||
|
||||
async def _add_user_black_word(
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
black_word: str,
|
||||
message: str,
|
||||
punish_level: int,
|
||||
):
|
||||
"""
|
||||
添加敏感词数据
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
:param black_word: 触发的黑名单词汇
|
||||
:param message: 原始文本
|
||||
:param punish_level: 惩罚等级
|
||||
"""
|
||||
cycle_days = Config.get_config("black_word", "CYCLE_DAYS") or 7
|
||||
user_count = await BlackWord.get_user_count(user_id, cycle_days, punish_level)
|
||||
# 周期内超过次数直接提升惩罚
|
||||
if Config.get_config(
|
||||
"black_word", "AUTO_ADD_PUNISH_LEVEL"
|
||||
) and user_count > Config.get_config("black_word", "ADD_PUNISH_LEVEL_TO_COUNT"):
|
||||
punish_level -= 1
|
||||
await BlackWord.add_user_black_word(
|
||||
user_id, group_id, black_word, message, punish_level
|
||||
)
|
||||
logger.info(
|
||||
f"已将 USER {user_id} GROUP {group_id} 添加至黑名单词汇记录 Black_word:{black_word} Plant_text:{message}"
|
||||
)
|
||||
# 自动惩罚
|
||||
if Config.get_config("black_word", "AUTO_PUNISH") and punish_level != -1:
|
||||
await _punish_handle(user_id, group_id, punish_level, black_word)
|
||||
|
||||
|
||||
async def _punish_handle(
|
||||
user_id: int, group_id: Optional[int], punish_level: int, black_word: str
|
||||
):
|
||||
"""
|
||||
惩罚措施,级别越低惩罚越严
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
:param black_word: 触发的黑名单词汇
|
||||
"""
|
||||
logger.info(f"BlackWord USER {user_id} 触发 {punish_level} 级惩罚...")
|
||||
# 周期天数
|
||||
cycle_days = Config.get_config("black_word", "CYCLE_DAYS") or 7
|
||||
# 用户周期内触发punish_level级惩罚的次数
|
||||
user_count = await BlackWord.get_user_count(user_id, cycle_days, punish_level)
|
||||
# 获取最近一次的惩罚等级,将在此基础上增加
|
||||
punish_level = await BlackWord.get_user_punish_level(user_id, cycle_days) or punish_level
|
||||
# 容忍次数:List[int]
|
||||
tolerate_count = Config.get_config("black_word", "TOLERATE_COUNT")
|
||||
if not tolerate_count or len(tolerate_count) < 5:
|
||||
tolerate_count = [5, 2, 2, 2, 2]
|
||||
if punish_level == 1 and user_count > tolerate_count[punish_level - 1]:
|
||||
# 永久ban
|
||||
await _get_punish(1, user_id, group_id)
|
||||
await BlackWord.set_user_punish(user_id, "永久ban 删除好友", black_word)
|
||||
elif punish_level == 2 and user_count > tolerate_count[punish_level - 1]:
|
||||
# 删除好友
|
||||
await _get_punish(2, user_id, group_id)
|
||||
await BlackWord.set_user_punish(user_id, "删除好友", black_word)
|
||||
elif punish_level == 3 and user_count > tolerate_count[punish_level - 1]:
|
||||
# 永久ban
|
||||
ban_day = await _get_punish(3, user_id, group_id)
|
||||
await BlackWord.set_user_punish(user_id, f"ban {ban_day} 天", black_word)
|
||||
elif punish_level == 4 and user_count > tolerate_count[punish_level - 1]:
|
||||
# ban指定时长
|
||||
ban_time = await _get_punish(4, user_id, group_id)
|
||||
await BlackWord.set_user_punish(user_id, f"ban {ban_time} 分钟", black_word)
|
||||
elif punish_level == 5 and user_count > tolerate_count[punish_level - 1]:
|
||||
# 口头警告
|
||||
warning_result = await _get_punish(5, user_id, group_id)
|
||||
await BlackWord.set_user_punish(user_id, f"口头警告:{warning_result}", black_word)
|
||||
else:
|
||||
await BlackWord.set_user_punish(user_id, f"提示!", black_word)
|
||||
await send_msg(
|
||||
user_id,
|
||||
group_id,
|
||||
f"BlackWordChecker:该条发言已被记录,目前你在{cycle_days}天内的发表{punish_level}级"
|
||||
f"言论记录次数为:{user_count}次,请注意你的发言\n"
|
||||
f"* 如果你不清楚惩罚机制,请发送“惩罚机制” *",
|
||||
)
|
||||
|
||||
|
||||
async def _get_punish(
|
||||
id_: int, user_id: int, group_id: Optional[int] = None
|
||||
) -> Optional[Union[int, str]]:
|
||||
"""
|
||||
通过id_获取惩罚
|
||||
:param id_: id
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
"""
|
||||
bot = get_bot()
|
||||
# 忽略的群聊
|
||||
# _ignore_group = Config.get_config("black_word", "IGNORE_GROUP")
|
||||
# 处罚 id 4 ban 时间:int,List[int]
|
||||
ban_3_duration = Config.get_config("black_word", "BAN_3_DURATION")
|
||||
# 处罚 id 4 ban 时间:int,List[int]
|
||||
ban_4_duration = Config.get_config("black_word", "BAN_4_DURATION")
|
||||
# 口头警告内容
|
||||
warning_result = Config.get_config("black_word", "WARNING_RESULT")
|
||||
try:
|
||||
uname = (await GroupInfoUser.get_member_info(user_id, group_id)).user_name
|
||||
except AttributeError:
|
||||
uname = user_id
|
||||
# 永久ban
|
||||
if id_ == 1:
|
||||
if str(user_id) not in bot.config.superusers:
|
||||
await BanUser.ban(user_id, 10, 99999999)
|
||||
await send_msg(user_id, group_id, f"BlackWordChecker 永久ban USER {uname}({user_id})")
|
||||
logger.info(f"BlackWord 永久封禁 USER {user_id}...")
|
||||
# 删除好友(有的话
|
||||
elif id_ == 2:
|
||||
if str(user_id) not in bot.config.superusers:
|
||||
try:
|
||||
await bot.delete_friend(user_id=user_id)
|
||||
await send_msg(
|
||||
user_id, group_id, f"BlackWordChecker 删除好友 USER {uname}({user_id})"
|
||||
)
|
||||
logger.info(f"BlackWord 删除好友 {user_id}...")
|
||||
except ActionFailed:
|
||||
pass
|
||||
# 封禁用户指定时间,默认7天
|
||||
elif id_ == 3:
|
||||
if isinstance(ban_3_duration, list):
|
||||
ban_3_duration = random.randint(ban_3_duration[0], ban_3_duration[1])
|
||||
await BanUser.ban(user_id, 9, ban_4_duration * 60 * 60 * 24)
|
||||
await send_msg(
|
||||
user_id,
|
||||
group_id,
|
||||
f"BlackWordChecker 对用户 USER {uname}({user_id}) 进行封禁 {ban_3_duration} 天处罚。",
|
||||
)
|
||||
logger.info(f"BlackWord 封禁 USER {uname}({user_id}) {ban_3_duration} 天...")
|
||||
return ban_3_duration
|
||||
# 封禁用户指定时间,默认360分钟
|
||||
elif id_ == 4:
|
||||
if isinstance(ban_4_duration, list):
|
||||
ban_4_duration = random.randint(ban_4_duration[0], ban_4_duration[1])
|
||||
await BanUser.ban(user_id, 9, ban_4_duration * 60)
|
||||
await send_msg(
|
||||
user_id,
|
||||
group_id,
|
||||
f"BlackWordChecker 对用户 USER {uname}({user_id}) 进行封禁 {ban_4_duration} 分钟处罚。",
|
||||
)
|
||||
logger.info(f"BlackWord 封禁 USER {uname}({user_id}) {ban_4_duration} 分钟...")
|
||||
return ban_4_duration
|
||||
# 口头警告
|
||||
elif id_ == 5:
|
||||
if group_id:
|
||||
await bot.send_group_msg(group_id=group_id, message=warning_result)
|
||||
else:
|
||||
await bot.send_private_msg(user_id=user_id, message=warning_result)
|
||||
logger.info(f"BlackWord 口头警告 USER {user_id}")
|
||||
return warning_result
|
||||
return None
|
||||
|
||||
|
||||
async def send_msg(user_id: int, group_id: Optional[int], message: str):
|
||||
"""
|
||||
发送消息
|
||||
:param user_id: user_id
|
||||
:param group_id: group_id
|
||||
:param message: message
|
||||
"""
|
||||
bot = get_bot()
|
||||
if not user_id:
|
||||
user_id = int(list(bot.config.superusers)[0])
|
||||
if group_id:
|
||||
await bot.send_group_msg(group_id=group_id, message=message)
|
||||
else:
|
||||
await bot.send_private_msg(user_id=user_id, message=message)
|
||||
|
||||
|
||||
async def check_text(text: str) -> bool:
|
||||
"""
|
||||
ALAPI文本检测,检测输入违规
|
||||
:param text: 回复
|
||||
"""
|
||||
if not Config.get_config("alapi", "ALAPI_TOKEN"):
|
||||
return True
|
||||
params = {"token": Config.get_config("alapi", "ALAPI_TOKEN"), "text": text}
|
||||
try:
|
||||
data = (
|
||||
await AsyncHttpx.get(
|
||||
"https://v2.alapi.cn/api/censor/text", timeout=4, params=params
|
||||
)
|
||||
).json()
|
||||
if data["code"] == 200:
|
||||
return data["data"]["conclusion_type"] == 2
|
||||
except Exception as e:
|
||||
logger.error(f"检测违规文本错误...{type(e)}:{e}")
|
||||
return True
|
||||
|
||||
|
||||
black_word_manager = BlackWordManager(DATA_PATH / "black_word" / "black_word.json", DATA_PATH / "black_word" / "black_py.json")
|
||||
@@ -3,13 +3,13 @@ from configs.config import Config
|
||||
from bs4 import BeautifulSoup
|
||||
import platform
|
||||
|
||||
if platform.system() == "Windows":
|
||||
import asyncio
|
||||
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
# if platform.system() == "Windows":
|
||||
# import asyncio
|
||||
#
|
||||
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
|
||||
|
||||
url = "http://www.eclzz.world"
|
||||
url = "http://www.eclzz.mobi"
|
||||
|
||||
|
||||
async def get_bt_info(keyword: str, page: int):
|
||||
|
||||
@@ -14,9 +14,9 @@ import tarfile
|
||||
import shutil
|
||||
import os
|
||||
|
||||
if str(platform.system()).lower() == "windows":
|
||||
policy = asyncio.WindowsSelectorEventLoopPolicy()
|
||||
asyncio.set_event_loop_policy(policy)
|
||||
# if str(platform.system()).lower() == "windows":
|
||||
# policy = asyncio.WindowsSelectorEventLoopPolicy()
|
||||
# asyncio.set_event_loop_policy(policy)
|
||||
|
||||
|
||||
driver = nonebot.get_driver()
|
||||
@@ -73,6 +73,7 @@ async def check_update(bot: Bot) -> 'int, str':
|
||||
message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....",
|
||||
)
|
||||
logger.info(f"开始下载真寻最新版文件....")
|
||||
tar_gz_url = (await AsyncHttpx.get(tar_gz_url)).headers.get('Location')
|
||||
if await AsyncHttpx.download_file(tar_gz_url, zhenxun_latest_tar_gz):
|
||||
logger.info("下载真寻最新版文件完成....")
|
||||
error = await asyncio.get_event_loop().run_in_executor(
|
||||
|
||||
+24
-37
@@ -1,58 +1,34 @@
|
||||
from httpx import AsyncClient
|
||||
from datetime import datetime
|
||||
from nonebot.log import logger
|
||||
from nonebot.adapters.onebot.v11 import Bot
|
||||
from configs.config import NICKNAME
|
||||
from utils.http_utils import AsyncHttpx
|
||||
|
||||
|
||||
# 获取所有 Epic Game Store 促销游戏
|
||||
# 方法参考:RSSHub /epicgames 路由
|
||||
# https://github.com/DIYgod/RSSHub/blob/master/lib/routes/epicgames/index.js
|
||||
async def get_epic_game():
|
||||
# 现在没用 graphql 辣
|
||||
"""prv_graphql Code
|
||||
epic_url = "https://www.epicgames.com/store/backend/graphql-proxy"
|
||||
headers = {
|
||||
"Referer": "https://www.epicgames.com/store/zh-CN/",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
}
|
||||
data = {
|
||||
"query": "query searchStoreQuery($allowCountries: String, $category: String, $count: Int, $country: String!, $keywords: String, $locale: String, $namespace: String, $sortBy: String, $sortDir: String, $start: Int, $tag: String, $withPrice: Boolean = false, $withPromotions: Boolean = false) {\n Catalog {\n searchStore(allowCountries: $allowCountries, category: $category, count: $count, country: $country, keywords: $keywords, locale: $locale, namespace: $namespace, sortBy: $sortBy, sortDir: $sortDir, start: $start, tag: $tag) {\n elements {\n title\n id\n namespace\n description\n effectiveDate\n keyImages {\n type\n url\n }\n seller {\n id\n name\n }\n productSlug\n urlSlug\n url\n items {\n id\n namespace\n }\n customAttributes {\n key\n value\n }\n categories {\n path\n }\n price(country: $country) @include(if: $withPrice) {\n totalPrice {\n discountPrice\n originalPrice\n voucherDiscount\n discount\n currencyCode\n currencyInfo {\n decimals\n }\n fmtPrice(locale: $locale) {\n originalPrice\n discountPrice\n intermediatePrice\n }\n }\n lineOffers {\n appliedRules {\n id\n endDate\n discountSetting {\n discountType\n }\n }\n }\n }\n promotions(category: $category) @include(if: $withPromotions) {\n promotionalOffers {\n promotionalOffers {\n startDate\n endDate\n discountSetting {\n discountType\n discountPercentage\n }\n }\n }\n upcomingPromotionalOffers {\n promotionalOffers {\n startDate\n endDate\n discountSetting {\n discountType\n discountPercentage\n }\n }\n }\n }\n }\n paging {\n count\n total\n }\n }\n }\n}\n",
|
||||
"variables": {
|
||||
"allowCountries": "CN",
|
||||
"category": "freegames",
|
||||
"count": 1000,
|
||||
"country": "CN",
|
||||
"locale": "zh-CN",
|
||||
"sortBy": "effectiveDate",
|
||||
"sortDir": "asc",
|
||||
"withPrice": True,
|
||||
"withPromotions": True,
|
||||
},
|
||||
}
|
||||
"""
|
||||
|
||||
epic_url = "https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions?locale=zh-CN&country=CN&allowCountries=CN"
|
||||
headers = {
|
||||
"Referer": "https://www.epicgames.com/store/zh-CN/",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36",
|
||||
}
|
||||
async with AsyncClient(headers=headers) as client:
|
||||
try:
|
||||
res = await client.get(epic_url, timeout=10.0)
|
||||
res_json = res.json()
|
||||
games = res_json["data"]["Catalog"]["searchStore"]["elements"]
|
||||
return games
|
||||
except Exception as e:
|
||||
logger.error(str(e))
|
||||
return None
|
||||
try:
|
||||
res = await AsyncHttpx.get(epic_url, headers=headers, timeout=10)
|
||||
res_json = res.json()
|
||||
games = res_json["data"]["Catalog"]["searchStore"]["elements"]
|
||||
return games
|
||||
except Exception as e:
|
||||
logger.error(f"Epic 访问接口错误 {type(e)}:{e}")
|
||||
return None
|
||||
|
||||
|
||||
# 获取 Epic Game Store 免费游戏信息
|
||||
# 处理免费游戏的信息方法借鉴 pip 包 epicstore_api 示例
|
||||
# https://github.com/SD4RK/epicstore_api/blob/master/examples/free_games_example.py
|
||||
async def get_epic_free(bot: Bot, Type_Event: str):
|
||||
async def get_epic_free(bot: Bot, type_event: str):
|
||||
games = await get_epic_game()
|
||||
if not games:
|
||||
return "Epic 可能又抽风啦,请稍后再试(", 404
|
||||
@@ -81,7 +57,7 @@ async def get_epic_free(bot: Bot, Type_Event: str):
|
||||
end_date = datetime.fromisoformat(end_date_iso).strftime(
|
||||
"%b.%d %H:%M"
|
||||
)
|
||||
if Type_Event == "Group":
|
||||
if type_event == "Group":
|
||||
_message = "\n由 {} 公司发行的游戏 {} ({}) 在 UTC 时间 {} 即将推出免费游玩,预计截至 {}。".format(
|
||||
game_corp, game_name, game_price, start_date, end_date
|
||||
)
|
||||
@@ -101,8 +77,19 @@ async def get_epic_free(bot: Bot, Type_Event: str):
|
||||
msg_list.append(msg)
|
||||
else:
|
||||
for image in game["keyImages"]:
|
||||
if image["type"] == "Thumbnail":
|
||||
if (
|
||||
image.get("url")
|
||||
and not game_thumbnail
|
||||
and image["type"]
|
||||
in [
|
||||
"Thumbnail",
|
||||
"VaultOpened",
|
||||
"DieselStoreFrontWide",
|
||||
"OfferImageWide",
|
||||
]
|
||||
):
|
||||
game_thumbnail = image["url"]
|
||||
break
|
||||
for pair in game["customAttributes"]:
|
||||
if pair["key"] == "developerName":
|
||||
game_dev = pair["value"]
|
||||
@@ -127,7 +114,7 @@ async def get_epic_free(bot: Bot, Type_Event: str):
|
||||
game_url = "https://www.epicgames.com/store/zh-CN/p/{}".format(
|
||||
game_url_part
|
||||
)
|
||||
if Type_Event == "Group":
|
||||
if type_event == "Group":
|
||||
_message = "[CQ:image,file={}]\n\nFREE now :: {} ({})\n{}\n此游戏由 {} 开发、{} 发行,将在 UTC 时间 {} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{}\n".format(
|
||||
game_thumbnail,
|
||||
game_name,
|
||||
|
||||
+4
-3
@@ -9,6 +9,7 @@ from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from configs.config import Config
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from services.log import logger
|
||||
from configs.config import NICKNAME
|
||||
|
||||
|
||||
__zx_plugin_name__ = "复读"
|
||||
@@ -74,15 +75,15 @@ class Fudu:
|
||||
_fudu_list = Fudu()
|
||||
|
||||
|
||||
fudu = on_message(permission=GROUP, priority=9)
|
||||
fudu = on_message(permission=GROUP, priority=999)
|
||||
|
||||
|
||||
@fudu.handle()
|
||||
async def _(event: GroupMessageEvent):
|
||||
if event.is_tome():
|
||||
return
|
||||
if get_message_text(event.json()):
|
||||
if get_message_text(event.json()).find("@可爱的小真寻") != -1:
|
||||
if msg := get_message_text(event.json()):
|
||||
if msg.startswith(f"@可爱的{NICKNAME}"):
|
||||
await fudu.finish("复制粘贴的虚空艾特?", at_sender=True)
|
||||
img = get_message_img(event.json())
|
||||
msg = get_message_text(event.json())
|
||||
|
||||
@@ -35,7 +35,7 @@ Config.add_plugin_config(
|
||||
default_value=True,
|
||||
)
|
||||
|
||||
almanac = on_command("原神黄历", priority=5, block=True)
|
||||
almanac = on_command("原神黄历", priority=15, block=True)
|
||||
|
||||
|
||||
ALC_PATH = IMAGE_PATH / "genshin" / "alc"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import Tuple, Optional, List
|
||||
from configs.path_config import IMAGE_PATH, TEXT_PATH
|
||||
from PIL.Image import UnidentifiedImageError
|
||||
from utils.message_builder import image
|
||||
from services.log import logger
|
||||
from utils.image_utils import BuildImage
|
||||
@@ -137,7 +137,7 @@ async def download_resource_data(semaphore: Semaphore):
|
||||
asyncio.ensure_future(
|
||||
download_image(
|
||||
img_url,
|
||||
f"{icon_path}/{id_}.png",
|
||||
icon_path / f"{id_}.png",
|
||||
semaphore,
|
||||
True,
|
||||
)
|
||||
@@ -179,7 +179,7 @@ async def download_map_init(semaphore: Semaphore, flag: bool = False):
|
||||
map_url = _map_data["url"]
|
||||
await download_image(
|
||||
map_url,
|
||||
f"{map_path}/{idx}.png",
|
||||
map_path / f"{idx}.png",
|
||||
semaphore,
|
||||
force_flag=flag,
|
||||
)
|
||||
@@ -228,15 +228,14 @@ async def download_resource_type():
|
||||
except (TimeoutError, ConnectTimeout):
|
||||
logger.warning("下载原神资源类型数据超时....")
|
||||
except Exception as e:
|
||||
logger.error(f"载原神资源类型数据超时 {type(e)}:{e}")
|
||||
logger.error(f"载原神资源类型数据错误 {type(e)}:{e}")
|
||||
|
||||
|
||||
# 初始化资源图标
|
||||
def gen_icon(icon: str):
|
||||
def gen_icon(icon: Path):
|
||||
A = BuildImage(0, 0, background=f"{icon_path}/box.png")
|
||||
B = BuildImage(0, 0, background=f"{icon_path}/box_alpha.png")
|
||||
icon_ = icon_path / f"{icon}"
|
||||
icon_img = BuildImage(115, 115, background=icon_)
|
||||
icon_img = BuildImage(115, 115, background=icon)
|
||||
icon_img.circle()
|
||||
B.paste(icon_img, (17, 10), True)
|
||||
B.paste(A, alpha=True)
|
||||
@@ -247,22 +246,22 @@ def gen_icon(icon: str):
|
||||
# 下载图片
|
||||
async def download_image(
|
||||
img_url: str,
|
||||
path: str,
|
||||
path: Path,
|
||||
semaphore: Semaphore,
|
||||
gen_flag: bool = False,
|
||||
force_flag: bool = False,
|
||||
):
|
||||
async with semaphore:
|
||||
try:
|
||||
if not os.path.exists(path) or not is_valid or force_flag:
|
||||
if not path.exists() or not is_valid(path) or force_flag:
|
||||
if await AsyncHttpx.download_file(img_url, path, timeout=10):
|
||||
logger.info(f"下载原神资源图标:{img_url}")
|
||||
if gen_flag:
|
||||
gen_icon(path)
|
||||
else:
|
||||
logger.info(f"下载原神资源图标:{img_url} 失败,等待下次更新...")
|
||||
except UnidentifiedImageError:
|
||||
logger.warning(f"原神图片打开错误..已删除,等待下次更新... file: {path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"原神图片错误..已删除,等待下次更新... file: {path} {type(e)}:{e}")
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
|
||||
|
||||
@@ -254,10 +254,9 @@ class Genshin(db.Model):
|
||||
query = cls.query.where(cls.today_query_uid.contains(str(uid)))
|
||||
x = await query.gino.first()
|
||||
if x:
|
||||
await cls._add_query_uid(uid, uid)
|
||||
return x.cookie
|
||||
for u in [
|
||||
x for x in await cls.query.order_by(db.func.random()).gino.all() if x.cookie
|
||||
]:
|
||||
for u in await cls.query.where(cls.cookie != "").order_by(db.func.random()).gino.all():
|
||||
if not u.today_query_uid or len(u.today_query_uid[:-1].split()) < 30:
|
||||
await cls._add_query_uid(uid, u.uid)
|
||||
return u.cookie
|
||||
@@ -356,7 +355,7 @@ class Genshin(db.Model):
|
||||
"""
|
||||
query = cls.query.where(cls.uid == cookie_uid).with_for_update()
|
||||
user = await query.gino.first()
|
||||
await user.update(today_query_uid=cls.today_query_uid + f"{uid} ").apply()
|
||||
await user.update(today_query_uid=user.today_query_uid + f"{uid} ").apply()
|
||||
|
||||
@classmethod
|
||||
async def _get_user_data(
|
||||
|
||||
@@ -23,17 +23,17 @@ async def _():
|
||||
g_list = await Genshin.get_all_auto_sign_user()
|
||||
for u in g_list:
|
||||
if u.auto_sign_time:
|
||||
date = await Genshin.random_sign_time(u.uid)
|
||||
scheduler.add_job(
|
||||
_sign,
|
||||
"date",
|
||||
run_date=date.replace(microsecond=0),
|
||||
id=f"genshin_auto_sign_{u.uid}_{u.user_qq}_0",
|
||||
args=[u.user_qq, u.uid, 0],
|
||||
)
|
||||
logger.info(
|
||||
f"genshin_sign add_job:USER:{u.user_qq} UID:{u.uid} " f"{date} 原神自动签到"
|
||||
)
|
||||
if date := await Genshin.random_sign_time(u.uid):
|
||||
scheduler.add_job(
|
||||
_sign,
|
||||
"date",
|
||||
run_date=date.replace(microsecond=0),
|
||||
id=f"genshin_auto_sign_{u.uid}_{u.user_qq}_0",
|
||||
args=[u.user_qq, u.uid, 0],
|
||||
)
|
||||
logger.info(
|
||||
f"genshin_sign add_job:USER:{u.user_qq} UID:{u.uid} " f"{date} 原神自动签到"
|
||||
)
|
||||
|
||||
|
||||
def add_job(user_id: int, uid: int, date: datetime):
|
||||
|
||||
@@ -200,7 +200,7 @@ def _parse_data_and_draw(
|
||||
file_name = x["avatar_side_icon"].split("_")[-1]
|
||||
role_avatar = memo_path / "role_avatar" / file_name
|
||||
_ava_img = BuildImage(75, 75, background=role_avatar)
|
||||
_ava_img.circle()
|
||||
# _ava_img.circle()
|
||||
if x["status"] == "Finished":
|
||||
msg = "探索完成"
|
||||
font_color = (146, 188, 63)
|
||||
@@ -218,10 +218,10 @@ def _parse_data_and_draw(
|
||||
a_circle.circle()
|
||||
b_circle = BuildImage(47, 47)
|
||||
b_circle.circle()
|
||||
a_circle.paste(b_circle, (4, 4), alpha=True)
|
||||
_circle_bk.paste(a_circle, (4, 4), alpha=True)
|
||||
a_circle.paste(b_circle, (4, 4), True)
|
||||
_circle_bk.paste(a_circle, (4, 4), True)
|
||||
|
||||
_bk.paste(_circle_bk, (25, 0), True, center_type="by_height")
|
||||
_bk.paste(_circle_bk, (25, 0), True, "by_height")
|
||||
_bk.paste(_ava_img, (19, -13), True)
|
||||
_bk.text((100, 0), msg, font_color, "by_height")
|
||||
_bk.circle_corner(20)
|
||||
|
||||
@@ -128,7 +128,7 @@ async def get_character(
|
||||
) -> Optional[dict]:
|
||||
try:
|
||||
req = await AsyncHttpx.post(
|
||||
url="https://api-takumi.mihoyo.com/game_record/app/genshin/api/character",
|
||||
url="https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/character",
|
||||
headers={
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"DS": get_ds(
|
||||
@@ -232,7 +232,7 @@ async def get_mys_data(uid: str, mys_id: Optional[str]) -> Optional[List[Dict]]:
|
||||
if mys_id:
|
||||
try:
|
||||
req = await AsyncHttpx.get(
|
||||
url=f"https://api-takumi.mihoyo.com/game_record/card/wapi/getGameRecordCard?uid={mys_id}",
|
||||
url=f"https://api-takumi-record.mihoyo.com/game_record/card/wapi/getGameRecordCard?uid={mys_id}",
|
||||
headers={
|
||||
"DS": get_ds(f"uid={mys_id}"),
|
||||
"x-rpc-app_version": Config.get_config("genshin", "mhyVersion"),
|
||||
|
||||
@@ -296,9 +296,12 @@ def get_country_data_image(world_data_dict: Dict) -> BuildImage:
|
||||
画出国家探索供奉等图像
|
||||
:param world_data_dict: 国家数据字典
|
||||
"""
|
||||
region = BuildImage(790, 267 * len(world_data_dict), color="#F9F6F2")
|
||||
# 层岩巨渊 和 地下矿区 算一个
|
||||
region = BuildImage(790, 267 * (len(world_data_dict) - 1), color="#F9F6F2")
|
||||
height = 0
|
||||
for country in ["蒙德", "龙脊雪山", "璃月", "稻妻", "渊下宫"]:
|
||||
for country in ["蒙德", "龙脊雪山", "璃月", "层岩巨渊", "稻妻", "渊下宫"]:
|
||||
if not world_data_dict.get(country):
|
||||
continue
|
||||
x = BuildImage(790, 250, color="#3A4467")
|
||||
logo = BuildImage(180, 180, background=image_path / "logo" / f"{country}.png")
|
||||
tmp_bk = BuildImage(770, 230, color="#606779")
|
||||
@@ -320,6 +323,25 @@ def get_country_data_image(world_data_dict: Dict) -> BuildImage:
|
||||
f"Lv.{world_data_dict[country]['level']}",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
elif country in ["层岩巨渊"]:
|
||||
content_bk.text((300, 20), "层岩巨渊探索", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
(570, 20),
|
||||
f"{world_data_dict['层岩巨渊']['exploration_percentage'] / 10}%",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
content_bk.text((300, 85), "地下矿区探索", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
(570, 85),
|
||||
f"{world_data_dict['层岩巨渊·地下矿区']['exploration_percentage'] / 10}%",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
content_bk.text((300, 150), "流明石触媒", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
(570, 150),
|
||||
f"LV.{world_data_dict['层岩巨渊·地下矿区']['offerings'][0]['level']}",
|
||||
fill=(255, 255, 255),
|
||||
)
|
||||
elif country in ["龙脊雪山"]:
|
||||
content_bk.text((300, 40), "探索", fill=(239, 211, 114))
|
||||
content_bk.text(
|
||||
|
||||
@@ -55,7 +55,7 @@ async def _(event: MessageEvent, cmd: Tuple[str, ...] = Command()):
|
||||
scheduler.remove_job(f"genshin_resin_remind_{uid}_{event.user_id}")
|
||||
except JobLookupError:
|
||||
pass
|
||||
if cmd == "开":
|
||||
if cmd[0] == "开":
|
||||
await Genshin.set_resin_remind(uid, True)
|
||||
add_job(event.user_id, uid)
|
||||
logger.info(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from nonebot.adapters.onebot.v11 import ActionFailed
|
||||
|
||||
from utils.utils import get_bot, scheduler
|
||||
from utils.message_builder import at
|
||||
from models.group_member_info import GroupInfoUser
|
||||
@@ -20,6 +22,9 @@ driver: Driver = nonebot.get_driver()
|
||||
get_memo = require("query_memo").get_memo
|
||||
|
||||
|
||||
global_map = {}
|
||||
|
||||
|
||||
class UserManager:
|
||||
def __init__(self, max_error_count: int = 3):
|
||||
self._data = []
|
||||
@@ -146,8 +151,8 @@ async def _remind(user_id: int, uid: str):
|
||||
if current_resin < max_resin:
|
||||
user_manager.remove(uid)
|
||||
user_manager.remove_overflow(uid)
|
||||
if max_resin - 40 <= current_resin <= max_resin - 20:
|
||||
next_time = now + timedelta(minutes=(max_resin - 20 - current_resin) * 8, seconds=10)
|
||||
if max_resin - 40 < current_resin <= max_resin - 20:
|
||||
next_time = now + timedelta(minutes=(max_resin - 20 - current_resin + 1) * 8, seconds=10)
|
||||
elif current_resin < max_resin:
|
||||
next_time = now + timedelta(minutes=(max_resin - current_resin) * 8, seconds=10)
|
||||
elif current_resin == max_resin:
|
||||
@@ -175,10 +180,13 @@ async def _remind(user_id: int, uid: str):
|
||||
group_list = await GroupInfoUser.get_user_all_group(user_id)
|
||||
if group_list:
|
||||
group_id = group_list[0]
|
||||
await bot.send_group_msg(
|
||||
group_id=group_id,
|
||||
message=at(user_id) + msg
|
||||
)
|
||||
try:
|
||||
await bot.send_group_msg(
|
||||
group_id=group_id,
|
||||
message=at(user_id) + msg
|
||||
)
|
||||
except ActionFailed as e:
|
||||
logger.error(f"树脂提醒推送发生错误 {type(e)}:{e}")
|
||||
if not next_time:
|
||||
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)
|
||||
@@ -189,6 +197,7 @@ async def _remind(user_id: int, uid: str):
|
||||
user_manager.remove_error_count(uid)
|
||||
await Genshin.set_user_resin_recovery_time(int(uid), next_time)
|
||||
scheduler.add_job(
|
||||
_remind,
|
||||
_remind,
|
||||
"date",
|
||||
run_date=next_time,
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
from nonebot import on_message
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from .data_source import cancel_all_notice, save_data, get_data, set_data_value
|
||||
from services.log import logger
|
||||
import time
|
||||
|
||||
|
||||
__zx_plugin_name__ = "群聊最后聊天时间记录 [Hidden]"
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
|
||||
|
||||
last_chat = on_message(priority=1, block=False, permission=GROUP)
|
||||
|
||||
|
||||
@last_chat.handle()
|
||||
async def _(event: GroupMessageEvent):
|
||||
time_data = await get_data()
|
||||
set_data_value(event.group_id, time.time())
|
||||
if event.group_id in time_data["_group"]:
|
||||
time_data["_group"].remove(event.group_id)
|
||||
set_data_value("_group", time_data["_group"])
|
||||
for key in time_data.keys():
|
||||
if key not in ["check_time", "_group"]:
|
||||
if key not in time_data["_group"]:
|
||||
if time.time() - time_data[key] > 60 * 60 * 36:
|
||||
await cancel_all_notice(key)
|
||||
time_data["_group"].append(key)
|
||||
set_data_value("_group", time_data["_group"])
|
||||
logger.info(f"GROUP {event.group_id} 因群内发言时间大于36小时被取消全部通知")
|
||||
if time.time() - time_data["check_time"] > 60 * 60 * 1:
|
||||
set_data_value("check_time", time.time())
|
||||
save_data()
|
||||
@@ -1,67 +0,0 @@
|
||||
from configs.path_config import DATA_PATH
|
||||
from utils.utils import get_bot
|
||||
from datetime import datetime
|
||||
import time
|
||||
from services.log import logger
|
||||
from utils.manager import group_manager
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
time_data = {}
|
||||
|
||||
|
||||
async def init():
|
||||
global time_data
|
||||
bot = get_bot()
|
||||
gl = await bot.get_group_list()
|
||||
gl = [g["group_id"] for g in gl]
|
||||
data = read_data("group_last_chat_time.json")
|
||||
for g in gl:
|
||||
if not data.get(g):
|
||||
time_data[g] = time.time()
|
||||
if not time_data.get("check_time"):
|
||||
time_data["check_time"] = time.time()
|
||||
if not time_data.get("_group"):
|
||||
time_data["_group"] = []
|
||||
save_data()
|
||||
return time_data
|
||||
|
||||
|
||||
def read_data(file_name: str):
|
||||
try:
|
||||
with open(DATA_PATH / file_name, "r", encoding="utf8") as f:
|
||||
return json.load(f)
|
||||
except (ValueError, FileNotFoundError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_data():
|
||||
with open(DATA_PATH / "group_last_chat_time.json", "w") as f:
|
||||
json.dump(time_data, f, indent=4)
|
||||
logger.info(
|
||||
f'自动存储 group_last_chat_time.json 时间:{str(datetime.now()).split(".")[0]}'
|
||||
)
|
||||
|
||||
|
||||
# 取消全部通知
|
||||
async def cancel_all_notice(group_id):
|
||||
group_id = int(group_id)
|
||||
for command in group_manager.get_task_data():
|
||||
if await group_manager.check_group_task_status(group_id, command):
|
||||
await group_manager.close_group_task(group_id, command)
|
||||
logger.info(f"关闭了 {group_id} 群的全部通知")
|
||||
|
||||
|
||||
async def get_data():
|
||||
global time_data
|
||||
if not time_data:
|
||||
time_data = await init()
|
||||
return time_data
|
||||
|
||||
|
||||
def set_data_value(key, value):
|
||||
global time_data
|
||||
time_data[key] = value
|
||||
+14
-16
@@ -1,8 +1,7 @@
|
||||
from nonebot import on_message, on_command
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from utils.utils import is_number, get_message_img
|
||||
from nonebot.typing import T_State
|
||||
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 utils.image_utils import get_img_hash
|
||||
@@ -10,7 +9,7 @@ from services.log import logger
|
||||
from configs.config import NICKNAME, Config
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from nonebot.params import CommandArg, Command
|
||||
from typing import Tuple
|
||||
from typing import Tuple, Dict, Any
|
||||
import time
|
||||
|
||||
try:
|
||||
@@ -57,7 +56,7 @@ mute_setting = on_command(
|
||||
)
|
||||
|
||||
|
||||
def get_data():
|
||||
def get_data() -> Dict[Any, Any]:
|
||||
try:
|
||||
with open(DATA_PATH / "group_mute_data.json", "r", encoding="utf8") as f:
|
||||
data = json.load(f)
|
||||
@@ -72,7 +71,7 @@ def save_data():
|
||||
json.dump(mute_data, f, indent=4)
|
||||
|
||||
|
||||
async def download_img_and_hash(url, group_id):
|
||||
async def download_img_and_hash(url, group_id) -> str:
|
||||
if await AsyncHttpx.download_file(
|
||||
url, TEMP_PATH / f"mute_{group_id}_img.jpg"
|
||||
):
|
||||
@@ -85,9 +84,9 @@ mute_data = get_data()
|
||||
|
||||
|
||||
@mute.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
async def _(bot: Bot, event: GroupMessageEvent):
|
||||
group_id = str(event.group_id)
|
||||
msg = arg.extract_plain_text().strip()
|
||||
msg = get_message_text(event.json())
|
||||
img_list = get_message_img(event.json())
|
||||
img_hash = ""
|
||||
for img in img_list:
|
||||
@@ -102,8 +101,6 @@ async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command()
|
||||
if not mute_dict.get(event.user_id):
|
||||
mute_dict[event.user_id] = {"time": time.time(), "count": 1, "msg": msg}
|
||||
else:
|
||||
if cmd or not msg:
|
||||
return
|
||||
if msg and msg.find(mute_dict[event.user_id]["msg"]) != -1:
|
||||
mute_dict[event.user_id]["count"] += 1
|
||||
else:
|
||||
@@ -123,7 +120,7 @@ async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command()
|
||||
await bot.set_group_ban(
|
||||
group_id=event.group_id,
|
||||
user_id=event.user_id,
|
||||
duration=mute_data[group_id]["duration"],
|
||||
duration=mute_data[group_id]["duration"] * 60,
|
||||
)
|
||||
await mute.send(f"检测到恶意刷屏,{NICKNAME}要把你关进小黑屋!", at_sender=True)
|
||||
mute_dict[event.user_id]["count"] = 0
|
||||
@@ -137,27 +134,28 @@ async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command()
|
||||
|
||||
@mute_setting.handle()
|
||||
async def _(event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
global mute_data
|
||||
group_id = str(event.group_id)
|
||||
if not mute_data.get(group_id):
|
||||
mute_data[group_id] = {"count": 10, "time": 7, "duration": 0}
|
||||
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()
|
||||
if cmd[0] == "刷屏检测设置":
|
||||
await mute_setting.finish(
|
||||
f'最大次数:{mute_data[group_id]["count"]} 次\n'
|
||||
f'规定时间:{mute_data[group_id]["time"]} 秒\n'
|
||||
f'禁言时长:{mute_data[group_id]["duration"] / 60} 分钟\n'
|
||||
f'禁言时长:{mute_data[group_id]["duration"]:.2f} 分钟\n'
|
||||
f"【在规定时间内发送相同消息超过最大次数则禁言\n当禁言时长为0时关闭此功能】"
|
||||
)
|
||||
if not is_number(msg):
|
||||
await mute.finish("设置的参数必须是数字啊!", at_sender=True)
|
||||
if cmd[0] == "设置检测时间":
|
||||
if cmd[0] == "设置刷屏检测时间":
|
||||
mute_data[group_id]["time"] = int(msg)
|
||||
msg += "秒"
|
||||
if cmd[0] == "设置检测次数":
|
||||
if cmd[0] == "设置刷屏检测次数":
|
||||
mute_data[group_id]["count"] = int(msg)
|
||||
msg += " 次"
|
||||
if cmd[0] == "设置禁言时长":
|
||||
mute_data[group_id]["duration"] = int(msg) * 60
|
||||
if cmd[0] == "设置刷屏禁言时长":
|
||||
mute_data[group_id]["duration"] = int(msg)
|
||||
msg += " 分钟"
|
||||
await mute_setting.send(f'刷屏检测:{cmd[0]}为 {msg}')
|
||||
logger.info(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Type
|
||||
from typing import Type, Tuple, Any
|
||||
from nonebot import on_command
|
||||
from nonebot.matcher import Matcher
|
||||
from utils.utils import scheduler, is_number
|
||||
@@ -9,7 +9,7 @@ from nonebot.permission import SUPERUSER
|
||||
import random
|
||||
from nonebot.plugin import MatcherGroup
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from nonebot.params import CommandArg
|
||||
from nonebot.params import CommandArg, RegexGroup
|
||||
from .open_cases_c import (
|
||||
open_case,
|
||||
total_open_statistics,
|
||||
@@ -145,12 +145,12 @@ async def _(event: GroupMessageEvent):
|
||||
)
|
||||
|
||||
|
||||
open_shilian: Type[Matcher] = cases_matcher_group.on_regex("(.*)连开箱(.*?)")
|
||||
open_shilian: Type[Matcher] = cases_matcher_group.on_regex("(.*)连开箱(.*)?")
|
||||
|
||||
|
||||
@open_shilian.handle()
|
||||
async def _(event: GroupMessageEvent, state: T_State):
|
||||
num = state["_matched_groups"][0].strip()
|
||||
async def _(event: GroupMessageEvent, state: T_State, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
num, case_name = reg_group
|
||||
if is_number(num) or num_dict.get(num):
|
||||
try:
|
||||
num = num_dict[num]
|
||||
@@ -162,7 +162,6 @@ async def _(event: GroupMessageEvent, state: T_State):
|
||||
await open_shilian.finish("再负开箱就扣你明天开箱数了!", at_sender=True)
|
||||
else:
|
||||
await open_shilian.finish("必须要是数字切不要超过30啊笨蛋!中文也可!", at_sender=True)
|
||||
case_name = state["_matched_groups"][1].strip()
|
||||
case_name = case_name.replace("武器箱", "").strip()
|
||||
if not case_name:
|
||||
case_name = random.choice(cases_name)
|
||||
@@ -212,16 +211,16 @@ update_price = on_command("更新开箱价格", priority=1, permission=SUPERUSER
|
||||
|
||||
|
||||
@update_price.handle()
|
||||
async def _( event: MessageEvent):
|
||||
await update_price.send(await util_get_buff_price(str(event.get_message())))
|
||||
async def _(event: MessageEvent, arg: Message = CommandArg()):
|
||||
await update_price.send(await util_get_buff_price(arg.extract_plain_text().strip()))
|
||||
|
||||
|
||||
update_img = on_command("更新开箱图片", priority=1, permission=SUPERUSER, block=True)
|
||||
|
||||
|
||||
@update_img.handle()
|
||||
async def _(event: MessageEvent):
|
||||
await update_img.send(await util_get_buff_img(str(event.get_message())))
|
||||
async def _(event: MessageEvent, arg: Message = CommandArg()):
|
||||
await update_img.send(await util_get_buff_img(str(arg.extract_plain_text().strip())))
|
||||
|
||||
|
||||
# 重置开箱
|
||||
|
||||
+166
-171
@@ -1,171 +1,166 @@
|
||||
from nonebot import on_message
|
||||
from services.log import logger
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from utils.utils import get_message_json, get_local_proxy, is_number, get_message_text
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from bilibili_api import video
|
||||
from utils.message_builder import image
|
||||
from nonebot.adapters.onebot.v11.exception import ActionFailed
|
||||
from utils.image_utils import BuildImage
|
||||
from utils.browser import get_browser
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from configs.config import Config
|
||||
from utils.user_agent import get_user_agent
|
||||
import aiohttp
|
||||
import asyncio
|
||||
import time
|
||||
from bilibili_api import settings
|
||||
import ujson as json
|
||||
|
||||
|
||||
__zx_plugin_name__ = "B站转发解析"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
B站转发解析,解析b站分享信息,支持bv,bilibili链接,b站手机端转发卡片,cv,b23.tv,且5分钟内不解析相同url
|
||||
""".strip()
|
||||
__plugin_des__ = "B站转发解析"
|
||||
__plugin_type__ = ("其他",)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_task__ = {"bilibili_parse": "b站转发解析"}
|
||||
Config.add_plugin_config(
|
||||
"_task",
|
||||
"DEFAULT_BILIBILI_PARSE",
|
||||
True,
|
||||
help_="被动 B站转发解析 进群默认开关状态",
|
||||
default_value=True,
|
||||
)
|
||||
|
||||
|
||||
if get_local_proxy():
|
||||
settings.proxy = get_local_proxy()
|
||||
|
||||
parse_bilibili_json = on_message(priority=1, permission=GROUP, block=False)
|
||||
|
||||
_tmp = {}
|
||||
|
||||
|
||||
@parse_bilibili_json.handle()
|
||||
async def _(event: GroupMessageEvent):
|
||||
vd_info = None
|
||||
url = None
|
||||
if get_message_json(event.json()):
|
||||
try:
|
||||
data = json.loads(get_message_json(event.json())[0]["data"])
|
||||
except (IndexError, KeyError):
|
||||
data = None
|
||||
if data:
|
||||
# 转发视频
|
||||
if data.get("desc") == "哔哩哔哩":
|
||||
async with aiohttp.ClientSession(
|
||||
headers=get_user_agent()
|
||||
) as session:
|
||||
async with session.get(
|
||||
data["meta"]["detail_1"]["qqdocurl"],
|
||||
proxy=get_local_proxy(),
|
||||
timeout=7,
|
||||
) as response:
|
||||
url = str(response.url).split("?")[0]
|
||||
bvid = url.split("/")[-1]
|
||||
vd_info = await video.Video(bvid=bvid).get_info()
|
||||
# response = await AsyncHttpx.get(
|
||||
# data["meta"]["detail_1"]["qqdocurl"], timeout=7
|
||||
# )
|
||||
# url = str(response.url).split("?")[0]
|
||||
# bvid = url.split("/")[-1]
|
||||
# vd_info = await video.Video(bvid=bvid).get_info()
|
||||
# 转发专栏
|
||||
if (
|
||||
data.get("meta")
|
||||
and data["meta"].get("news")
|
||||
and data["meta"]["news"].get("desc") == "哔哩哔哩专栏"
|
||||
):
|
||||
url = data["meta"]["news"]["jumpUrl"]
|
||||
page = None
|
||||
try:
|
||||
browser = await get_browser()
|
||||
if not browser:
|
||||
return
|
||||
page = await browser.new_page(
|
||||
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
||||
" (KHTML, like Gecko) Chrome/93.0.4530.0 Safari/537.36"
|
||||
)
|
||||
await page.goto(url, wait_until="networkidle", timeout=10000)
|
||||
await page.set_viewport_size({"width": 2560, "height": 1080})
|
||||
await page.click("#app > div")
|
||||
div = await page.query_selector("#app > div")
|
||||
await div.screenshot(
|
||||
path=f"{IMAGE_PATH}/temp/cv_{event.user_id}.png",
|
||||
timeout=100000,
|
||||
)
|
||||
await asyncio.get_event_loop().run_in_executor(
|
||||
None, resize, f"{IMAGE_PATH}/temp/cv_{event.user_id}.png"
|
||||
)
|
||||
await parse_bilibili_json.send(
|
||||
"[[_task|bilibili_parse]]" + image(f"cv_{event.user_id}.png", "temp")
|
||||
)
|
||||
await page.close()
|
||||
logger.info(
|
||||
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"尝试解析bilibili专栏 {url} 失败 {type(e)}:{e}")
|
||||
if page:
|
||||
await page.close()
|
||||
return
|
||||
# BV
|
||||
if msg := get_message_text(event.json()):
|
||||
if "BV" in msg:
|
||||
index = msg.find("BV")
|
||||
if len(msg[index + 2 :]) >= 10:
|
||||
msg = msg[index : index + 12]
|
||||
url = f"https://www.bilibili.com/video/{msg}"
|
||||
vd_info = await video.Video(bvid=msg).get_info()
|
||||
elif "av" in msg:
|
||||
index = msg.find("av")
|
||||
if len(msg[index + 2 :]) >= 9:
|
||||
msg = msg[index + 2 : index + 11]
|
||||
if is_number(msg):
|
||||
url = f"https://www.bilibili.com/video/{msg}"
|
||||
vd_info = await video.Video(aid=int(msg)).get_info()
|
||||
elif "https://b23.tv" in msg:
|
||||
url = "https://" + msg[msg.find("b23.tv") : msg.find("b23.tv") + 13]
|
||||
res = await AsyncHttpx.get(url, timeout=7)
|
||||
url = str(res.url).split("?")[0]
|
||||
bvid = url.split("/")[-1]
|
||||
vd_info = await video.Video(bvid=bvid).get_info()
|
||||
if vd_info:
|
||||
if (
|
||||
url in _tmp.keys() and time.time() - _tmp[url] > 30
|
||||
) or url not in _tmp.keys():
|
||||
_tmp[url] = time.time()
|
||||
aid = vd_info["aid"]
|
||||
title = vd_info["title"]
|
||||
author = vd_info["owner"]["name"]
|
||||
reply = vd_info["stat"]["reply"] # 回复
|
||||
favorite = vd_info["stat"]["favorite"] # 收藏
|
||||
coin = vd_info["stat"]["coin"] # 投币
|
||||
# like = vd_info['stat']['like'] # 点赞
|
||||
# danmu = vd_info['stat']['danmaku'] # 弹幕
|
||||
date = time.strftime("%Y-%m-%d", time.localtime(vd_info["ctime"]))
|
||||
try:
|
||||
await parse_bilibili_json.send(
|
||||
"[[_task|bilibili_parse]]" +
|
||||
image(vd_info["pic"]) + f"\nav{aid}\n标题:{title}\n"
|
||||
f"UP:{author}\n"
|
||||
f"上传日期:{date}\n"
|
||||
f"回复:{reply},收藏:{favorite},投币:{coin}\n"
|
||||
f"{url}"
|
||||
)
|
||||
except ActionFailed:
|
||||
logger.warning(f"{event.group_id} 发送bilibili解析失败")
|
||||
else:
|
||||
logger.info(
|
||||
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
|
||||
)
|
||||
|
||||
|
||||
def resize(path: str):
|
||||
A = BuildImage(0, 0, background=path, ratio=0.5)
|
||||
A.save(path)
|
||||
# from nonebot import on_message
|
||||
# from services.log import logger
|
||||
# from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
# from utils.utils import get_message_json, get_local_proxy, is_number, get_message_text
|
||||
# from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
# from utils.message_builder import image
|
||||
# from nonebot.adapters.onebot.v11.exception import ActionFailed
|
||||
# from utils.image_utils import BuildImage
|
||||
# from utils.browser import get_browser
|
||||
# from configs.path_config import IMAGE_PATH
|
||||
# from utils.http_utils import AsyncHttpx
|
||||
# from configs.config import Config
|
||||
# from utils.user_agent import get_user_agent
|
||||
# import aiohttp
|
||||
# import asyncio
|
||||
# import time
|
||||
# import ujson as json
|
||||
#
|
||||
#
|
||||
# __zx_plugin_name__ = "B站转发解析"
|
||||
# __plugin_usage__ = """
|
||||
# usage:
|
||||
# B站转发解析,解析b站分享信息,支持bv,bilibili链接,b站手机端转发卡片,cv,b23.tv,且5分钟内不解析相同url
|
||||
# """.strip()
|
||||
# __plugin_des__ = "B站转发解析"
|
||||
# __plugin_type__ = ("其他",)
|
||||
# __plugin_version__ = 0.1
|
||||
# __plugin_author__ = "HibiKier"
|
||||
# __plugin_task__ = {"bilibili_parse": "b站转发解析"}
|
||||
# Config.add_plugin_config(
|
||||
# "_task",
|
||||
# "DEFAULT_BILIBILI_PARSE",
|
||||
# True,
|
||||
# help_="被动 B站转发解析 进群默认开关状态",
|
||||
# default_value=True,
|
||||
# )
|
||||
#
|
||||
#
|
||||
# parse_bilibili_json = on_message(priority=1, permission=GROUP, block=False)
|
||||
#
|
||||
# _tmp = {}
|
||||
#
|
||||
#
|
||||
# @parse_bilibili_json.handle()
|
||||
# async def _(event: GroupMessageEvent):
|
||||
# vd_info = None
|
||||
# url = None
|
||||
# if get_message_json(event.json()):
|
||||
# try:
|
||||
# data = json.loads(get_message_json(event.json())[0]["data"])
|
||||
# except (IndexError, KeyError):
|
||||
# data = None
|
||||
# if data:
|
||||
# # 转发视频
|
||||
# if data.get("desc") == "哔哩哔哩":
|
||||
# async with aiohttp.ClientSession(
|
||||
# headers=get_user_agent()
|
||||
# ) as session:
|
||||
# async with session.get(
|
||||
# data["meta"]["detail_1"]["qqdocurl"],
|
||||
# proxy=get_local_proxy(),
|
||||
# timeout=7,
|
||||
# ) as response:
|
||||
# url = str(response.url).split("?")[0]
|
||||
# bvid = url.split("/")[-1]
|
||||
# vd_info = await video.Video(bvid=bvid).get_info()
|
||||
# # response = await AsyncHttpx.get(
|
||||
# # data["meta"]["detail_1"]["qqdocurl"], timeout=7
|
||||
# # )
|
||||
# # url = str(response.url).split("?")[0]
|
||||
# # bvid = url.split("/")[-1]
|
||||
# # vd_info = await video.Video(bvid=bvid).get_info()
|
||||
# # 转发专栏
|
||||
# if (
|
||||
# data.get("meta")
|
||||
# and data["meta"].get("news")
|
||||
# and data["meta"]["news"].get("desc") == "哔哩哔哩专栏"
|
||||
# ):
|
||||
# url = data["meta"]["news"]["jumpUrl"]
|
||||
# page = None
|
||||
# try:
|
||||
# browser = await get_browser()
|
||||
# if not browser:
|
||||
# return
|
||||
# page = await browser.new_page(
|
||||
# user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
||||
# " (KHTML, like Gecko) Chrome/93.0.4530.0 Safari/537.36"
|
||||
# )
|
||||
# await page.goto(url, wait_until="networkidle", timeout=10000)
|
||||
# await page.set_viewport_size({"width": 2560, "height": 1080})
|
||||
# await page.click("#app > div")
|
||||
# div = await page.query_selector("#app > div")
|
||||
# await div.screenshot(
|
||||
# path=f"{IMAGE_PATH}/temp/cv_{event.user_id}.png",
|
||||
# timeout=100000,
|
||||
# )
|
||||
# await asyncio.get_event_loop().run_in_executor(
|
||||
# None, resize, f"{IMAGE_PATH}/temp/cv_{event.user_id}.png"
|
||||
# )
|
||||
# await parse_bilibili_json.send(
|
||||
# "[[_task|bilibili_parse]]" + image(f"cv_{event.user_id}.png", "temp")
|
||||
# )
|
||||
# await page.close()
|
||||
# logger.info(
|
||||
# f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
|
||||
# )
|
||||
# except Exception as e:
|
||||
# logger.error(f"尝试解析bilibili专栏 {url} 失败 {type(e)}:{e}")
|
||||
# if page:
|
||||
# await page.close()
|
||||
# return
|
||||
# # BV
|
||||
# if msg := get_message_text(event.json()):
|
||||
# if "BV" in msg:
|
||||
# index = msg.find("BV")
|
||||
# if len(msg[index + 2 :]) >= 10:
|
||||
# msg = msg[index : index + 12]
|
||||
# url = f"https://www.bilibili.com/video/{msg}"
|
||||
# vd_info = await video.Video(bvid=msg).get_info()
|
||||
# elif "av" in msg:
|
||||
# index = msg.find("av")
|
||||
# if len(msg[index + 2 :]) >= 9:
|
||||
# msg = msg[index + 2 : index + 11]
|
||||
# if is_number(msg):
|
||||
# url = f"https://www.bilibili.com/video/{msg}"
|
||||
# vd_info = await video.Video(aid=int(msg)).get_info()
|
||||
# elif "https://b23.tv" in msg:
|
||||
# url = "https://" + msg[msg.find("b23.tv") : msg.find("b23.tv") + 13]
|
||||
# res = await AsyncHttpx.get(url, timeout=7)
|
||||
# url = str(res.url).split("?")[0]
|
||||
# bvid = url.split("/")[-1]
|
||||
# vd_info = await video.Video(bvid=bvid).get_info()
|
||||
# if vd_info:
|
||||
# if (
|
||||
# url in _tmp.keys() and time.time() - _tmp[url] > 30
|
||||
# ) or url not in _tmp.keys():
|
||||
# _tmp[url] = time.time()
|
||||
# aid = vd_info["aid"]
|
||||
# title = vd_info["title"]
|
||||
# author = vd_info["owner"]["name"]
|
||||
# reply = vd_info["stat"]["reply"] # 回复
|
||||
# favorite = vd_info["stat"]["favorite"] # 收藏
|
||||
# coin = vd_info["stat"]["coin"] # 投币
|
||||
# # like = vd_info['stat']['like'] # 点赞
|
||||
# # danmu = vd_info['stat']['danmaku'] # 弹幕
|
||||
# date = time.strftime("%Y-%m-%d", time.localtime(vd_info["ctime"]))
|
||||
# try:
|
||||
# await parse_bilibili_json.send(
|
||||
# "[[_task|bilibili_parse]]" +
|
||||
# image(vd_info["pic"]) + f"\nav{aid}\n标题:{title}\n"
|
||||
# f"UP:{author}\n"
|
||||
# f"上传日期:{date}\n"
|
||||
# f"回复:{reply},收藏:{favorite},投币:{coin}\n"
|
||||
# f"{url}"
|
||||
# )
|
||||
# except ActionFailed:
|
||||
# logger.warning(f"{event.group_id} 发送bilibili解析失败")
|
||||
# else:
|
||||
# logger.info(
|
||||
# f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
|
||||
# )
|
||||
#
|
||||
#
|
||||
# def resize(path: str):
|
||||
# A = BuildImage(0, 0, background=path, ratio=0.5)
|
||||
# A.save(path)
|
||||
|
||||
+117
-100
@@ -1,100 +1,117 @@
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from nonebot import on_command
|
||||
from nonebot.adapters.onebot.v11 import MessageEvent, Message, GroupMessageEvent
|
||||
from nonebot.typing import T_State
|
||||
from configs.path_config import TEMP_PATH
|
||||
from services.log import logger
|
||||
from utils.message_builder import image
|
||||
from utils.utils import is_number
|
||||
from utils.manager import withdraw_message_manager
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from nonebot.params import CommandArg, Arg
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
__zx_plugin_name__ = "pid搜索"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
通过 pid 搜索图片
|
||||
指令:
|
||||
p搜 [pid]
|
||||
""".strip()
|
||||
__plugin_des__ = "通过 pid 搜索图片"
|
||||
__plugin_cmd__ = ["p搜 [pid]"]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
"limit_superuser": False,
|
||||
"cmd": ["p搜"],
|
||||
}
|
||||
|
||||
pid_search = on_command("p搜", aliases={"pixiv搜", "P搜"}, priority=5, block=True)
|
||||
|
||||
url = "https://api.fantasyzone.cc/tu/search.php"
|
||||
|
||||
|
||||
@pid_search.handle()
|
||||
async def _(state: T_State, arg: Message = CommandArg()):
|
||||
pid = arg.extract_plain_text().strip()
|
||||
if pid:
|
||||
state["pid"] = pid
|
||||
|
||||
|
||||
@pid_search.got("pid", prompt="需要查询的图片PID是?")
|
||||
async def _(event: MessageEvent, state: T_State, pid: str = Arg("pid")):
|
||||
if pid in ["取消", "算了"]:
|
||||
await pid_search.finish("已取消操作...")
|
||||
if is_number(pid):
|
||||
await pid_search.reject_arg("pid", "笨蛋,重新输入数!字!")
|
||||
params = {
|
||||
"id": pid,
|
||||
"p": 1,
|
||||
}
|
||||
for _ in range(3):
|
||||
try:
|
||||
data = (await AsyncHttpx.get(url, params=params, timeout=5)).json()
|
||||
except TimeoutError:
|
||||
pass
|
||||
except Exception as e:
|
||||
await pid_search.finish(f"发生了一些错误..{type(e)}:{e}")
|
||||
else:
|
||||
if not data["width"] and not data["height"]:
|
||||
await pid_search.finish(f"没有搜索到 PID:{pid} 的图片", at_sender=True)
|
||||
pid = data["id"]
|
||||
title = data["title"]
|
||||
author = data["userName"]
|
||||
author_id = data["userId"]
|
||||
img_url = data["url"]
|
||||
if not await AsyncHttpx.download_file(
|
||||
img_url, TEMP_PATH / f"pid_search_{event.user_id}.png"
|
||||
):
|
||||
await pid_search.finish("图片下载失败了....", at_sender=True)
|
||||
tmp = ""
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
tmp = "\n【注】将在30后撤回......"
|
||||
msg_id = await pid_search.send(
|
||||
Message(
|
||||
f"title:{title}\n"
|
||||
f"pid:{pid}\n"
|
||||
f"author:{author}\n"
|
||||
f"author_id:{author_id}\n"
|
||||
f'{image(f"pid_search_{event.user_id}.png", "temp")}'
|
||||
f"{tmp}"
|
||||
)
|
||||
)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, "
|
||||
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 查询图片 PID:{pid}"
|
||||
)
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
withdraw_message_manager.append((msg_id, 30))
|
||||
break
|
||||
else:
|
||||
await pid_search.finish("图片下载失败了....", at_sender=True)
|
||||
from nonebot import on_command
|
||||
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, Message, GroupMessageEvent
|
||||
from nonebot.typing import T_State
|
||||
|
||||
from configs.config import Config
|
||||
from utils.utils import is_number, change_pixiv_image_links
|
||||
from utils.message_builder import image
|
||||
from services.log import logger
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from utils.manager import withdraw_message_manager
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from nonebot.params import CommandArg, Arg
|
||||
|
||||
|
||||
__zx_plugin_name__ = "pid搜索"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
通过 pid 搜索图片
|
||||
指令:
|
||||
p搜 [pid]
|
||||
""".strip()
|
||||
__plugin_des__ = "通过 pid 搜索图片"
|
||||
__plugin_cmd__ = ["p搜 [pid]"]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
"limit_superuser": False,
|
||||
"cmd": ["p搜"],
|
||||
}
|
||||
|
||||
pid_search = on_command("p搜", aliases={"pixiv搜", "P搜"}, priority=5, block=True)
|
||||
|
||||
|
||||
@pid_search.handle()
|
||||
async def _h(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
|
||||
pid = arg.extract_plain_text().strip()
|
||||
if pid:
|
||||
state["pid"] = pid
|
||||
|
||||
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
|
||||
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
|
||||
"Referer": "https://www.pixiv.net",
|
||||
}
|
||||
|
||||
|
||||
@pid_search.got("pid", prompt="需要查询的图片PID是?")
|
||||
async def _g(event: MessageEvent, state: T_State, pid: str = Arg("pid")):
|
||||
url = Config.get_config("hibiapi", "HIBIAPI") + "/api/pixiv/"
|
||||
if pid in ["取消", "算了"]:
|
||||
await pid_search.finish("已取消操作...")
|
||||
if not is_number(pid):
|
||||
await pid_search.reject_arg("pid", "笨蛋,重新输入数!字!")
|
||||
for _ in range(3):
|
||||
try:
|
||||
data = (
|
||||
await AsyncHttpx.get(
|
||||
url,
|
||||
params={"id": pid},
|
||||
timeout=5,
|
||||
)
|
||||
).json()
|
||||
except TimeoutError:
|
||||
pass
|
||||
except Exception as e:
|
||||
await pid_search.finish(f"发生了一些错误..{type(e)}:{e}")
|
||||
else:
|
||||
if data.get("error"):
|
||||
await pid_search.finish(data["error"]["user_message"], at_sender=True)
|
||||
data = data["illust"]
|
||||
if not data["width"] and not data["height"]:
|
||||
await pid_search.finish(f"没有搜索到 PID:{pid} 的图片", at_sender=True)
|
||||
pid = data["id"]
|
||||
title = data["title"]
|
||||
author = data["user"]["name"]
|
||||
author_id = data["user"]["id"]
|
||||
image_list = []
|
||||
try:
|
||||
image_list.append(data["meta_single_page"]["original_image_url"])
|
||||
except KeyError:
|
||||
for image_url in data["meta_pages"]:
|
||||
image_list.append(image_url["image_urls"]["original"])
|
||||
for i, img_url in enumerate(image_list):
|
||||
img_url = change_pixiv_image_links(img_url)
|
||||
if not await AsyncHttpx.download_file(
|
||||
img_url,
|
||||
IMAGE_PATH / "temp" / f"pid_search_{event.user_id}_{i}.png",
|
||||
headers=headers,
|
||||
):
|
||||
await pid_search.send("图片下载失败了....", at_sender=True)
|
||||
tmp = ""
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
tmp = "\n【注】将在30后撤回......"
|
||||
msg_id = await pid_search.send(
|
||||
Message(
|
||||
f"title:{title}\n"
|
||||
f"pid:{pid}\n"
|
||||
f"author:{author}\n"
|
||||
f"author_id:{author_id}\n"
|
||||
f'{image(f"pid_search_{event.user_id}_{i}.png", "temp")}'
|
||||
f"{tmp}"
|
||||
)
|
||||
)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, "
|
||||
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 查询图片 PID:{pid}"
|
||||
)
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
withdraw_message_manager.append((msg_id, 30))
|
||||
break
|
||||
else:
|
||||
await pid_search.finish("图片下载失败了....", at_sender=True)
|
||||
|
||||
@@ -20,9 +20,9 @@ try:
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
if str(platform.system()).lower() == "windows":
|
||||
policy = asyncio.WindowsSelectorEventLoopPolicy()
|
||||
asyncio.set_event_loop_policy(policy)
|
||||
# if str(platform.system()).lower() == "windows":
|
||||
# policy = asyncio.WindowsSelectorEventLoopPolicy()
|
||||
# asyncio.set_event_loop_policy(policy)
|
||||
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
|
||||
|
||||
@@ -139,15 +139,14 @@ class OmegaPixivIllusts(db.Model):
|
||||
data = await cls.select('pid').gino.all()
|
||||
return [x[0] for x in data]
|
||||
|
||||
@classmethod
|
||||
async def test(cls, nsfw_tag: int = 1):
|
||||
if nsfw_tag is not None:
|
||||
query = cls.query.where(cls.nsfw_tag == nsfw_tag)
|
||||
else:
|
||||
query = cls.query
|
||||
query = query.where((cls.width - cls.height) < 50)
|
||||
for x in await query.gino.all():
|
||||
print(x.pid)
|
||||
# async def test(cls, nsfw_tag: int = 1):
|
||||
# if nsfw_tag is not None:
|
||||
# query = cls.query.where(cls.nsfw_tag == nsfw_tag)
|
||||
# else:
|
||||
# query = cls.query
|
||||
# query = query.where((cls.width - cls.height) < 50)
|
||||
# for x in await query.gino.all():
|
||||
# print(x.pid)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ usage:
|
||||
查看 pix 好康图库
|
||||
指令:
|
||||
pix ?*[tags]: 通过 tag 获取相似图片,不含tag时随机抽取
|
||||
pid [uid]: 通过uid获取图片
|
||||
pix pid[pid]: 查看图库中指定pid图片
|
||||
""".strip()
|
||||
__plugin_superuser_usage__ = """
|
||||
@@ -49,7 +50,9 @@ __plugin_configs__ = {
|
||||
"value": None,
|
||||
"help": "单次发送的图片数量达到指定值时转发为合并消息",
|
||||
"default_value": None,
|
||||
}
|
||||
},
|
||||
"ALLOW_GROUP_SETU": {"value": False, "help": "允许非超级用户使用-s参数", "default_value": False},
|
||||
"ALLOW_GROUP_R18": {"value": False, "help": "允许非超级用户使用-r参数", "default_value": False},
|
||||
}
|
||||
|
||||
|
||||
@@ -80,10 +83,13 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
nsfw_tag = 2
|
||||
else:
|
||||
nsfw_tag = 0
|
||||
if nsfw_tag != 0 and str(event.user_id) not in bot.config.superusers:
|
||||
await pix.finish("你不能看这些噢,这些都是是留给管理员看的...")
|
||||
if n := len(x) == 1 and is_number(x[0]):
|
||||
num = int(x[-1])
|
||||
if str(event.user_id) not in bot.config.superusers:
|
||||
if (nsfw_tag == 1 and not Config.get_config("pix", "ALLOW_GROUP_SETU")) or (
|
||||
nsfw_tag == 2 and not Config.get_config("pix", "ALLOW_GROUP_R18")
|
||||
):
|
||||
await pix.finish("你不能看这些噢,这些都是是留给管理员看的...")
|
||||
if n := len(x) == 1 and is_number(x[0]) and int(x[0]) < 100:
|
||||
num = int(x[0])
|
||||
keyword = ""
|
||||
elif n > 1:
|
||||
if is_number(x[-1]):
|
||||
|
||||
@@ -44,6 +44,8 @@ usage:
|
||||
搜图 樱岛麻衣
|
||||
搜图 樱岛麻衣 5
|
||||
搜图 樱岛麻衣 5 r18
|
||||
搜图 樱岛麻衣#1000users 5
|
||||
【多个关键词用#分割】
|
||||
【默认为 热度排序】
|
||||
【注意空格!!】【在线搜索会较慢】【数量可能不符?可能该页数量不够,也可能被R-18屏蔽】
|
||||
""".strip()
|
||||
@@ -161,8 +163,8 @@ async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
|
||||
info_list = None
|
||||
num = 10
|
||||
page = 1
|
||||
if (n := len(msg)) == 1:
|
||||
keyword = msg[0]
|
||||
if (n := len(msg)) > 0:
|
||||
keyword = msg[0].replace("#"," ")
|
||||
if n > 1:
|
||||
if not is_number(msg[1]):
|
||||
await pixiv_keyword.finish("图片数量必须是数字!", at_sender=True)
|
||||
|
||||
@@ -8,10 +8,10 @@ from services.log import logger
|
||||
from pathlib import Path
|
||||
import platform
|
||||
|
||||
if platform.system() == "Windows":
|
||||
import asyncio
|
||||
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
# if platform.system() == "Windows":
|
||||
# import asyncio
|
||||
#
|
||||
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
|
||||
|
||||
headers = {
|
||||
|
||||
@@ -64,8 +64,8 @@ async def _poke_event(event: PokeNotifyEvent):
|
||||
rand = random.random()
|
||||
if rand <= 0.3:
|
||||
path = random.choice(["luoli", "meitu"])
|
||||
index = random.randint(0, len(os.listdir(IMAGE_PATH / path)))
|
||||
result = f"id:{index}" + image(f"{index}.jpg", path)
|
||||
index = random.randint(0, len(os.listdir(IMAGE_PATH / "image_management" / path)))
|
||||
result = f"id:{index}" + image(f"{index}.jpg", "image_management/" + path)
|
||||
await poke_.send(result)
|
||||
logger.info(f"USER {event.user_id} 戳了戳我 回复: {result} \n {result}")
|
||||
elif 0.3 < rand < 0.6:
|
||||
|
||||
@@ -49,6 +49,8 @@ async def _(bot: Bot, event: MessageEvent, state: T_State, key_word: str = ArgSt
|
||||
Config.get_config("search_anime", "SEARCH_ANIME_MAX_INFO"),
|
||||
)
|
||||
if anime_report:
|
||||
if isinstance(anime_report, str):
|
||||
await search_anime.finish(anime_report)
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
mes_list = custom_forward_msg(anime_report, bot.self_id)
|
||||
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
|
||||
|
||||
@@ -3,18 +3,18 @@ import feedparser
|
||||
from urllib import parse
|
||||
from services.log import logger
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from typing import List
|
||||
from typing import List, Union
|
||||
import time
|
||||
|
||||
|
||||
async def from_anime_get_info(key_word: str, max_: int) -> List[str]:
|
||||
async def from_anime_get_info(key_word: str, max_: int) -> Union[str, List[str]]:
|
||||
s_time = time.time()
|
||||
repass = ""
|
||||
url = "https://share.dmhy.org/topics/rss/rss.xml?keyword=" + parse.quote(key_word)
|
||||
try:
|
||||
repass = await get_repass(url, max_)
|
||||
except Exception as e:
|
||||
logger.error("Timeout! {}".format(e))
|
||||
logger.error(f"发生了一些错误 {type(e)}:{e}")
|
||||
return "发生了一些错误!"
|
||||
repass.insert(0, f"搜索 {key_word} 结果(耗时 {int(time.time() - s_time)} 秒):\n")
|
||||
return repass
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
from nonebot.plugin import on_command
|
||||
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
|
||||
from nonebot.typing import T_State
|
||||
from services.log import logger
|
||||
from utils.utils import get_message_img
|
||||
from utils.message_builder import custom_forward_msg
|
||||
from nonebot.params import CommandArg, Arg, ArgStr, Depends
|
||||
from .saucenao import get_saucenao_image
|
||||
|
||||
|
||||
__zx_plugin_name__ = "识图"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
识别图片 [二次元图片]
|
||||
指令:
|
||||
识图 [图片]
|
||||
""".strip()
|
||||
__plugin_des__ = "以图搜图,看破本源"
|
||||
__plugin_cmd__ = ["识图"]
|
||||
__plugin_type__ = ("一些工具",)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
"limit_superuser": False,
|
||||
"cmd": ["识图"],
|
||||
}
|
||||
__plugin_configs__ = {
|
||||
"MAX_FIND_IMAGE_COUNT": {"value": 3, "help": "识图返回的最大结果数", "default_value": 3},
|
||||
"API_KEY": {
|
||||
"value": None,
|
||||
"help": "Saucenao的API_KEY,通过 https://saucenao.com/user.php?page=search-api 注册获取",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
search_image = on_command("识图", block=True, priority=5)
|
||||
|
||||
|
||||
async def get_image_info(mod: str, url: str):
|
||||
if mod == "saucenao":
|
||||
return await get_saucenao_image(url)
|
||||
|
||||
|
||||
def parse_image(key: str):
|
||||
async def _key_parser(
|
||||
state: T_State, img: Message = Arg(key)
|
||||
):
|
||||
if not get_message_img(img):
|
||||
await search_image.reject_arg(key, "请发送要识别的图片!")
|
||||
state[key] = img
|
||||
return _key_parser
|
||||
|
||||
|
||||
@search_image.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
if msg:
|
||||
state["mod"] = msg
|
||||
else:
|
||||
state["mod"] = "saucenao"
|
||||
if get_message_img(event.json()):
|
||||
state["img"] = event.message
|
||||
|
||||
|
||||
@search_image.got("img", prompt="图来!", parameterless=[Depends(parse_image("img"))])
|
||||
async def _(
|
||||
bot: Bot,
|
||||
event: MessageEvent,
|
||||
state: T_State,
|
||||
mod: str = ArgStr("mod"),
|
||||
img: Message = Arg("img"),
|
||||
):
|
||||
img = get_message_img(img)[0]
|
||||
await search_image.send("开始处理图片...")
|
||||
msg = await get_image_info(mod, img)
|
||||
if isinstance(msg, str):
|
||||
await search_image.finish(msg, at_sender=True)
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
await bot.send_group_forward_msg(
|
||||
group_id=event.group_id, messages=custom_forward_msg(msg, bot.self_id)
|
||||
)
|
||||
else:
|
||||
for m in msg[1:]:
|
||||
await search_image.send(m)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP "
|
||||
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 识图:" + img
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from configs.config import Config
|
||||
from configs.path_config import TEMP_PATH
|
||||
from utils.message_builder import image
|
||||
from typing import Union, List
|
||||
import random
|
||||
|
||||
API_URL_SAUCENAO = "https://saucenao.com/search.php"
|
||||
API_URL_ASCII2D = "https://ascii2d.net/search/url/"
|
||||
API_URL_IQDB = "https://iqdb.org/"
|
||||
|
||||
|
||||
async def get_saucenao_image(url: str) -> Union[str, List[str]]:
|
||||
api_key = Config.get_config("search_image", "API_KEY")
|
||||
if not api_key:
|
||||
return "Saucenao 缺失API_KEY!"
|
||||
|
||||
params = {
|
||||
"output_type": 2,
|
||||
"api_key": api_key,
|
||||
"testmode": 1,
|
||||
"numres": 6,
|
||||
"db": 999,
|
||||
"url": url,
|
||||
}
|
||||
data = (await AsyncHttpx.post(API_URL_SAUCENAO, params=params)).json()
|
||||
if data["header"]["status"] != 0:
|
||||
return f"Saucenao识图失败..status:{data['header']['status']}"
|
||||
data = data["results"]
|
||||
data = (
|
||||
data
|
||||
if len(data) < Config.get_config("search_image", "MAX_FIND_IMAGE_COUNT")
|
||||
else data[: Config.get_config("search_image", "MAX_FIND_IMAGE_COUNT")]
|
||||
)
|
||||
msg_list = []
|
||||
index = random.randint(0, 10000)
|
||||
if await AsyncHttpx.download_file(
|
||||
url, TEMP_PATH / f"saucenao_search_{index}.jpg"
|
||||
):
|
||||
msg_list.append(image(TEMP_PATH / f"saucenao_search_{index}.jpg"))
|
||||
for info in data:
|
||||
similarity = info["header"]["similarity"]
|
||||
tmp = f"相似度:{similarity}%\n"
|
||||
for x in info["data"].keys():
|
||||
if x != "ext_urls":
|
||||
tmp += f"{x}:{info['data'][x]}\n"
|
||||
if "source" not in info["data"].keys():
|
||||
tmp += f'source:{info["data"]["ext_urls"][0]}\n'
|
||||
msg_list.append(tmp[:-1])
|
||||
return msg_list
|
||||
@@ -144,7 +144,6 @@ class Setu(db.Model):
|
||||
return _tmp_local_id
|
||||
return -1
|
||||
|
||||
|
||||
@classmethod
|
||||
async def update_setu_data(
|
||||
cls,
|
||||
|
||||
@@ -4,7 +4,7 @@ from services.log import logger
|
||||
from models.sign_group_user import SignGroupUser
|
||||
from nonebot.message import run_postprocessor
|
||||
from nonebot.matcher import Matcher
|
||||
from typing import Optional, Type
|
||||
from typing import Optional, Type, Any
|
||||
from gino.exceptions import UninitializedError
|
||||
from utils.utils import (
|
||||
is_number,
|
||||
@@ -33,7 +33,7 @@ from .data_source import (
|
||||
from nonebot.adapters.onebot.v11.exception import ActionFailed
|
||||
from configs.config import Config, NICKNAME
|
||||
from utils.manager import withdraw_message_manager
|
||||
from nonebot.params import CommandArg, Command
|
||||
from nonebot.params import CommandArg, Command, RegexGroup
|
||||
from typing import Tuple
|
||||
import re
|
||||
|
||||
@@ -97,6 +97,7 @@ __plugin_configs__ = {
|
||||
},
|
||||
"TIMEOUT": {"value": 10, "help": "色图下载超时限制(秒)", "default_value": 10},
|
||||
"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反向代理")
|
||||
|
||||
@@ -148,10 +149,16 @@ async def _(
|
||||
if cmd[0] == "色图r" and isinstance(event, PrivateMessageEvent):
|
||||
r18 = 1
|
||||
num = 10
|
||||
elif cmd[0] == "色图r" and isinstance(event, GroupMessageEvent):
|
||||
await setu.finish(
|
||||
random.choice(["这种不好意思的东西怎么可能给这么多人看啦", "羞羞脸!给我滚出克私聊!", "变态变态变态变态大变态!"])
|
||||
)
|
||||
elif (
|
||||
cmd[0] == "色图r"
|
||||
and isinstance(event, GroupMessageEvent)
|
||||
):
|
||||
if not Config.get_config("send_setu", "ALLOW_GROUP_R18"):
|
||||
await setu.finish(
|
||||
random.choice(["这种不好意思的东西怎么可能给这么多人看啦", "羞羞脸!给我滚出克私聊!", "变态变态变态变态大变态!"])
|
||||
)
|
||||
else:
|
||||
r18 = 1
|
||||
# 有 数字 的话先尝试本地色图id
|
||||
if msg and is_number(msg):
|
||||
setu_list, code = await get_setu_list(int(msg), r18=r18)
|
||||
@@ -190,7 +197,7 @@ num_key = {
|
||||
|
||||
|
||||
@setu_reg.handle()
|
||||
async def _(event: MessageEvent, arg: Message = CommandArg()):
|
||||
async def _(event: MessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
impression = (
|
||||
await SignGroupUser.ensure(event.user_id, event.group_id)
|
||||
@@ -198,28 +205,15 @@ async def _(event: MessageEvent, arg: Message = CommandArg()):
|
||||
luox = get_luoxiang(impression)
|
||||
if luox:
|
||||
await setu.finish(luox, at_sender=True)
|
||||
msg = arg.extract_plain_text().strip()
|
||||
num = 1
|
||||
msg = re.search(r"(.*)[份发张个次点](.*)[瑟涩色]图", msg)
|
||||
# 解析 tags 以及 num
|
||||
if msg:
|
||||
num = msg.group(1)
|
||||
tags = msg.group(2)
|
||||
if tags:
|
||||
tags = tags[:-1] if tags[-1] == "的" else tags
|
||||
if num:
|
||||
num = num[-1]
|
||||
if num_key.get(num):
|
||||
num = num_key[num]
|
||||
elif is_number(num):
|
||||
try:
|
||||
num = int(num)
|
||||
except ValueError:
|
||||
num = 1
|
||||
else:
|
||||
num = 1
|
||||
else:
|
||||
return
|
||||
num, tags = reg_group
|
||||
num = num or 1
|
||||
tags = tags[:-1] if tags and tags[-1] == "的" else tags
|
||||
if num_key.get(num):
|
||||
num = num_key[num]
|
||||
try:
|
||||
num = int(num)
|
||||
except ValueError:
|
||||
num = 1
|
||||
await send_setu_handle(setu_reg, event, "色图", tags, num, 0)
|
||||
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ async def update_setu_img(flag: bool = False):
|
||||
f"--> /{path}/{image.local_id}.jpg"
|
||||
)
|
||||
os.rename(
|
||||
TEMP_PATH / f"/{image.local_id}.jpg",
|
||||
TEMP_PATH / f"{image.local_id}.jpg",
|
||||
path / f"{image.local_id}.jpg",
|
||||
)
|
||||
except FileNotFoundError:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Tuple, Any
|
||||
|
||||
from .group_user_checkin import (
|
||||
group_user_check_in,
|
||||
group_user_check,
|
||||
@@ -8,9 +10,9 @@ from .group_user_checkin import (
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
|
||||
from nonebot.adapters.onebot.v11.permission import GROUP
|
||||
from utils.message_builder import image
|
||||
from nonebot import on_command
|
||||
from nonebot import on_command, on_regex
|
||||
from utils.utils import scheduler
|
||||
from nonebot.params import CommandArg
|
||||
from nonebot.params import CommandArg, RegexGroup
|
||||
from pathlib import Path
|
||||
from configs.path_config import DATA_PATH
|
||||
from services.log import logger
|
||||
@@ -68,7 +70,7 @@ except (FileNotFoundError, ValueError, TypeError):
|
||||
data = {"0": []}
|
||||
|
||||
|
||||
sign = on_command("签到", priority=5, permission=GROUP, block=True)
|
||||
sign = on_regex("^签到(all)?$", priority=5, permission=GROUP, block=True)
|
||||
my_sign = on_command(
|
||||
cmd="我的签到", aliases={"好感度"}, priority=5, permission=GROUP, block=True
|
||||
)
|
||||
@@ -85,13 +87,13 @@ total_sign_rank = on_command(
|
||||
|
||||
|
||||
@sign.handle()
|
||||
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
async def _(event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
nickname = event.sender.card or event.sender.nickname
|
||||
await sign.send(
|
||||
await group_user_check_in(nickname, event.user_id, event.group_id),
|
||||
at_sender=True,
|
||||
)
|
||||
if arg.extract_plain_text().strip() == "all":
|
||||
if reg_group[0]:
|
||||
await check_in_all(nickname, event.user_id)
|
||||
|
||||
|
||||
|
||||
+13
-16
@@ -55,13 +55,10 @@ async def get_card(
|
||||
date = datetime.now().date()
|
||||
_type = "view" if is_card_view else "sign"
|
||||
card_file = (
|
||||
Path(SIGN_TODAY_CARD_PATH)
|
||||
/ f"{user_id}_{user.group_id}_{_type}_{date}.png"
|
||||
Path(SIGN_TODAY_CARD_PATH) / f"{user_id}_{user.group_id}_{_type}_{date}.png"
|
||||
)
|
||||
if card_file.exists():
|
||||
return image(
|
||||
f"{user_id}_{user.group_id}_{_type}_{date}.png", "sign/today_card"
|
||||
)
|
||||
return image(f"{user_id}_{user.group_id}_{_type}_{date}.png", "sign/today_card")
|
||||
else:
|
||||
if add_impression == -1:
|
||||
card_file = (
|
||||
@@ -75,9 +72,7 @@ async def get_card(
|
||||
)
|
||||
is_card_view = True
|
||||
ava = BytesIO(await get_user_avatar(user_id))
|
||||
uid = await GroupInfoUser.get_group_member_uid(
|
||||
user.user_qq, user.group_id
|
||||
)
|
||||
uid = await GroupInfoUser.get_group_member_uid(user.user_qq, user.group_id)
|
||||
impression_list = None
|
||||
if is_card_view:
|
||||
_, impression_list, _ = await SignGroupUser.get_all_impression(
|
||||
@@ -128,9 +123,13 @@ def _generate_card(
|
||||
level, next_impression, previous_impression = get_level_and_next_impression(
|
||||
user.impression
|
||||
)
|
||||
interpolation = next_impression - user.impression
|
||||
if level == "9":
|
||||
level = "8"
|
||||
interpolation = 0
|
||||
info_img.text((0, 0), f"· 好感度等级:{level} [{lik2relation[level]}]")
|
||||
info_img.text((0, 20), f"· {NICKNAME}对你的态度:{level2attitude[level]}")
|
||||
info_img.text((0, 40), f"· 距离升级还差 {next_impression - user.impression:.2f} 好感度")
|
||||
info_img.text((0, 40), f"· 距离升级还差 {interpolation:.2f} 好感度")
|
||||
|
||||
bar_bk = BuildImage(220, 20, background=SIGN_RESOURCE_PATH / "bar_white.png")
|
||||
bar = BuildImage(220, 20, background=SIGN_RESOURCE_PATH / "bar.png")
|
||||
@@ -240,7 +239,9 @@ def _generate_card(
|
||||
f"上次签到日期:{'从未' if user.checkin_time_last == datetime.min else user.checkin_time_last.date()}",
|
||||
)
|
||||
today_data.text((0, 25), f"总金币:{gold}")
|
||||
default_setu_prob = Config.get_config("send_setu", "INITIAL_SETU_PROBABILITY") * 100
|
||||
default_setu_prob = (
|
||||
Config.get_config("send_setu", "INITIAL_SETU_PROBABILITY") * 100
|
||||
)
|
||||
today_data.text(
|
||||
(0, 50),
|
||||
f"色图概率:{(default_setu_prob + user.impression if user.impression < 100 else 100):.2f}%",
|
||||
@@ -286,12 +287,8 @@ def _generate_card(
|
||||
bk.paste(today_sign_text_img, (550, 180), True)
|
||||
bk.paste(today_data, (580, 220), True)
|
||||
bk.paste(watermark, (15, 400), True)
|
||||
bk.save(
|
||||
SIGN_TODAY_CARD_PATH / f"{user_id}_{user.group_id}_{_type}_{data}.png"
|
||||
)
|
||||
return image(
|
||||
f"{user_id}_{user.group_id}_{_type}_{data}.png", "sign/today_card"
|
||||
)
|
||||
bk.save(SIGN_TODAY_CARD_PATH / f"{user_id}_{user.group_id}_{_type}_{data}.png")
|
||||
return image(f"{user_id}_{user.group_id}_{_type}_{data}.png", "sign/today_card")
|
||||
|
||||
|
||||
def generate_progress_bar_pic():
|
||||
|
||||
@@ -1,280 +1,279 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, Message
|
||||
from models.group_info import GroupInfo
|
||||
from configs.path_config import DATA_PATH, IMAGE_PATH
|
||||
from nonebot.params import CommandArg, Command
|
||||
from utils.image_utils import BuildMat
|
||||
from utils.message_builder import image
|
||||
from utils.manager import plugins2settings_manager
|
||||
from typing import Tuple
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
__zx_plugin_name__ = "功能调用统计可视化"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
功能调用统计可视化
|
||||
指令:
|
||||
功能调用统计
|
||||
日功能调用统计
|
||||
周功能调用统计 ?[功能]
|
||||
月功能调用统计 ?[功能]
|
||||
我的功能调用统计
|
||||
我的日功能调用统计 ?[功能]
|
||||
我的周功能调用统计 ?[功能]
|
||||
我的月功能调用统计 ?[功能]
|
||||
""".strip()
|
||||
__plugin_superuser_usage__ = """
|
||||
usage:
|
||||
功能调用统计可视化
|
||||
指令:
|
||||
全局功能调用统计
|
||||
全局日功能调用统计
|
||||
全局周功能调用统计 ?[功能]
|
||||
全局月功能调用统计 ?[功能]
|
||||
""".strip()
|
||||
__plugin_des__ = "功能调用统计可视化"
|
||||
__plugin_cmd__ = [
|
||||
"功能调用统计",
|
||||
"全局功能调用统计 [_superuser]",
|
||||
"全局日功能调用统计 [_superuser]",
|
||||
"全局周功能调用统计 ?[功能] [_superuser]",
|
||||
"全局月功能调用统计 ?[功能] [_superuser]",
|
||||
"周功能调用统计 ?[功能]",
|
||||
"月功能调用统计 ?[功能]",
|
||||
"我的功能调用统计",
|
||||
"我的日功能调用统计 ?[功能]",
|
||||
"我的周功能调用统计 ?[功能]",
|
||||
"我的月功能调用统计 ?[功能]",
|
||||
]
|
||||
__plugin_type__ = ("功能调用统计可视化", 1)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
"limit_superuser": False,
|
||||
"cmd": ["功能调用统计"],
|
||||
}
|
||||
|
||||
|
||||
statistics = on_command(
|
||||
"功能调用统计",
|
||||
aliases={
|
||||
"全局功能调用统计",
|
||||
"全局日功能调用统计",
|
||||
"全局周功能调用统计",
|
||||
"全局月功能调用统计",
|
||||
"日功能调用统计",
|
||||
"周功能调用统计",
|
||||
"月功能调用统计",
|
||||
"我的功能调用统计",
|
||||
"我的日功能调用统计",
|
||||
"我的周功能调用统计",
|
||||
"我的月功能调用统计",
|
||||
},
|
||||
priority=5,
|
||||
block=True,
|
||||
)
|
||||
|
||||
|
||||
statistics_group_file = DATA_PATH / "statistics" / "_prefix_count.json"
|
||||
statistics_user_file = DATA_PATH / "statistics" / "_prefix_user_count.json"
|
||||
|
||||
|
||||
@statistics.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
if cmd[0][:2] == "全局":
|
||||
if str(event.user_id) in bot.config.superusers:
|
||||
data: dict = json.load(open(statistics_group_file, "r", encoding="utf8"))
|
||||
if cmd[0][2] == '日':
|
||||
_type = 'day_statistics'
|
||||
elif cmd[0][2] == '周':
|
||||
_type = 'week_statistics'
|
||||
elif cmd[0][2] == '月':
|
||||
_type = 'month_statistics'
|
||||
else:
|
||||
_type = 'total_statistics'
|
||||
tmp_dict = {}
|
||||
data = data[_type]
|
||||
if _type in ["day_statistics", "total_statistics"]:
|
||||
for key in data['total']:
|
||||
tmp_dict[key] = data['total'][key]
|
||||
else:
|
||||
for group in data.keys():
|
||||
if group != 'total':
|
||||
for day in data[group].keys():
|
||||
for plugin_name in data[group][day].keys():
|
||||
if data[group][day][plugin_name] is not None:
|
||||
if tmp_dict.get(plugin_name) is None:
|
||||
tmp_dict[plugin_name] = 1
|
||||
else:
|
||||
tmp_dict[plugin_name] += data[group][day][plugin_name]
|
||||
bar_graph = await init_bar_graph(tmp_dict, cmd[0])
|
||||
await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph)
|
||||
await statistics.finish(image(b64=bar_graph.pic2bs4()))
|
||||
return
|
||||
if cmd[0][:2] == "我的":
|
||||
_type = "user"
|
||||
key = str(event.user_id)
|
||||
cmd = list(cmd)
|
||||
cmd[0] = cmd[0][2:]
|
||||
if not statistics_user_file.exists():
|
||||
await statistics.finish("统计文件不存在...", at_sender=True)
|
||||
else:
|
||||
if not isinstance(event, GroupMessageEvent):
|
||||
await statistics.finish("请在群内调用此功能...")
|
||||
_type = "group"
|
||||
key = str(event.group_id)
|
||||
if not statistics_group_file.exists():
|
||||
await statistics.finish("统计文件不存在...", at_sender=True)
|
||||
plugin = ""
|
||||
if cmd[0][0] == "日":
|
||||
arg = "day_statistics"
|
||||
elif cmd[0][0] == "周":
|
||||
arg = "week_statistics"
|
||||
elif cmd[0][0] == "月":
|
||||
arg = "month_statistics"
|
||||
else:
|
||||
arg = "total_statistics"
|
||||
if msg:
|
||||
plugin = plugins2settings_manager.get_plugin_module(msg)
|
||||
if not plugin:
|
||||
if arg not in ["day_statistics", "total_statistics"]:
|
||||
await statistics.finish("未找到此功能的调用...", at_sender=True)
|
||||
if _type == "group":
|
||||
data: dict = json.load(open(statistics_group_file, "r", encoding="utf8"))
|
||||
if not data[arg].get(str(event.group_id)):
|
||||
await statistics.finish("该群统计数据不存在...", at_sender=True)
|
||||
else:
|
||||
data: dict = json.load(open(statistics_user_file, "r", encoding="utf8"))
|
||||
if not data[arg].get(str(event.user_id)):
|
||||
await statistics.finish("该用户统计数据不存在...", at_sender=True)
|
||||
day_index = data["day_index"]
|
||||
data = data[arg][key]
|
||||
if _type == "group":
|
||||
name = await GroupInfo.get_group_info(event.group_id)
|
||||
name = name.group_name if name else str(event.group_id)
|
||||
else:
|
||||
name = event.sender.card or event.sender.nickname
|
||||
img = await generate_statistics_img(data, arg, name, plugin, day_index)
|
||||
await statistics.send(image(b64=img))
|
||||
|
||||
|
||||
async def generate_statistics_img(
|
||||
data: dict, arg: str, name: str, plugin: str, day_index: int
|
||||
):
|
||||
try:
|
||||
plugin = plugins2settings_manager.get_plugin_data(plugin)['cmd'][0]
|
||||
except (KeyError, IndexError):
|
||||
pass
|
||||
bar_graph = None
|
||||
if arg == "day_statistics":
|
||||
bar_graph = await init_bar_graph(data, f"{name} 日功能调用统计")
|
||||
elif arg == "week_statistics":
|
||||
if plugin:
|
||||
current_week = day_index % 7
|
||||
week_lst = []
|
||||
if current_week == 0:
|
||||
week_lst = [1, 2, 3, 4, 5, 6, 7]
|
||||
else:
|
||||
for i in range(current_week + 1, 7):
|
||||
week_lst.append(str(i))
|
||||
for i in range(current_week + 1):
|
||||
week_lst.append(str(i))
|
||||
count = []
|
||||
for i in range(7):
|
||||
if int(week_lst[i]) == 7:
|
||||
try:
|
||||
count.append(data[str(0)][plugin])
|
||||
except KeyError:
|
||||
count.append(0)
|
||||
else:
|
||||
try:
|
||||
count.append(data[str(week_lst[i])][plugin])
|
||||
except KeyError:
|
||||
count.append(0)
|
||||
week_lst = ["7" if i == "0" else i for i in week_lst]
|
||||
bar_graph = BuildMat(
|
||||
y=count,
|
||||
mat_type="line",
|
||||
title=f"{name} 周 {plugin} 功能调用统计【为7天统计】",
|
||||
x_index=week_lst,
|
||||
display_num=True,
|
||||
background=[
|
||||
f"{IMAGE_PATH}/background/create_mat/{x}"
|
||||
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
|
||||
],
|
||||
bar_color=["*"],
|
||||
)
|
||||
else:
|
||||
bar_graph = await init_bar_graph(update_data(data), f"{name} 周功能调用统计【为7天统计】")
|
||||
elif arg == "month_statistics":
|
||||
if plugin:
|
||||
day_index = day_index % 30
|
||||
day_lst = []
|
||||
for i in range(day_index + 1, 30):
|
||||
day_lst.append(i)
|
||||
for i in range(day_index + 1):
|
||||
day_lst.append(i)
|
||||
count = [data[str(day_lst[i])][plugin] for i in range(30)]
|
||||
day_lst = [str(x + 1) for x in day_lst]
|
||||
bar_graph = BuildMat(
|
||||
y=count,
|
||||
mat_type="line",
|
||||
title=f"{name} 月 {plugin} 功能调用统计【为30天统计】",
|
||||
x_index=day_lst,
|
||||
display_num=True,
|
||||
background=[
|
||||
f"{IMAGE_PATH}/background/create_mat/{x}"
|
||||
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
|
||||
],
|
||||
bar_color=["*"],
|
||||
)
|
||||
else:
|
||||
bar_graph = await init_bar_graph(update_data(data), f"{name} 月功能调用统计【为30天统计】")
|
||||
elif arg == "total_statistics":
|
||||
bar_graph = await init_bar_graph(data, f"{name} 功能调用统计")
|
||||
await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph)
|
||||
return bar_graph.pic2bs4()
|
||||
|
||||
|
||||
async def init_bar_graph(data: dict, title: str) -> BuildMat:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, _init_bar_graph, data, title)
|
||||
|
||||
|
||||
def _init_bar_graph(data: dict, title: str) -> BuildMat:
|
||||
bar_graph = BuildMat(
|
||||
y=[data[x] for x in data.keys() if data[x] != 0],
|
||||
mat_type="barh",
|
||||
title=title,
|
||||
x_index=[x for x in data.keys() if data[x] != 0],
|
||||
display_num=True,
|
||||
background=[
|
||||
f"{IMAGE_PATH}/background/create_mat/{x}"
|
||||
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
|
||||
],
|
||||
bar_color=["*"],
|
||||
)
|
||||
return bar_graph
|
||||
|
||||
|
||||
def update_data(data: dict):
|
||||
tmp_dict = {}
|
||||
for day in data.keys():
|
||||
for plugin_name in data[day].keys():
|
||||
# print(f'{day}:{plugin_name} = {data[day][plugin_name]}')
|
||||
if data[day][plugin_name] is not None:
|
||||
if tmp_dict.get(plugin_name) is None:
|
||||
tmp_dict[plugin_name] = 1
|
||||
else:
|
||||
tmp_dict[plugin_name] += data[day][plugin_name]
|
||||
return tmp_dict
|
||||
|
||||
from nonebot import on_command
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, Message
|
||||
from models.group_info import GroupInfo
|
||||
from configs.path_config import DATA_PATH, IMAGE_PATH
|
||||
from nonebot.params import CommandArg, Command
|
||||
from utils.image_utils import BuildMat
|
||||
from utils.message_builder import image
|
||||
from utils.manager import plugins2settings_manager
|
||||
from typing import Tuple
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
__zx_plugin_name__ = "功能调用统计可视化"
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
功能调用统计可视化
|
||||
指令:
|
||||
功能调用统计
|
||||
日功能调用统计
|
||||
周功能调用统计 ?[功能]
|
||||
月功能调用统计 ?[功能]
|
||||
我的功能调用统计
|
||||
我的日功能调用统计 ?[功能]
|
||||
我的周功能调用统计 ?[功能]
|
||||
我的月功能调用统计 ?[功能]
|
||||
""".strip()
|
||||
__plugin_superuser_usage__ = """
|
||||
usage:
|
||||
功能调用统计可视化
|
||||
指令:
|
||||
全局功能调用统计
|
||||
全局日功能调用统计
|
||||
全局周功能调用统计 ?[功能]
|
||||
全局月功能调用统计 ?[功能]
|
||||
""".strip()
|
||||
__plugin_des__ = "功能调用统计可视化"
|
||||
__plugin_cmd__ = [
|
||||
"功能调用统计",
|
||||
"全局功能调用统计 [_superuser]",
|
||||
"全局日功能调用统计 [_superuser]",
|
||||
"全局周功能调用统计 ?[功能] [_superuser]",
|
||||
"全局月功能调用统计 ?[功能] [_superuser]",
|
||||
"周功能调用统计 ?[功能]",
|
||||
"月功能调用统计 ?[功能]",
|
||||
"我的功能调用统计",
|
||||
"我的日功能调用统计 ?[功能]",
|
||||
"我的周功能调用统计 ?[功能]",
|
||||
"我的月功能调用统计 ?[功能]",
|
||||
]
|
||||
__plugin_type__ = ("数据统计", 1)
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
"limit_superuser": False,
|
||||
"cmd": ["功能调用统计"],
|
||||
}
|
||||
|
||||
|
||||
statistics = on_command(
|
||||
"功能调用统计",
|
||||
aliases={
|
||||
"全局功能调用统计",
|
||||
"全局日功能调用统计",
|
||||
"全局周功能调用统计",
|
||||
"全局月功能调用统计",
|
||||
"日功能调用统计",
|
||||
"周功能调用统计",
|
||||
"月功能调用统计",
|
||||
"我的功能调用统计",
|
||||
"我的日功能调用统计",
|
||||
"我的周功能调用统计",
|
||||
"我的月功能调用统计",
|
||||
},
|
||||
priority=5,
|
||||
block=True,
|
||||
)
|
||||
|
||||
|
||||
statistics_group_file = DATA_PATH / "statistics" / "_prefix_count.json"
|
||||
statistics_user_file = DATA_PATH / "statistics" / "_prefix_user_count.json"
|
||||
|
||||
|
||||
@statistics.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
if cmd[0][:2] == "全局":
|
||||
if str(event.user_id) in bot.config.superusers:
|
||||
data: dict = json.load(open(statistics_group_file, "r", encoding="utf8"))
|
||||
if cmd[0][2] == '日':
|
||||
_type = 'day_statistics'
|
||||
elif cmd[0][2] == '周':
|
||||
_type = 'week_statistics'
|
||||
elif cmd[0][2] == '月':
|
||||
_type = 'month_statistics'
|
||||
else:
|
||||
_type = 'total_statistics'
|
||||
tmp_dict = {}
|
||||
data = data[_type]
|
||||
if _type in ["day_statistics", "total_statistics"]:
|
||||
for key in data['total']:
|
||||
tmp_dict[key] = data['total'][key]
|
||||
else:
|
||||
for group in data.keys():
|
||||
if group != 'total':
|
||||
for day in data[group].keys():
|
||||
for plugin_name in data[group][day].keys():
|
||||
if data[group][day][plugin_name] is not None:
|
||||
if tmp_dict.get(plugin_name) is None:
|
||||
tmp_dict[plugin_name] = 1
|
||||
else:
|
||||
tmp_dict[plugin_name] += data[group][day][plugin_name]
|
||||
bar_graph = await init_bar_graph(tmp_dict, cmd[0])
|
||||
await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph)
|
||||
await statistics.finish(image(b64=bar_graph.pic2bs4()))
|
||||
return
|
||||
if cmd[0][:2] == "我的":
|
||||
_type = "user"
|
||||
key = str(event.user_id)
|
||||
cmd = list(cmd)
|
||||
cmd[0] = cmd[0][2:]
|
||||
if not statistics_user_file.exists():
|
||||
await statistics.finish("统计文件不存在...", at_sender=True)
|
||||
else:
|
||||
if not isinstance(event, GroupMessageEvent):
|
||||
await statistics.finish("请在群内调用此功能...")
|
||||
_type = "group"
|
||||
key = str(event.group_id)
|
||||
if not statistics_group_file.exists():
|
||||
await statistics.finish("统计文件不存在...", at_sender=True)
|
||||
plugin = ""
|
||||
if cmd[0][0] == "日":
|
||||
arg = "day_statistics"
|
||||
elif cmd[0][0] == "周":
|
||||
arg = "week_statistics"
|
||||
elif cmd[0][0] == "月":
|
||||
arg = "month_statistics"
|
||||
else:
|
||||
arg = "total_statistics"
|
||||
if msg:
|
||||
plugin = plugins2settings_manager.get_plugin_module(msg)
|
||||
if not plugin:
|
||||
if arg not in ["day_statistics", "total_statistics"]:
|
||||
await statistics.finish("未找到此功能的调用...", at_sender=True)
|
||||
if _type == "group":
|
||||
data: dict = json.load(open(statistics_group_file, "r", encoding="utf8"))
|
||||
if not data[arg].get(str(event.group_id)):
|
||||
await statistics.finish("该群统计数据不存在...", at_sender=True)
|
||||
else:
|
||||
data: dict = json.load(open(statistics_user_file, "r", encoding="utf8"))
|
||||
if not data[arg].get(str(event.user_id)):
|
||||
await statistics.finish("该用户统计数据不存在...", at_sender=True)
|
||||
day_index = data["day_index"]
|
||||
data = data[arg][key]
|
||||
if _type == "group":
|
||||
name = await GroupInfo.get_group_info(event.group_id)
|
||||
name = name.group_name if name else str(event.group_id)
|
||||
else:
|
||||
name = event.sender.card or event.sender.nickname
|
||||
img = await generate_statistics_img(data, arg, name, plugin, day_index)
|
||||
await statistics.send(image(b64=img))
|
||||
|
||||
|
||||
async def generate_statistics_img(
|
||||
data: dict, arg: str, name: str, plugin: str, day_index: int
|
||||
):
|
||||
try:
|
||||
plugin = plugins2settings_manager.get_plugin_data(plugin)['cmd'][0]
|
||||
except (KeyError, IndexError):
|
||||
pass
|
||||
bar_graph = None
|
||||
if arg == "day_statistics":
|
||||
bar_graph = await init_bar_graph(data, f"{name} 日功能调用统计")
|
||||
elif arg == "week_statistics":
|
||||
if plugin:
|
||||
current_week = day_index % 7
|
||||
week_lst = []
|
||||
if current_week == 0:
|
||||
week_lst = [1, 2, 3, 4, 5, 6, 7]
|
||||
else:
|
||||
for i in range(current_week + 1, 7):
|
||||
week_lst.append(str(i))
|
||||
for i in range(current_week + 1):
|
||||
week_lst.append(str(i))
|
||||
count = []
|
||||
for i in range(7):
|
||||
if int(week_lst[i]) == 7:
|
||||
try:
|
||||
count.append(data[str(0)][plugin])
|
||||
except KeyError:
|
||||
count.append(0)
|
||||
else:
|
||||
try:
|
||||
count.append(data[str(week_lst[i])][plugin])
|
||||
except KeyError:
|
||||
count.append(0)
|
||||
week_lst = ["7" if i == "0" else i for i in week_lst]
|
||||
bar_graph = BuildMat(
|
||||
y=count,
|
||||
mat_type="line",
|
||||
title=f"{name} 周 {plugin} 功能调用统计【为7天统计】",
|
||||
x_index=week_lst,
|
||||
display_num=True,
|
||||
background=[
|
||||
f"{IMAGE_PATH}/background/create_mat/{x}"
|
||||
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
|
||||
],
|
||||
bar_color=["*"],
|
||||
)
|
||||
else:
|
||||
bar_graph = await init_bar_graph(update_data(data), f"{name} 周功能调用统计【为7天统计】")
|
||||
elif arg == "month_statistics":
|
||||
if plugin:
|
||||
day_index = day_index % 30
|
||||
day_lst = []
|
||||
for i in range(day_index + 1, 30):
|
||||
day_lst.append(i)
|
||||
for i in range(day_index + 1):
|
||||
day_lst.append(i)
|
||||
count = [data[str(day_lst[i])][plugin] for i in range(30)]
|
||||
day_lst = [str(x + 1) for x in day_lst]
|
||||
bar_graph = BuildMat(
|
||||
y=count,
|
||||
mat_type="line",
|
||||
title=f"{name} 月 {plugin} 功能调用统计【为30天统计】",
|
||||
x_index=day_lst,
|
||||
display_num=True,
|
||||
background=[
|
||||
f"{IMAGE_PATH}/background/create_mat/{x}"
|
||||
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
|
||||
],
|
||||
bar_color=["*"],
|
||||
)
|
||||
else:
|
||||
bar_graph = await init_bar_graph(update_data(data), f"{name} 月功能调用统计【为30天统计】")
|
||||
elif arg == "total_statistics":
|
||||
bar_graph = await init_bar_graph(data, f"{name} 功能调用统计")
|
||||
await asyncio.get_event_loop().run_in_executor(None, bar_graph.gen_graph)
|
||||
return bar_graph.pic2bs4()
|
||||
|
||||
|
||||
async def init_bar_graph(data: dict, title: str) -> BuildMat:
|
||||
return await asyncio.get_event_loop().run_in_executor(None, _init_bar_graph, data, title)
|
||||
|
||||
|
||||
def _init_bar_graph(data: dict, title: str) -> BuildMat:
|
||||
bar_graph = BuildMat(
|
||||
y=[data[x] for x in data.keys() if data[x] != 0],
|
||||
mat_type="barh",
|
||||
title=title,
|
||||
x_index=[x for x in data.keys() if data[x] != 0],
|
||||
display_num=True,
|
||||
background=[
|
||||
f"{IMAGE_PATH}/background/create_mat/{x}"
|
||||
for x in os.listdir(f"{IMAGE_PATH}/background/create_mat")
|
||||
],
|
||||
bar_color=["*"],
|
||||
)
|
||||
return bar_graph
|
||||
|
||||
|
||||
def update_data(data: dict):
|
||||
tmp_dict = {}
|
||||
for day in data.keys():
|
||||
for plugin_name in data[day].keys():
|
||||
# print(f'{day}:{plugin_name} = {data[day][plugin_name]}')
|
||||
if data[day][plugin_name] is not None:
|
||||
if tmp_dict.get(plugin_name) is None:
|
||||
tmp_dict[plugin_name] = 1
|
||||
else:
|
||||
tmp_dict[plugin_name] += data[day][plugin_name]
|
||||
return tmp_dict
|
||||
@@ -96,7 +96,7 @@ async def _(
|
||||
global _prefix_count_dict
|
||||
if (
|
||||
matcher.type == "message"
|
||||
and matcher.priority not in [1, 9]
|
||||
and matcher.priority not in [1, 999]
|
||||
and matcher.plugin_name not in ["update_info", "statistics_handle"]
|
||||
):
|
||||
module = matcher.plugin_name
|
||||
|
||||
@@ -5,8 +5,8 @@ import asyncio
|
||||
import platform
|
||||
import os
|
||||
|
||||
if platform.system() == "Windows":
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
# if platform.system() == "Windows":
|
||||
# asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
|
||||
|
||||
url = "https://github.com/Mrs4s/go-cqhttp/releases"
|
||||
|
||||
@@ -12,7 +12,7 @@ __plugin_usage__ = """
|
||||
usage:
|
||||
普普通通的查天气吧
|
||||
指令:
|
||||
[城市]天气/天气[城市]
|
||||
[城市]天气
|
||||
""".strip()
|
||||
__plugin_des__ = "出门要看看天气,不要忘了带伞"
|
||||
__plugin_cmd__ = ["[城市]天气/天气[城市]"]
|
||||
@@ -27,13 +27,13 @@ __plugin_settings__ = {
|
||||
}
|
||||
|
||||
|
||||
weather = on_regex(r".{0,10}?(.*)的?天气.*?.{0,10}", priority=5, block=True)
|
||||
weather = on_regex(r".{0,10}?(.*)的?天气.{0,10}", priority=5, block=True)
|
||||
|
||||
|
||||
@weather.handle()
|
||||
async def _(event: MessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
|
||||
msg = reg_group[0]
|
||||
if msg[-1] != "市":
|
||||
if msg and msg[-1] != "市":
|
||||
msg += "市"
|
||||
city = ""
|
||||
if msg:
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
from configs.config import Config as gConfig
|
||||
from .api import *
|
||||
from .auth import *
|
||||
|
||||
|
||||
gConfig.add_plugin_config(
|
||||
"web-ui",
|
||||
"username",
|
||||
"admin",
|
||||
name="web-ui",
|
||||
help_="前端管理用户名"
|
||||
)
|
||||
|
||||
gConfig.add_plugin_config(
|
||||
"web-ui",
|
||||
"password",
|
||||
None,
|
||||
name="web-ui",
|
||||
help_="前端管理密码"
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
from .group import *
|
||||
from .plugins import *
|
||||
from .request import *
|
||||
from .system import *
|
||||
@@ -0,0 +1,61 @@
|
||||
from pydantic.error_wrappers import ValidationError
|
||||
from services.log import logger
|
||||
from utils.manager import group_manager
|
||||
from utils.utils import get_bot
|
||||
|
||||
from ..auth import Depends, User, token_to_user
|
||||
from ..config import *
|
||||
|
||||
|
||||
@app.get("/webui/group")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
获取群信息
|
||||
"""
|
||||
group_list_result = []
|
||||
group_info = {}
|
||||
if bot := get_bot():
|
||||
group_list = await bot.get_group_list()
|
||||
for g in group_list:
|
||||
group_info[g["group_id"]] = Group(**g)
|
||||
group_data = group_manager.get_data()
|
||||
for group_id in group_data["group_manager"]:
|
||||
try:
|
||||
task_list = []
|
||||
data = group_data["group_manager"][group_id]
|
||||
for tn, status in data["group_task_status"].items():
|
||||
task_list.append(
|
||||
Task(
|
||||
**{
|
||||
"name": tn,
|
||||
"nameZh": group_manager.get_task_data().get(tn) or tn,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
)
|
||||
data["task"] = task_list
|
||||
if x := group_info.get(int(group_id)):
|
||||
data["group"] = x
|
||||
else:
|
||||
continue
|
||||
try:
|
||||
group_list_result.append(GroupResult(**data))
|
||||
except ValidationError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"WEB_UI /webui/group 发生错误 {type(e)}:{e}")
|
||||
return Result(code=200, data=group_list_result)
|
||||
|
||||
|
||||
@app.post("/webui/group")
|
||||
async def _(group: GroupResult, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
修改群信息
|
||||
"""
|
||||
group_id = group.group.group_id
|
||||
group_manager.set_group_level(group_id, group.level)
|
||||
if group.status:
|
||||
group_manager.turn_on_group_bot_status(group_id)
|
||||
else:
|
||||
group_manager.shutdown_group_bot_status(group_id)
|
||||
return Result(code=200)
|
||||
@@ -0,0 +1,142 @@
|
||||
from configs.config import Config
|
||||
from services.log import logger
|
||||
from utils.manager import (plugins2block_manager, plugins2cd_manager,
|
||||
plugins2count_manager, plugins2settings_manager,
|
||||
plugins_manager)
|
||||
from utils.utils import get_matchers
|
||||
|
||||
from ..auth import Depends, User, token_to_user
|
||||
from ..config import *
|
||||
|
||||
plugin_name_list = None
|
||||
|
||||
|
||||
@app.get("/webui/plugins")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
获取插件列表
|
||||
:param type_: 类型 normal, superuser, hidden, admin
|
||||
"""
|
||||
global plugin_name_list
|
||||
if not plugin_name_list:
|
||||
plugin_name_list = [x.plugin_name for x in get_matchers()]
|
||||
plugin_list = []
|
||||
plugin_data = plugins_manager.get_data()
|
||||
for model in plugin_data:
|
||||
if model in plugin_name_list:
|
||||
try:
|
||||
data = plugin_data.get(model)
|
||||
data["model"] = model
|
||||
plugin_name = data.get("plugin_name")
|
||||
if (
|
||||
(type_ == "hidden" and "[hidden]" not in plugin_name.lower())
|
||||
or (type_ == "admin" and "[admin]" not in plugin_name.lower())
|
||||
or (
|
||||
type_ == "superuser"
|
||||
and "[superuser]" not in plugin_name.lower()
|
||||
)
|
||||
):
|
||||
continue
|
||||
if type_ == "normal" and (
|
||||
"[hidden]" in plugin_name.lower()
|
||||
or "[admin]" in plugin_name.lower()
|
||||
or "[superuser]" in plugin_name.lower()
|
||||
):
|
||||
continue
|
||||
data = {"model": model}
|
||||
if x := plugin_data.get(model):
|
||||
if not x.get("status") and x.get("block_type") in [
|
||||
"group",
|
||||
"private",
|
||||
"all",
|
||||
]:
|
||||
x["block_type"] = (
|
||||
"群聊"
|
||||
if x["block_type"] == "group"
|
||||
else "私聊"
|
||||
if x["block_type"] == "private"
|
||||
else "全部"
|
||||
)
|
||||
data["plugin_manager"] = PluginManager(**x)
|
||||
if x := plugins2settings_manager.get(model):
|
||||
if x.get("cmd") and isinstance(x.get("cmd"), list):
|
||||
x["cmd"] = ",".join(x["cmd"])
|
||||
data["plugin_settings"] = PluginSettings(**x)
|
||||
if x := plugins2cd_manager.get(model):
|
||||
data["cd_limit"] = CdLimit(**x)
|
||||
if x := plugins2block_manager.get(model):
|
||||
data["block_limit"] = BlockLimit(**x)
|
||||
if x := plugins2count_manager.get(model):
|
||||
data["count_limit"] = CountLimit(**x)
|
||||
if x := Config.get(model):
|
||||
id_ = 0
|
||||
tmp = []
|
||||
for key in x.keys():
|
||||
tmp.append(
|
||||
PluginConfig(
|
||||
**{
|
||||
"key": key,
|
||||
"help_": x[key].get("help"),
|
||||
"id": id_,
|
||||
**x[key],
|
||||
}
|
||||
)
|
||||
)
|
||||
id_ += 1
|
||||
data["plugin_config"] = tmp
|
||||
plugin_list.append(Plugin(**data))
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}"
|
||||
)
|
||||
return Result(
|
||||
code=500,
|
||||
data=f"WEB_UI GET /webui/plugins model:{model} 发生错误 {type(e)}:{e}",
|
||||
)
|
||||
return Result(code=200, data=plugin_list)
|
||||
|
||||
|
||||
@app.post("/webui/plugins")
|
||||
def _(plugin: Plugin, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
修改插件信息
|
||||
:param plugin: 插件内容
|
||||
"""
|
||||
try:
|
||||
if plugin.plugin_config:
|
||||
for c in plugin.plugin_config:
|
||||
if str(c.value).lower() in ["true", "false"] and (
|
||||
c.default_value is None or isinstance(c.default_value, bool)
|
||||
):
|
||||
c.value = True if str(c.value).lower() == "true" else False
|
||||
elif isinstance(
|
||||
Config.get_config(plugin.model, c.key, c.value), int
|
||||
) or isinstance(c.default_value, int):
|
||||
c.value = int(c.value)
|
||||
elif isinstance(
|
||||
Config.get_config(plugin.model, c.key, c.value), float
|
||||
) or isinstance(c.default_value, float):
|
||||
c.value = float(c.value)
|
||||
elif isinstance(c.value, str) and (
|
||||
isinstance(Config.get_config(plugin.model, c.key, c.value), list)
|
||||
or isinstance(c.default_value, list)
|
||||
):
|
||||
c.value = c.value.split(",")
|
||||
Config.set_config(plugin.model, c.key, c.value)
|
||||
Config.save(None, True)
|
||||
else:
|
||||
if plugin.plugin_settings:
|
||||
for key, value in plugin.plugin_settings:
|
||||
plugins2settings_manager.set_module_data(plugin.model, key, value)
|
||||
if plugin.plugin_manager:
|
||||
for key, value in plugin.plugin_manager:
|
||||
plugins_manager.set_module_data(plugin.model, key, value)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"WEB_UI POST /webui/plugins model:{plugin.model} 发生错误 {type(e)}:{e}"
|
||||
)
|
||||
return Result(
|
||||
code=500,
|
||||
data=f"WEB_UI POST /webui/plugins model:{plugin.model} 发生错误 {type(e)}:{e}",
|
||||
)
|
||||
return Result(code=200)
|
||||
@@ -0,0 +1,65 @@
|
||||
from utils.manager import requests_manager
|
||||
from ..auth import token_to_user, Depends, User
|
||||
from utils.utils import get_bot
|
||||
from models.group_info import GroupInfo
|
||||
from ..config import *
|
||||
|
||||
|
||||
@app.get("/webui/request")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
req_data = requests_manager.get_data()
|
||||
req_list = []
|
||||
if type_ in ["group", "private"]:
|
||||
req_data = req_data[type_]
|
||||
for x in req_data:
|
||||
req_data[x]["oid"] = x
|
||||
req_list.append(RequestResult(**req_data[x]))
|
||||
req_list.reverse()
|
||||
return Result(code=200, data=req_list)
|
||||
|
||||
|
||||
@app.delete("/webui/request")
|
||||
def _(type_: Optional[str], user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
清空请求
|
||||
:param type_: 类型
|
||||
"""
|
||||
requests_manager.clear(type_)
|
||||
return Result(code=200)
|
||||
|
||||
|
||||
@app.post("/webui/request")
|
||||
async def _(parma: RequestParma, user: User = Depends(token_to_user)) -> Result:
|
||||
"""
|
||||
操作请求
|
||||
:param parma: 参数
|
||||
"""
|
||||
result = "ok"
|
||||
flag = 3
|
||||
if bot := get_bot():
|
||||
if parma.handle == "approve":
|
||||
if parma.type == "group":
|
||||
rid = requests_manager.get_group_id(parma.id)
|
||||
if await GroupInfo.get_group_info(rid):
|
||||
await GroupInfo.set_group_flag(rid, 1)
|
||||
else:
|
||||
group_info = await bot.get_group_info(group_id=rid)
|
||||
await GroupInfo.add_group_info(
|
||||
rid,
|
||||
group_info["group_name"],
|
||||
group_info["max_member_count"],
|
||||
group_info["member_count"],
|
||||
1,
|
||||
)
|
||||
flag = await requests_manager.approve(bot, parma.id, parma.type)
|
||||
elif parma.handle == "refuse":
|
||||
flag = await requests_manager.refused(bot, parma.id, parma.type)
|
||||
elif parma.handle == "delete":
|
||||
requests_manager.delete_request(parma.id, parma.type)
|
||||
if parma.handle != "delete":
|
||||
if flag == 1:
|
||||
result = "该请求已失效"
|
||||
requests_manager.delete_request(parma.id, parma.type)
|
||||
elif flag == 2:
|
||||
result = "未找到此Id"
|
||||
return Result(code=200, data=result)
|
||||
@@ -0,0 +1,219 @@
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
import ujson as json
|
||||
from configs.path_config import (
|
||||
DATA_PATH,
|
||||
FONT_PATH,
|
||||
IMAGE_PATH,
|
||||
LOG_PATH,
|
||||
RECORD_PATH,
|
||||
TEMP_PATH,
|
||||
TEXT_PATH,
|
||||
)
|
||||
from services.log import logger
|
||||
from utils.http_utils import AsyncHttpx
|
||||
|
||||
from ..auth import Depends, User, token_to_user
|
||||
from ..config import *
|
||||
|
||||
CPU_DATA_PATH = DATA_PATH / "system" / "cpu.json"
|
||||
MEMORY_DATA_PATH = DATA_PATH / "system" / "memory.json"
|
||||
DISK_DATA_PATH = DATA_PATH / "system" / "disk.json"
|
||||
CPU_DATA_PATH.parent.mkdir(exist_ok=True, parents=True)
|
||||
cpu_data = {"data": []}
|
||||
memory_data = {"data": []}
|
||||
disk_data = {"data": []}
|
||||
|
||||
|
||||
@app.get("/webui/system")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
return await get_system_data()
|
||||
|
||||
|
||||
@app.get("/webui/system/status")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
return Result(
|
||||
code=200,
|
||||
data=await asyncio.get_event_loop().run_in_executor(None, _get_system_status),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/webui/system/disk")
|
||||
async def _(type_: Optional[str] = None, user: User = Depends(token_to_user)) -> Result:
|
||||
return Result(
|
||||
code=200,
|
||||
data=await asyncio.get_event_loop().run_in_executor(
|
||||
None, _get_system_disk, type_
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/webui/system/statusList")
|
||||
async def _(user: User = Depends(token_to_user)) -> Result:
|
||||
global cpu_data, memory_data, disk_data
|
||||
await asyncio.get_event_loop().run_in_executor(None, _get_system_status)
|
||||
cpu_rst = cpu_data["data"][-10:] if len(cpu_data["data"]) > 10 else cpu_data["data"]
|
||||
memory_rst = (
|
||||
memory_data["data"][-10:]
|
||||
if len(memory_data["data"]) > 10
|
||||
else memory_data["data"]
|
||||
)
|
||||
disk_rst = (
|
||||
disk_data["data"][-10:] if len(disk_data["data"]) > 10 else disk_data["data"]
|
||||
)
|
||||
return Result(
|
||||
code=200,
|
||||
data=SystemStatusList(
|
||||
cpu_data=cpu_rst,
|
||||
memory_data=memory_rst,
|
||||
disk_data=disk_rst,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def get_system_data():
|
||||
"""
|
||||
说明:
|
||||
获取系统信息,资源文件大小,网络状态等
|
||||
"""
|
||||
baidu = 200
|
||||
google = 200
|
||||
try:
|
||||
await AsyncHttpx.get("https://www.baidu.com/", timeout=5)
|
||||
except Exception as e:
|
||||
logger.warning(f"访问BaiDu失败... {type(e)}: {e}")
|
||||
baidu = 404
|
||||
try:
|
||||
await AsyncHttpx.get("https://www.google.com/", timeout=5)
|
||||
except Exception as e:
|
||||
logger.warning(f"访问Google失败... {type(e)}: {e}")
|
||||
google = 404
|
||||
network = SystemNetwork(baidu=baidu, google=google)
|
||||
disk = await asyncio.get_event_loop().run_in_executor(None, _get_system_disk)
|
||||
status = await asyncio.get_event_loop().run_in_executor(None, _get_system_status)
|
||||
return Result(
|
||||
code=200,
|
||||
data=SystemResult(
|
||||
status=status,
|
||||
network=network,
|
||||
disk=disk,
|
||||
check_time=datetime.now().replace(microsecond=0),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _get_system_status() -> SystemStatus:
|
||||
"""
|
||||
说明:
|
||||
获取系统信息等
|
||||
"""
|
||||
cpu = psutil.cpu_percent()
|
||||
memory = psutil.virtual_memory().percent
|
||||
disk = psutil.disk_usage("/").percent
|
||||
save_system_data(cpu, memory, disk)
|
||||
return SystemStatus(
|
||||
cpu=cpu,
|
||||
memory=memory,
|
||||
disk=disk,
|
||||
check_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
|
||||
|
||||
def _get_system_disk(
|
||||
type_: Optional[str],
|
||||
) -> Union[SystemFolderSize, Dict[str, Union[float, datetime]]]:
|
||||
"""
|
||||
说明:
|
||||
获取资源文件大小等
|
||||
"""
|
||||
if not type_:
|
||||
disk = SystemFolderSize(
|
||||
font_dir_size=_get_dir_size(FONT_PATH) / 1024 / 1024,
|
||||
image_dir_size=_get_dir_size(IMAGE_PATH) / 1024 / 1024,
|
||||
text_dir_size=_get_dir_size(TEXT_PATH) / 1024 / 1024,
|
||||
record_dir_size=_get_dir_size(RECORD_PATH) / 1024 / 1024,
|
||||
temp_dir_size=_get_dir_size(TEMP_PATH) / 1024 / 102,
|
||||
data_dir_size=_get_dir_size(DATA_PATH) / 1024 / 1024,
|
||||
log_dir_size=_get_dir_size(LOG_PATH) / 1024 / 1024,
|
||||
check_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
return disk
|
||||
else:
|
||||
if type_ == "image":
|
||||
dir_path = IMAGE_PATH
|
||||
elif type_ == "font":
|
||||
dir_path = FONT_PATH
|
||||
elif type_ == "text":
|
||||
dir_path = TEXT_PATH
|
||||
elif type_ == "record":
|
||||
dir_path = RECORD_PATH
|
||||
elif type_ == "data":
|
||||
dir_path = DATA_PATH
|
||||
elif type_ == "temp":
|
||||
dir_path = TEMP_PATH
|
||||
else:
|
||||
dir_path = LOG_PATH
|
||||
dir_map = {}
|
||||
other_file_size = 0
|
||||
for file in os.listdir(dir_path):
|
||||
file = Path(dir_path / file)
|
||||
if file.is_dir():
|
||||
dir_map[file.name] = _get_dir_size(file) / 1024 / 1024
|
||||
else:
|
||||
other_file_size += os.path.getsize(file) / 1024 / 1024
|
||||
dir_map["其他文件"] = other_file_size
|
||||
dir_map["check_time"] = datetime.now().replace(microsecond=0)
|
||||
return dir_map
|
||||
|
||||
|
||||
def _get_dir_size(dir_path: Path) -> float:
|
||||
"""
|
||||
说明:
|
||||
获取文件夹大小
|
||||
参数:
|
||||
:param dir_path: 文件夹路径
|
||||
"""
|
||||
size = 0
|
||||
for root, dirs, files in os.walk(dir_path):
|
||||
size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
|
||||
return size
|
||||
|
||||
|
||||
def save_system_data(cpu: float, memory: float, disk: float):
|
||||
"""
|
||||
说明:
|
||||
保存一些系统信息
|
||||
参数:
|
||||
:param cpu: cpu
|
||||
:param memory: memory
|
||||
:param disk: disk
|
||||
"""
|
||||
global cpu_data, memory_data, disk_data
|
||||
if CPU_DATA_PATH.exists() and not cpu_data["data"]:
|
||||
with open(CPU_DATA_PATH, "r") as f:
|
||||
cpu_data = json.load(f)
|
||||
if MEMORY_DATA_PATH.exists() and not memory_data["data"]:
|
||||
with open(MEMORY_DATA_PATH, "r") as f:
|
||||
memory_data = json.load(f)
|
||||
if DISK_DATA_PATH.exists() and not disk_data["data"]:
|
||||
with open(DISK_DATA_PATH, "r") as f:
|
||||
disk_data = json.load(f)
|
||||
now = str(datetime.now().time().replace(microsecond=0))
|
||||
cpu_data["data"].append({"time": now, "data": cpu})
|
||||
memory_data["data"].append({"time": now, "data": memory})
|
||||
disk_data["data"].append({"time": now, "data": disk})
|
||||
if len(cpu_data["data"]) > 50:
|
||||
cpu_data["data"] = cpu_data["data"][-50:]
|
||||
if len(memory_data["data"]) > 50:
|
||||
memory_data["data"] = memory_data["data"][-50:]
|
||||
if len(disk_data["data"]) > 50:
|
||||
disk_data["data"] = disk_data["data"][-50:]
|
||||
with open(CPU_DATA_PATH, "w") as f:
|
||||
json.dump(cpu_data, f, indent=4, ensure_ascii=False)
|
||||
with open(MEMORY_DATA_PATH, "w") as f:
|
||||
json.dump(memory_data, f, indent=4, ensure_ascii=False)
|
||||
with open(DISK_DATA_PATH, "w") as f:
|
||||
json.dump(disk_data, f, indent=4, ensure_ascii=False)
|
||||
@@ -0,0 +1,89 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
from starlette import status
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel
|
||||
from configs.config import Config
|
||||
from jose import JWTError, jwt
|
||||
import nonebot
|
||||
|
||||
app = nonebot.get_app()
|
||||
|
||||
|
||||
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="webui/login")
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
|
||||
|
||||
# USER_LIST = [
|
||||
# User(username="admin", password="123")
|
||||
# ]
|
||||
|
||||
|
||||
def get_user(uname: str) -> Optional[User]:
|
||||
username = Config.get_config("web-ui", "username")
|
||||
password = Config.get_config("web-ui", "password")
|
||||
if username and password and uname == username:
|
||||
return User(username=username, password=password)
|
||||
|
||||
|
||||
form_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
def create_token(user: User, expires_delta: Optional[timedelta] = None):
|
||||
expire = datetime.utcnow() + expires_delta or timedelta(minutes=15)
|
||||
return jwt.encode(
|
||||
claims={"sub": user.username, "exp": expire},
|
||||
key=SECRET_KEY,
|
||||
algorithm=ALGORITHM
|
||||
)
|
||||
|
||||
|
||||
@app.post("/webui/login")
|
||||
async def login_get_token(form_data: OAuth2PasswordRequestForm = Depends()):
|
||||
user: User = get_user(form_data.username)
|
||||
if not user or user.password != form_data.password:
|
||||
raise form_exception
|
||||
access_token = create_token(user=user, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
def token_to_user(token: str = Depends(oauth2_scheme)):
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username, expire = payload.get("sub"), payload.get("exp")
|
||||
user = get_user(username)
|
||||
if user is None:
|
||||
raise JWTError
|
||||
except JWTError:
|
||||
raise credentials_exception
|
||||
return user
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="127.0.0.1", port=8080)
|
||||
@@ -0,0 +1,212 @@
|
||||
from typing import Optional, List, Any, Union, Dict
|
||||
from pydantic import BaseModel
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from datetime import datetime
|
||||
import nonebot
|
||||
|
||||
|
||||
app = nonebot.get_app()
|
||||
|
||||
origins = ["http://localhost"]
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
class CdLimit(BaseModel):
|
||||
"""
|
||||
Cd 限制
|
||||
"""
|
||||
cd: int
|
||||
status: bool
|
||||
check_type: str
|
||||
limit_type: str
|
||||
rst: Optional[str]
|
||||
|
||||
|
||||
class BlockLimit(BaseModel):
|
||||
"""
|
||||
Block限制
|
||||
"""
|
||||
status: bool
|
||||
check_type: str
|
||||
limit_type: str
|
||||
rst: Optional[str]
|
||||
|
||||
|
||||
class CountLimit(BaseModel):
|
||||
"""
|
||||
Count限制
|
||||
"""
|
||||
max_count: int
|
||||
status: bool
|
||||
limit_type: bool
|
||||
rst: Optional[str]
|
||||
|
||||
|
||||
class PluginManager(BaseModel):
|
||||
"""
|
||||
插件信息
|
||||
"""
|
||||
plugin_name: str # 插件名称
|
||||
status: Optional[bool] # 插件状态
|
||||
error: Optional[bool] # 加载状态
|
||||
version: Optional[float] # 版本
|
||||
author: Optional[str] # 作者
|
||||
block_type: Optional[str] # 禁用类型
|
||||
|
||||
|
||||
class PluginSettings(BaseModel):
|
||||
"""
|
||||
插件基本设置
|
||||
"""
|
||||
level: Optional[int] # 群权限等级
|
||||
default_status: Optional[bool] # 默认开关
|
||||
limit_superuser: Optional[bool] # 是否限制超级用户
|
||||
cmd: Optional[str] # cmd别名
|
||||
cost_gold: Optional[int] # 花费金币限制
|
||||
plugin_type: Optional[List[Union[str, int]]] # 帮助类型
|
||||
|
||||
|
||||
class PluginConfig(BaseModel):
|
||||
"""
|
||||
插件配置项
|
||||
"""
|
||||
id: int
|
||||
key: str
|
||||
value: Optional[Any]
|
||||
help_: Optional[str]
|
||||
default_value: Optional[Any]
|
||||
|
||||
|
||||
class Plugin(BaseModel):
|
||||
"""
|
||||
插件
|
||||
"""
|
||||
model: str # 模块
|
||||
plugin_settings: Optional[PluginSettings]
|
||||
plugin_manager: Optional[PluginManager]
|
||||
plugin_config: Optional[List[PluginConfig]]
|
||||
cd_limit: Optional[CdLimit]
|
||||
block_limit: Optional[BlockLimit]
|
||||
count_limit: Optional[CountLimit]
|
||||
|
||||
|
||||
class Group(BaseModel):
|
||||
"""
|
||||
群组信息
|
||||
"""
|
||||
group_id: int
|
||||
group_name: str
|
||||
member_count: int
|
||||
max_member_count: int
|
||||
|
||||
|
||||
class Task(BaseModel):
|
||||
"""
|
||||
被动技能
|
||||
"""
|
||||
name: str
|
||||
nameZh: str
|
||||
status: bool
|
||||
|
||||
|
||||
class GroupResult(BaseModel):
|
||||
"""
|
||||
群组返回数据
|
||||
"""
|
||||
group: Group
|
||||
level: int
|
||||
status: bool
|
||||
close_plugins: List[str]
|
||||
task: List[Task]
|
||||
|
||||
|
||||
class RequestResult(BaseModel):
|
||||
"""
|
||||
好友/群组请求管理
|
||||
"""
|
||||
oid: str
|
||||
id: int
|
||||
flag: str
|
||||
nickname: Optional[str]
|
||||
level: Optional[int]
|
||||
sex: Optional[str]
|
||||
age: Optional[int]
|
||||
from_: Optional[str]
|
||||
comment: Optional[str]
|
||||
invite_group: Optional[int]
|
||||
group_name: Optional[str]
|
||||
|
||||
|
||||
class RequestParma(BaseModel):
|
||||
"""
|
||||
操作请求接收数据
|
||||
"""
|
||||
id: int
|
||||
handle: str
|
||||
type: str
|
||||
|
||||
|
||||
class SystemStatus(BaseModel):
|
||||
"""
|
||||
系统状态
|
||||
"""
|
||||
cpu: int
|
||||
memory: int
|
||||
disk: int
|
||||
check_time: datetime
|
||||
|
||||
|
||||
class SystemNetwork(BaseModel):
|
||||
"""
|
||||
系统网络状态
|
||||
"""
|
||||
baidu: int
|
||||
google: int
|
||||
|
||||
|
||||
class SystemFolderSize(BaseModel):
|
||||
"""
|
||||
资源文件占比
|
||||
"""
|
||||
font_dir_size: float
|
||||
image_dir_size: float
|
||||
text_dir_size: float
|
||||
record_dir_size: float
|
||||
temp_dir_size: float
|
||||
data_dir_size: float
|
||||
log_dir_size: float
|
||||
check_time: datetime
|
||||
|
||||
|
||||
class SystemStatusList(BaseModel):
|
||||
"""
|
||||
状态记录
|
||||
"""
|
||||
cpu_data: List[Dict[str, Union[float, str]]]
|
||||
memory_data: List[Dict[str, Union[float, str]]]
|
||||
disk_data: List[Dict[str, Union[float, str]]]
|
||||
|
||||
|
||||
class SystemResult(BaseModel):
|
||||
"""
|
||||
系统api返回
|
||||
"""
|
||||
status: SystemStatus
|
||||
network: SystemNetwork
|
||||
disk: SystemFolderSize
|
||||
check_time: datetime
|
||||
|
||||
|
||||
class Result(BaseModel):
|
||||
"""
|
||||
总体返回
|
||||
"""
|
||||
code: int
|
||||
data: Any
|
||||
@@ -1,8 +1,10 @@
|
||||
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message, Bot
|
||||
from nonebot.internal.params import ArgStr, Arg
|
||||
from nonebot.params import CommandArg
|
||||
|
||||
from .data_source import get_anime
|
||||
from nonebot import on_command
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.params import Arg
|
||||
from utils.utils import get_message_img
|
||||
from services.log import logger
|
||||
|
||||
@@ -31,10 +33,10 @@ what_anime = on_command("识番", priority=5, block=True)
|
||||
|
||||
|
||||
@what_anime.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State, args: Message = CommandArg()):
|
||||
img_url = get_message_img(event.json())
|
||||
if img_url:
|
||||
state["img_url"] = img_url[0]
|
||||
state["img_url"] = args
|
||||
|
||||
|
||||
@what_anime.got("img_url", prompt="虚空识番?来图来图GKD")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from configs.config import Config
|
||||
import nonebot
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
"word_bank",
|
||||
"WORD_BANK_LEVEL [LEVEL]",
|
||||
@@ -11,6 +10,25 @@ Config.add_plugin_config(
|
||||
default_value=5
|
||||
)
|
||||
|
||||
|
||||
Config.add_plugin_config(
|
||||
"word_bank",
|
||||
"WORD_BANK_FUZZY",
|
||||
False,
|
||||
help_="模糊匹配",
|
||||
default_value=False
|
||||
)
|
||||
Config.add_plugin_config(
|
||||
"word_bank",
|
||||
"WORD_BANK_KEY",
|
||||
True,
|
||||
help_="关键字匹配",
|
||||
default_value=True
|
||||
)
|
||||
Config.add_plugin_config(
|
||||
"word_bank",
|
||||
"WORD_BANK_MIX",
|
||||
25,
|
||||
help_="查看词条时图片内最多显示条数",
|
||||
default_value=25
|
||||
)
|
||||
nonebot.load_plugins("plugins/word_bank")
|
||||
|
||||
|
||||
@@ -5,12 +5,10 @@ from typing import Union
|
||||
class WordBankBuilder:
|
||||
|
||||
def __init__(self, user_id: int, group_id: int, problem: str):
|
||||
|
||||
self._data = {
|
||||
"user_id": user_id,
|
||||
"group_id": group_id,
|
||||
"problem": problem
|
||||
}
|
||||
"group_id": group_id}
|
||||
self.problem = problem
|
||||
|
||||
def set_placeholder(self, id_: int, placeholder: Union[str, int]):
|
||||
"""
|
||||
@@ -29,24 +27,28 @@ class WordBankBuilder:
|
||||
"""
|
||||
self._data["answer"] = answer
|
||||
|
||||
async def save(self):
|
||||
def set_problem(self, problem: str):
|
||||
"""
|
||||
设置问题
|
||||
:param problem: 问题
|
||||
"""
|
||||
self._data["problem"] = problem
|
||||
|
||||
async def save(self, search_type):
|
||||
user_id = self._data["user_id"]
|
||||
group_id = self._data["group_id"]
|
||||
problem = self._data["problem"]
|
||||
answer = self._data["answer"]
|
||||
placeholder = self._data.get("placeholder")
|
||||
await WordBank.add_problem_answer(user_id, group_id, problem, answer, placeholder)
|
||||
return await WordBank.add_problem_answer(user_id, group_id, search_type, problem, answer, placeholder)
|
||||
|
||||
async def update(self, index):
|
||||
user_id = self._data["user_id"]
|
||||
group_id = self._data["group_id"]
|
||||
problem = self._data["problem"]
|
||||
answer = self._data["answer"]
|
||||
placeholder = self._data.get("placeholder")
|
||||
return await WordBank.update_problem_answer(user_id, group_id, problem, answer, index, placeholder)
|
||||
|
||||
def __str__(self):
|
||||
return str(self._data)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import re
|
||||
|
||||
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Event
|
||||
from utils.utils import get_message_text
|
||||
from utils.utils import get_message_img_file
|
||||
from nonebot.typing import T_State
|
||||
from .model import WordBank
|
||||
|
||||
|
||||
async def check(bot: Bot, event: Event, state: T_State) -> bool:
|
||||
if isinstance(event, GroupMessageEvent):
|
||||
msg = event.raw_message
|
||||
list_img = get_message_img_file(event.json())
|
||||
if list_img:
|
||||
for img_file in list_img:
|
||||
strinfo = re.compile(f"{img_file},subType=\d*]")
|
||||
msg = strinfo.sub(f'{img_file}]', msg)
|
||||
return bool(
|
||||
await WordBank.check(event.group_id, get_message_text(event.json()), event.is_tome())
|
||||
await WordBank.check(event.group_id, msg, event.is_tome())
|
||||
)
|
||||
return False
|
||||
|
||||
@@ -3,38 +3,50 @@ from ._rule import check
|
||||
from .model import WordBank
|
||||
from configs.path_config import DATA_PATH
|
||||
from nonebot.adapters.onebot.v11 import GroupMessageEvent
|
||||
from utils.utils import get_message_text
|
||||
from utils.utils import get_message_at, get_message_img
|
||||
from nonebot import on_message
|
||||
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from utils.utils import get_message_img_file, is_number
|
||||
import re
|
||||
|
||||
__zx_plugin_name__ = "词库问答回复操作 [Hidden]"
|
||||
|
||||
|
||||
data_dir = DATA_PATH / "word_bank"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
message_handle = on_message(priority=5, block=True, rule=check)
|
||||
message_handle = on_message(priority=6, block=True, rule=check)
|
||||
|
||||
|
||||
@message_handle.handle()
|
||||
async def _(event: GroupMessageEvent):
|
||||
path = data_dir / f"{event.group_id}"
|
||||
msg = event.raw_message
|
||||
list_img = get_message_img_file(event.json())
|
||||
if list_img:
|
||||
for img_file in list_img:
|
||||
strinfo = re.compile(f"{img_file},subType=\d*]")
|
||||
msg = strinfo.sub(f'{img_file}]', msg)
|
||||
q = await WordBank.check(
|
||||
event.group_id, get_message_text(event.json()), event.is_tome()
|
||||
event.group_id, msg, event.is_tome()
|
||||
)
|
||||
await message_handle.send(await get_one_answer(event, q.format, q.answer))
|
||||
|
||||
|
||||
# 处理单条回答
|
||||
async def get_one_answer(event, format, _answer, all=1):
|
||||
path = data_dir / f"{event.group_id}"
|
||||
placeholder_list = (
|
||||
[
|
||||
(x.split("<_s>")[0], x.split("<_s>")[1])
|
||||
for x in q.format.split("<format>")[:-1]
|
||||
for x in format.split("<format>")[:-1]
|
||||
]
|
||||
if q.format
|
||||
if format
|
||||
else []
|
||||
)
|
||||
answer = ""
|
||||
_a = q.answer
|
||||
_a = _answer
|
||||
if not placeholder_list:
|
||||
answer = _a
|
||||
return answer
|
||||
else:
|
||||
for idx, placeholder in placeholder_list:
|
||||
if placeholder.endswith("jpg"):
|
||||
@@ -42,6 +54,76 @@ async def _(event: GroupMessageEvent):
|
||||
path / placeholder
|
||||
)
|
||||
else:
|
||||
answer += _a[: _a.find(f"[__placeholder_{idx}]")] + at(placeholder)
|
||||
_a = _a[_a.find(f"[__placeholder_{idx}]") + len(f"[__placeholder_{idx}]") :]
|
||||
await message_handle.send(answer)
|
||||
if all == 1:
|
||||
answer += _a[: _a.find(f"[__placeholder_{idx}]")] + at(placeholder)
|
||||
else:
|
||||
q = await GroupInfoUser.get_member_info(
|
||||
int(placeholder), event.group_id)
|
||||
answer += _a[: _a.find(f"[__placeholder_{idx}]")] + "@" + q.user_name
|
||||
_a = _a[_a.find(f"[__placeholder_{idx}]") + len(f"[__placeholder_{idx}]"):]
|
||||
return answer + _a
|
||||
|
||||
|
||||
# 处理单条问题
|
||||
async def get_one_problem(event, problem):
|
||||
strinfo = re.compile(f",subType=\d")
|
||||
problem = strinfo.sub('', problem)
|
||||
_problem = problem
|
||||
_p = problem
|
||||
problem = ''
|
||||
for img in get_message_img(event.json()):
|
||||
_x = img.split("?")[0]
|
||||
r = re.search(rf"\[CQ:image,file=(.*),url={_x}.*?]", _p)
|
||||
if r:
|
||||
_problem = _problem.replace(
|
||||
rf",url={img}",
|
||||
f"",
|
||||
)
|
||||
problem += _p[: _p.find(f"[CQ:image,file={r.group(1)},url={img}]")] + image(img)
|
||||
_p = _p[
|
||||
_p.find(f"[CQ:image,file={r.group(1)},url={img}]") + len(f"[CQ:image,file={r.group(1)},url={img}]"):]
|
||||
for at_ in get_message_at(event.json()):
|
||||
r = re.search(rf"\[CQ:at,qq={at_}]", problem)
|
||||
if r:
|
||||
q = await GroupInfoUser.get_member_info(
|
||||
int(at_), event.group_id)
|
||||
problem += _p[: _p.find(f"[CQ:at,qq={at_}]")] + "@" + q.user_name
|
||||
_p = _p[_p.find(f"[CQ:at,qq={at_}]") + len(f"[CQ:at,qq={at_}]"):]
|
||||
return _problem, problem + _p
|
||||
|
||||
|
||||
# 显示单条数据库问题
|
||||
async def get_one_image_problem(event, problem):
|
||||
path = data_dir / f"{event.group_id}" / "problem"
|
||||
placeholder_list = []
|
||||
idx = 0
|
||||
img_list = re.findall(rf"\[CQ:image,file=(.*?)]", problem)
|
||||
at_list = re.findall(rf"\[CQ:at,qq=(.*?)]", problem)
|
||||
if img_list:
|
||||
for img in img_list:
|
||||
problem = problem.replace(f'[CQ:image,file={img}]', f'[__placeholder_{idx}]', 1)
|
||||
placeholder_list.append([idx, img])
|
||||
idx += 1
|
||||
if at_list:
|
||||
for ats in at_list:
|
||||
problem = problem.replace(f'[CQ:at,qq={ats}]', f'[__placeholder_{idx}]', 1)
|
||||
placeholder_list.append([idx, ats])
|
||||
idx += 1
|
||||
_p = problem
|
||||
problem = ''
|
||||
if not placeholder_list:
|
||||
problem = _p
|
||||
return problem
|
||||
else:
|
||||
for idx, placeholder in placeholder_list:
|
||||
if is_number(placeholder):
|
||||
q = await GroupInfoUser.get_member_info(
|
||||
int(placeholder), event.group_id)
|
||||
problem += _p[: _p.find(f"[__placeholder_{idx}]")] + "@" + q.user_name
|
||||
else:
|
||||
problem += _p[: _p.find(f"[__placeholder_{idx}]")] + image(
|
||||
path / f"{placeholder}.jpg"
|
||||
)
|
||||
_p = _p[_p.find(f"[__placeholder_{idx}]") + len(f"[__placeholder_{idx}]"):]
|
||||
|
||||
return problem + _p
|
||||
|
||||
+121
-44
@@ -5,6 +5,7 @@ from pathlib import Path
|
||||
from configs.path_config import DATA_PATH
|
||||
import re
|
||||
import random
|
||||
from configs.config import Config
|
||||
|
||||
|
||||
class WordBank(db.Model):
|
||||
@@ -21,17 +22,19 @@ class WordBank(db.Model):
|
||||
|
||||
@classmethod
|
||||
async def add_problem_answer(
|
||||
cls,
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
problem: str,
|
||||
answer: str,
|
||||
format_: Optional[List[Tuple[int, Union[int, str]]]],
|
||||
cls,
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
search_type: [int],
|
||||
problem: str,
|
||||
answer: str,
|
||||
format_: Optional[List[Tuple[int, Union[int, str]]]],
|
||||
) -> bool:
|
||||
"""
|
||||
添加或新增一个问答
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
:search_type: 问题类型,
|
||||
:param problem: 问题
|
||||
:param answer: 回答
|
||||
:param format_: 格式化数据
|
||||
@@ -42,12 +45,12 @@ class WordBank(db.Model):
|
||||
for x, y in format_:
|
||||
_str += f"{x}<_s>{y}<format>"
|
||||
return await cls._problem_answer_handle(
|
||||
user_id, group_id, problem, "add", answer=answer, format_=_str
|
||||
user_id, group_id, problem, "add", search_type=search_type, answer=answer, format_=_str
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def delete_problem_answer(
|
||||
cls, user_id: int, group_id: Optional[int], problem: str, index: Optional[int]
|
||||
cls, user_id: int, group_id: Optional[int], problem: str, index: Optional[int]
|
||||
) -> str:
|
||||
"""
|
||||
删除某问题一个或全部回答
|
||||
@@ -60,9 +63,35 @@ class WordBank(db.Model):
|
||||
user_id, group_id, problem, "delete", index=index
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def update_problem_answer(
|
||||
cls,
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
problem: str,
|
||||
answer: str,
|
||||
index: Optional[int],
|
||||
format_: Optional[List[Tuple[int, Union[int, str]]]],
|
||||
) -> str:
|
||||
"""
|
||||
修改某问题一个或全部回答
|
||||
:param user_id: 用户id
|
||||
:param group_id: 群号
|
||||
:param problem: 问题
|
||||
:param index: 回答下标
|
||||
"""
|
||||
_str = None
|
||||
if format_:
|
||||
_str = ""
|
||||
for x, y in format_:
|
||||
_str += f"{x}<_s>{y}<format>"
|
||||
return await cls._problem_answer_handle(
|
||||
user_id, group_id, problem, "update", answer=answer, index=index, format_=_str
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def get_problem_answer(
|
||||
cls, user_id: int, group_id: Optional[int], problem: str
|
||||
cls, user_id: int, group_id: Optional[int], problem: str
|
||||
) -> List[str]:
|
||||
"""
|
||||
获取问题的所有回答
|
||||
@@ -79,15 +108,11 @@ class WordBank(db.Model):
|
||||
:param group_id: 群号
|
||||
:param problem: 问题
|
||||
"""
|
||||
if problem.startswith("id:"):
|
||||
problem_index = int(problem.split(":")[-1])
|
||||
q = await cls.get_group_all_problem(group_id)
|
||||
if len(q) > problem_index:
|
||||
problem = q[problem_index]
|
||||
q = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.problem == problem)
|
||||
).gino.all()
|
||||
return [x.answer for x in q] if q else None
|
||||
|
||||
return [(x.answer, x.format) for x in q] if q else None
|
||||
|
||||
@classmethod
|
||||
async def get_group_all_problem(cls, group_id: int) -> List[str]:
|
||||
@@ -128,22 +153,45 @@ class WordBank(db.Model):
|
||||
return x
|
||||
return None
|
||||
else:
|
||||
q = await cls.query.where(
|
||||
(cls.group_id == group_id) & (cls.problem == problem)
|
||||
).gino.all()
|
||||
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(
|
||||
(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
|
||||
|
||||
@classmethod
|
||||
async def _problem_answer_handle(
|
||||
cls,
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
problem: str,
|
||||
type_: str,
|
||||
*,
|
||||
answer: Optional[str] = None,
|
||||
index: Optional[int] = None,
|
||||
format_: Optional[str] = None,
|
||||
cls,
|
||||
user_id: int,
|
||||
group_id: Optional[int],
|
||||
problem: str,
|
||||
type_: str,
|
||||
*,
|
||||
search_type: [int] = 0,
|
||||
answer: Optional[str] = None,
|
||||
index: Optional[int] = None,
|
||||
format_: Optional[str] = None,
|
||||
) -> Union[List[Union[str, Tuple[str, str]]], bool, str]:
|
||||
"""
|
||||
添加或新增一个问答
|
||||
@@ -166,27 +214,27 @@ class WordBank(db.Model):
|
||||
else:
|
||||
q = cls.query.where((cls.user_qq == user_id) & (cls.problem == problem))
|
||||
if type_ == "add":
|
||||
q = await q.where(cls.answer == answer).gino.all()
|
||||
if not q or ".jpg" in format_:
|
||||
await cls.create(
|
||||
user_qq=user_id,
|
||||
group_id=group_id,
|
||||
problem=problem,
|
||||
answer=answer,
|
||||
format=format_,
|
||||
create_time=datetime.now().date(),
|
||||
update_time=datetime.now().date(),
|
||||
)
|
||||
q = await q.where((cls.answer == answer) & (cls.search_type == search_type)).gino.all()
|
||||
try:
|
||||
if not q or ".jpg" in format_:
|
||||
await cls.create(
|
||||
user_qq=user_id,
|
||||
group_id=group_id,
|
||||
search_type=search_type,
|
||||
problem=problem,
|
||||
answer=answer,
|
||||
format=format_,
|
||||
create_time=datetime.now().replace(microsecond=0),
|
||||
update_time=datetime.now().replace(microsecond=0),
|
||||
)
|
||||
except:
|
||||
return False
|
||||
return True
|
||||
elif type_ == "delete":
|
||||
q = await q.with_for_update().gino.all()
|
||||
if q:
|
||||
path = DATA_PATH / "word_bank" / f"{group_id}"
|
||||
if index is not None:
|
||||
_q = [x.problem for x in q]
|
||||
_q.sort()
|
||||
prob = _q[index]
|
||||
index = [x.problem for x in q].index(prob)
|
||||
q = [q[index]]
|
||||
answer = "\n".join([x.answer for x in q])
|
||||
for x in q:
|
||||
@@ -199,14 +247,43 @@ class WordBank(db.Model):
|
||||
if _path.exists():
|
||||
_path.unlink()
|
||||
await cls.delete.where(
|
||||
(cls.problem == problem)
|
||||
(cls.update_time == x.update_time)
|
||||
& (cls.problem == problem)
|
||||
& (cls.answer == x.answer)
|
||||
& (cls.group_id == group_id)
|
||||
).gino.status()
|
||||
return answer
|
||||
elif type_ == "update":
|
||||
new_format = format_
|
||||
new_answer = answer
|
||||
q = await q.with_for_update().gino.all()
|
||||
if q:
|
||||
path = DATA_PATH / "word_bank" / f"{group_id}"
|
||||
if index is not None:
|
||||
q = [q[index]]
|
||||
else:
|
||||
q = [q[0]]
|
||||
for x in q:
|
||||
format_ = x.format
|
||||
if format_:
|
||||
for sp in format_.split("<format>")[:-1]:
|
||||
_, image_name = sp.split("<_s>")
|
||||
if image_name.endswith("jpg"):
|
||||
_path = path / image_name
|
||||
if _path.exists():
|
||||
_path.unlink()
|
||||
await cls.update.values(answer=new_answer,
|
||||
format=new_format,
|
||||
update_time=datetime.now().replace(microsecond=0), ).where(
|
||||
(cls.problem == problem)
|
||||
& (cls.answer == x.answer)
|
||||
& (cls.group_id == group_id)
|
||||
& (cls.group_id == group_id)
|
||||
& (cls.update_time == x.update_time)
|
||||
).gino.status()
|
||||
return True
|
||||
elif type_ == "get":
|
||||
q = await q.gino.all()
|
||||
if q:
|
||||
return [(x.answer, x.format.split("<format>")[:-1]) for x in q]
|
||||
return False
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ from services.log import logger
|
||||
from configs.path_config import DATA_PATH
|
||||
from utils.http_utils import AsyncHttpx
|
||||
from ._data_source import WordBankBuilder
|
||||
from configs.config import Config
|
||||
from utils.message_builder import image
|
||||
from utils.image_utils import text2image
|
||||
from .message_handle import get_one_answer, get_one_problem, get_one_image_problem
|
||||
from .model import WordBank
|
||||
from nonebot.adapters.onebot.v11 import (
|
||||
Bot,
|
||||
@@ -18,6 +18,8 @@ from nonebot import on_command
|
||||
import random
|
||||
import os
|
||||
import re
|
||||
from configs.config import NICKNAME, Config
|
||||
from models.group_member_info import GroupInfoUser
|
||||
|
||||
__zx_plugin_name__ = "词库问答 [Admin]"
|
||||
__plugin_usage__ = """
|
||||
@@ -25,45 +27,51 @@ usage:
|
||||
对指定问题的随机回答,对相同问题可以设置多个不同回答
|
||||
删除词条后每个词条的id可能会变化,请查看后再删除
|
||||
指令:
|
||||
添加词条问...答...:添加问答词条,可重复添加相同问题的不同回答
|
||||
添加词条 ?[模糊/关键字|词]...答...:添加问答词条,可重复添加相同问题的不同回答
|
||||
删除词条 [问题/下标] ?[下标]:删除指定词条指定或全部回答
|
||||
修改词条 [问题/下标] ?[下标/新回答] [新回答]:修改指定词条指定回答默认修改为第一条
|
||||
查看词条 ?[问题/下标]:查看全部词条或对应词条回答
|
||||
示例:添加词条问谁是萝莉答是我
|
||||
示例:删除词条 谁是萝莉
|
||||
示例:删除词条 谁是萝莉 0
|
||||
示例:删除词条 id:0
|
||||
示例:修改词条 谁是萝莉 是你
|
||||
示例:修改词条 谁是萝莉 0 是你
|
||||
示例:修改词条 id:0 是你
|
||||
示例:查看词条
|
||||
示例:查看词条 谁是萝莉
|
||||
示例:查看词条 id:0
|
||||
""".strip()
|
||||
__plugin_des__ = "自定义词条内容随机回复"
|
||||
__plugin_cmd__ = [
|
||||
"添加词条问...答..",
|
||||
"添加词条 ?[模糊/关键字]问...答..",
|
||||
"删除词条 [问题/下标] ?[下标]",
|
||||
"修改词条 [问题/下标] ?[下标/新回答] [新回答]",
|
||||
"查看词条 ?[问题/下标]",
|
||||
]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "HibiKier"
|
||||
__plugin_version__ = 0.3
|
||||
__plugin_author__ = "HibiKier & yajiwa"
|
||||
__plugin_settings__ = {
|
||||
"admin_level": Config.get_config("word_bank", "WORD_BANK_LEVEL"),
|
||||
"cmd": ["词库问答", "添加词条", "删除词条", "查看词条"],
|
||||
"admin_level": Config.get_config("word_bank", "WORD_BANK_LEVEL [LEVEL]"),
|
||||
"cmd": ["词库问答", "添加词条", "删除词条", "修改词条", "查看词条"],
|
||||
}
|
||||
|
||||
data_dir = DATA_PATH / "word_bank"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
add_word = on_command("添加词条", priority=5, block=True)
|
||||
|
||||
delete_word = on_command("删除词条", priority=5, block=True)
|
||||
|
||||
update_word = on_command("修改词条", priority=5, block=True)
|
||||
|
||||
show_word = on_command("显示词条", aliases={"查看词条"}, priority=5, block=True)
|
||||
|
||||
|
||||
@add_word.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = CommandArg()):
|
||||
msg = str(arg)
|
||||
r = re.search(r"^问(.+)\s?答([\s\S]*)", msg)
|
||||
r = re.search(r"问(.+)\s?答([\s\S]*)", msg)
|
||||
if not r:
|
||||
await add_word.finish("未检测到词条问题...")
|
||||
problem = r.group(1).strip()
|
||||
@@ -75,47 +83,26 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = C
|
||||
idx = 0
|
||||
for n in bot.config.nickname:
|
||||
if n and problem.startswith(n):
|
||||
_problem = f"[_to_me|{n}]" + problem[len(n) :]
|
||||
_problem = f"[_to_me|{n}]" + problem[len(n):]
|
||||
break
|
||||
else:
|
||||
_problem = problem
|
||||
(data_dir / f"{event.group_id}").mkdir(exist_ok=True, parents=True)
|
||||
_builder = WordBankBuilder(event.user_id, event.group_id, _problem)
|
||||
for at_ in get_message_at(event.json()):
|
||||
r = re.search(rf"\[CQ:at,qq={at_}]", answer)
|
||||
if r:
|
||||
answer = answer.replace(f"[CQ:at,qq={at_}]", f"[__placeholder_{idx}]", 1)
|
||||
_builder.set_placeholder(idx, at_)
|
||||
idx += 1
|
||||
for img in get_message_img(event.json()):
|
||||
_x = img.split("?")[0]
|
||||
r = re.search(rf"\[CQ:image,file=(.*),url={_x}.*?]", answer)
|
||||
if r:
|
||||
rand = random.randint(1, 10000) + random.randint(1, 114514)
|
||||
for _ in range(10):
|
||||
if f"__placeholder_{rand}_{idx}.jpg" not in os.listdir(data_dir / f"{event.group_id}"):
|
||||
break
|
||||
rand = random.randint(1, 10000) + random.randint(1, 114514)
|
||||
for i in range(3):
|
||||
answer = answer.replace(f",subType={i}", "")
|
||||
answer = answer.replace(
|
||||
rf"[CQ:image,file={r.group(1)},url={img}]",
|
||||
f"[__placeholder_{idx}]",
|
||||
)
|
||||
await AsyncHttpx.download_file(
|
||||
img, data_dir / f"{event.group_id}" / f"__placeholder_{rand}_{idx}.jpg"
|
||||
)
|
||||
_builder.set_placeholder(idx, f"__placeholder_{rand}_{idx}.jpg")
|
||||
idx += 1
|
||||
_builder.set_answer(answer)
|
||||
await _builder.save()
|
||||
logger.info(f"已保存词条 问:{problem} 答:{msg}")
|
||||
await add_word.send(f"已保存词条:{problem}")
|
||||
search_type = 0
|
||||
if re.search("^关键字|词(.*)", msg):
|
||||
search_type = 1
|
||||
elif re.search("^模糊(.*)", msg):
|
||||
search_type = 2
|
||||
_builder = await get__builder(event, _problem, answer, idx)
|
||||
if await _builder.save(search_type):
|
||||
logger.info(f"已保存词条 问:{_builder.problem} 答:{msg}")
|
||||
await add_word.send("已保存词条:" + _builder.problem)
|
||||
else:
|
||||
await delete_word.send("保存失败,可能是回答重复")
|
||||
|
||||
|
||||
@delete_word.handle()
|
||||
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
msg = str(arg).strip()
|
||||
if not msg:
|
||||
await delete_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
|
||||
index = None
|
||||
@@ -133,42 +120,199 @@ async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
if p:
|
||||
problem = p[int(x)]
|
||||
try:
|
||||
_problem, problem = await get_one_problem(event, problem)
|
||||
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(f"删除词条成功:{problem}\n回答:\n{answer}")
|
||||
await delete_word.send("删除词条成功:" + problem + f"\n回答:\n{answer}")
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP "
|
||||
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 删除词条: {problem}"
|
||||
)
|
||||
else:
|
||||
await delete_word.send(f"删除词条:{problem} 失败,可能该词条不存在")
|
||||
await delete_word.send("删除词条:" + problem + "失败,可能该词条不存在")
|
||||
except IndexError:
|
||||
await delete_word.send("指定下标错误...请通过查看词条来确定..")
|
||||
|
||||
|
||||
@update_word.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
msg = str(arg)
|
||||
if not msg:
|
||||
await update_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
|
||||
index = None
|
||||
new_answer = None
|
||||
problem = None
|
||||
_sp_msg = msg.split()
|
||||
len_msg = len(_sp_msg)
|
||||
if 1 < len_msg:
|
||||
problem = "".join(_sp_msg[0])
|
||||
if len_msg == 3:
|
||||
if is_number(_sp_msg[1]):
|
||||
index = int(_sp_msg[1])
|
||||
new_answer = "".join(_sp_msg[2:])
|
||||
else:
|
||||
new_answer = "".join(_sp_msg[1:])
|
||||
else:
|
||||
await update_word.finish("此命令之后需要跟随修改内容")
|
||||
idx = 0
|
||||
for n in bot.config.nickname:
|
||||
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)
|
||||
|
||||
try:
|
||||
if await _builder.update(index):
|
||||
await update_word.send(f"修改词条成功:" + _builder.problem)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP "
|
||||
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
|
||||
f" 修改词条: {problem}"
|
||||
)
|
||||
else:
|
||||
await update_word.send(f"修改词条:" + _builder.problem + f"失败,可能该词条不存在")
|
||||
except IndexError:
|
||||
await update_word.send("指定下标错误...请通过查看词条来确定..")
|
||||
|
||||
|
||||
@show_word.handle()
|
||||
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
msg = arg.extract_plain_text().strip()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
|
||||
msg = str(arg).strip()
|
||||
if not msg:
|
||||
_problem_list = await WordBank.get_group_all_problem(event.group_id)
|
||||
if not _problem_list:
|
||||
await show_word.finish("该群未收录任何词条..")
|
||||
_problem_list = [f"\t{i}. {x}" for i, x in enumerate(_problem_list)]
|
||||
await show_word.send(
|
||||
image(
|
||||
b64=(await text2image(
|
||||
"该群已收录的词条:\n\n" + "\n".join(_problem_list),
|
||||
padding=10,
|
||||
color="#f9f6f2",
|
||||
)).pic2bs4()
|
||||
long_problem_list = len(_problem_list)
|
||||
max_line = Config.get_config("word_bank", "WORD_BANK_MIX")
|
||||
if long_problem_list > max_line:
|
||||
pic_list = []
|
||||
mes_list = []
|
||||
img_nu = long_problem_list // max_line
|
||||
one_msg = "该群已收录的词条:"
|
||||
await show_word.send(one_msg)
|
||||
for i in range(img_nu + 1):
|
||||
if _problem_list:
|
||||
one_img = image(
|
||||
b64=(await text2image("\n".join(_problem_list[:max_line]),
|
||||
padding=10,
|
||||
color="#f9f6f2",
|
||||
)).pic2bs4()
|
||||
)
|
||||
if img_nu > 2:
|
||||
pic_list.append(one_img)
|
||||
else:
|
||||
await show_word.send(one_img)
|
||||
del _problem_list[:max_line]
|
||||
if pic_list:
|
||||
for img in pic_list:
|
||||
data = {
|
||||
"type": "node",
|
||||
"data": {"name": f"{NICKNAME}", "uin": f"{bot.self_id}", "content": img},
|
||||
}
|
||||
mes_list.append(data)
|
||||
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
|
||||
else:
|
||||
await show_word.send(
|
||||
image(
|
||||
b64=(await text2image(
|
||||
"该群已收录的词条:\n\n" + "\n".join(_problem_list),
|
||||
padding=10,
|
||||
color="#f9f6f2",
|
||||
)).pic2bs4()
|
||||
)
|
||||
)
|
||||
)
|
||||
else:
|
||||
_answer_list = await WordBank.get_group_all_answer(event.group_id, msg)
|
||||
_answer_list = []
|
||||
if msg.startswith("id:"):
|
||||
x = msg.split(":")[-1]
|
||||
if not is_number(x) or int(x) < 0:
|
||||
return await delete_word.finish("id必须为数字且符合规范!")
|
||||
p = await WordBank.get_group_all_problem(event.group_id)
|
||||
if p:
|
||||
_problem = p[int(x)]
|
||||
_answer_list = await WordBank.get_group_all_answer(event.group_id, _problem)
|
||||
msg += '问' + await get_one_image_problem(event, _problem)
|
||||
else:
|
||||
_problem, msg = await get_one_problem(event, msg)
|
||||
_answer_list = await WordBank.get_group_all_answer(event.group_id, _problem)
|
||||
if not _answer_list:
|
||||
await show_word.send("未收录该词条...")
|
||||
|
||||
else:
|
||||
_answer_list = [f"{i}. {x}" for i, x in enumerate(_answer_list)]
|
||||
await show_word.send(f"词条 {msg} 回答:\n" + "\n".join(_answer_list))
|
||||
# 解析图片和@
|
||||
_answer_img_nu_list = [await get_one_answer(event, format, answer, 0) for answer, format in _answer_list]
|
||||
word_nu = len(_answer_img_nu_list)
|
||||
img_nu = 0
|
||||
answer = "词条" + msg + "回答:"
|
||||
for i, x, in enumerate(_answer_img_nu_list):
|
||||
r = re.findall(rf"\[CQ:image,file=", str(x))
|
||||
if r:
|
||||
img_nu += len(r)
|
||||
answer += "\n" + f"{i}." + x
|
||||
if (img_nu > 2 and word_nu > 5) or word_nu > 10 or img_nu > 4:
|
||||
data = {
|
||||
"type": "node",
|
||||
"data": {"name": f"{NICKNAME}", "uin": f"{bot.self_id}", "content": answer},
|
||||
}
|
||||
await bot.send_group_forward_msg(group_id=event.group_id, messages=data)
|
||||
else:
|
||||
await show_word.send(answer)
|
||||
# await show_word.send(f"词条 {msg} 回答:\n" + "\n".join(_answer_list))
|
||||
|
||||
|
||||
async def get__builder(event, _problem, answer, idx):
|
||||
(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)
|
||||
_builder = WordBankBuilder(event.user_id, event.group_id, _problem)
|
||||
problem = ''
|
||||
_p = _problem
|
||||
for at_ in get_message_at(event.json()):
|
||||
r = re.search(rf"\[CQ:at,qq={at_}]", answer)
|
||||
if r:
|
||||
answer = answer.replace(f"[CQ:at,qq={at_}]", f"[__placeholder_{idx}]", 1)
|
||||
_builder.set_placeholder(idx, at_)
|
||||
idx += 1
|
||||
r_problem = re.search(rf"\[CQ:at,qq={at_}]", _problem)
|
||||
if r_problem:
|
||||
q = await GroupInfoUser.get_member_info(
|
||||
int(at_), event.group_id)
|
||||
problem += _p[: _p.find(f"[CQ:at,qq={at_}]")] + "@" + q.user_name
|
||||
_p = _p[_p.find(f"[CQ:at,qq={at_}]") + len(f"[CQ:at,qq={at_}]"):]
|
||||
for img in get_message_img(event.json()):
|
||||
_x = img.split("?")[0]
|
||||
_x_list = img.split("?")
|
||||
r = re.search(rf"\[CQ:image,file=(.*),url={_x}.*?]", answer)
|
||||
if r:
|
||||
rand = random.randint(1, 10000) + random.randint(1, 114514)
|
||||
for _ in range(10):
|
||||
if f"__placeholder_{rand}_{idx}.jpg" not in os.listdir(data_dir / f"{event.group_id}"):
|
||||
break
|
||||
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*?]")
|
||||
answer = strinfo.sub(f"[__placeholder_{idx}]", answer)
|
||||
await AsyncHttpx.download_file(
|
||||
img, data_dir / f"{event.group_id}" / f"__placeholder_{rand}_{idx}.jpg"
|
||||
)
|
||||
_builder.set_placeholder(idx, f"__placeholder_{rand}_{idx}.jpg")
|
||||
idx += 1
|
||||
r_problem = re.search(rf"\[CQ:image,file=(.*?),url={_x}.*?]", _p)
|
||||
if r_problem:
|
||||
strinfo = re.compile(f",url={_x_list[0]}\?{_x_list[1]},subType=\d*?]")
|
||||
_problem = strinfo.sub(f"]", _problem)
|
||||
_p = strinfo.sub(f"]", _p)
|
||||
problem += _p[: _p.find(f"[CQ:image,file={r_problem.group(1)}]")] + image(img)
|
||||
_p = _p[_p.find(f"[CQ:image,file={r_problem.group(1)}]") + len(f"[CQ:image,file={r_problem.group(1)}]"):]
|
||||
problem_img = r_problem.group(1)
|
||||
if f"{problem_img}.jpg" not in os.listdir(data_dir / f"{event.group_id}" / f"problem"):
|
||||
await AsyncHttpx.download_file(
|
||||
img, data_dir / f"{event.group_id}" / f"problem" / f"{problem_img}.jpg"
|
||||
)
|
||||
_builder.set_answer(answer)
|
||||
_builder.set_problem(_problem)
|
||||
_builder.problem = problem + _p
|
||||
return _builder
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Tuple, Union
|
||||
import pytz
|
||||
from nonebot import on_command, get_driver
|
||||
from nonebot.adapters.onebot.v11 import Message, MessageSegment
|
||||
from nonebot.adapters.onebot.v11.event import GroupMessageEvent
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.params import Arg, Command, CommandArg, Depends
|
||||
from nonebot.typing import T_State
|
||||
from .data_source import draw_word_cloud, get_list_msg
|
||||
from configs.config import Config
|
||||
|
||||
__zx_plugin_name__ = "词云"
|
||||
|
||||
__plugin_usage__ = """
|
||||
usage:
|
||||
词云
|
||||
指令:
|
||||
今日词云:获取今天的词云
|
||||
昨日词云:获取昨天的词云
|
||||
本周词云:获取本周词云
|
||||
本月词云:获取本月词云
|
||||
年度词云:获取年度词云
|
||||
|
||||
历史词云(支持 ISO8601 格式的日期与时间,如 2022-02-22T22:22:22)
|
||||
获取某日的词云
|
||||
历史词云 2022-01-01
|
||||
获取指定时间段的词云
|
||||
历史词云
|
||||
示例:历史词云 2022-01-01~2022-02-22
|
||||
示例:历史词云 2022-02-22T11:11:11~2022-02-22T22:22:22
|
||||
|
||||
如果想要获取自己的发言,可在命令前添加 我的
|
||||
示例:我的今日词云
|
||||
""".strip()
|
||||
__plugin_des__ = "词云"
|
||||
__plugin_cmd__ = ["今日词云", "昨日词云", "本周词云"]
|
||||
__plugin_version__ = 0.1
|
||||
__plugin_author__ = "yajiwa"
|
||||
__plugin_settings__ = {
|
||||
"level": 5,
|
||||
"default_status": True,
|
||||
"limit_superuser": False,
|
||||
"cmd": __plugin_cmd__,
|
||||
}
|
||||
wordcloud_cmd = on_command(
|
||||
"wordcloud",
|
||||
aliases={
|
||||
"词云",
|
||||
"今日词云",
|
||||
"昨日词云",
|
||||
"本周词云",
|
||||
"本月词云",
|
||||
"年度词云",
|
||||
"历史词云",
|
||||
"我的今日词云",
|
||||
"我的昨日词云",
|
||||
"我的本周词云",
|
||||
"我的本月词云",
|
||||
"我的年度词云",
|
||||
"我的历史词云",
|
||||
}, block=True, priority=5
|
||||
)
|
||||
Config.add_plugin_config(
|
||||
"word_clouds",
|
||||
"WORD_CLOUDS_TEMPLATE",
|
||||
1,
|
||||
help_="词云模板 参1:图片生成,默认使用真寻图片,可在项目路径resources/image/wordcloud下配置图片,多张则随机 | 参2/其他:黑底图片"
|
||||
)
|
||||
|
||||
|
||||
def parse_datetime(key: str):
|
||||
"""解析数字,并将结果存入 state 中"""
|
||||
|
||||
async def _key_parser(
|
||||
matcher: Matcher,
|
||||
state: T_State,
|
||||
input_: Union[datetime, Message] = Arg(key),
|
||||
):
|
||||
if isinstance(input_, datetime):
|
||||
return
|
||||
|
||||
plaintext = input_.extract_plain_text()
|
||||
try:
|
||||
state[key] = get_datetime_fromisoformat_with_timezone(plaintext)
|
||||
except ValueError:
|
||||
await matcher.reject_arg(key, "请输入正确的日期,不然我没法理解呢!")
|
||||
|
||||
return _key_parser
|
||||
|
||||
|
||||
def get_datetime_now_with_timezone() -> datetime:
|
||||
"""获取当前时间,并包含时区信息"""
|
||||
return datetime.now().astimezone()
|
||||
|
||||
|
||||
def get_datetime_fromisoformat_with_timezone(date_string: str) -> datetime:
|
||||
"""从 iso8601 格式字符串中获取时间,并包含时区信息"""
|
||||
return datetime.fromisoformat(date_string).astimezone()
|
||||
|
||||
|
||||
@wordcloud_cmd.handle()
|
||||
async def handle_first_receive(
|
||||
event: GroupMessageEvent,
|
||||
state: T_State,
|
||||
commands: Tuple[str, ...] = Command(),
|
||||
args: Message = CommandArg(),
|
||||
):
|
||||
command = commands[0]
|
||||
|
||||
if command.startswith("我的"):
|
||||
state["my"] = True
|
||||
command = command[2:]
|
||||
else:
|
||||
state["my"] = False
|
||||
|
||||
if command == "今日词云":
|
||||
dt = get_datetime_now_with_timezone()
|
||||
state["start"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
state["stop"] = dt
|
||||
elif command == "昨日词云":
|
||||
dt = get_datetime_now_with_timezone()
|
||||
state["stop"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
state["start"] = state["stop"] - timedelta(days=1)
|
||||
elif command == "本周词云":
|
||||
dt = get_datetime_now_with_timezone()
|
||||
state["start"] = dt.replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(days=dt.weekday())
|
||||
state["stop"] = dt
|
||||
elif command == "本月词云":
|
||||
dt = get_datetime_now_with_timezone()
|
||||
state["start"] = dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
state["stop"] = dt
|
||||
elif command == "年度词云":
|
||||
dt = get_datetime_now_with_timezone()
|
||||
state["start"] = dt.replace(
|
||||
month=1, day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state["stop"] = dt
|
||||
elif command == "历史词云":
|
||||
plaintext = args.extract_plain_text().strip()
|
||||
match = re.match(r"^(.+?)(?:~(.+))?$", plaintext)
|
||||
if match:
|
||||
start = match.group(1)
|
||||
stop = match.group(2)
|
||||
try:
|
||||
state["start"] = get_datetime_fromisoformat_with_timezone(start)
|
||||
if stop:
|
||||
state["stop"] = get_datetime_fromisoformat_with_timezone(stop)
|
||||
else:
|
||||
# 如果没有指定结束日期,则认为是指查询这一天的词云
|
||||
state["start"] = state["start"].replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state["stop"] = state["start"] + timedelta(days=1)
|
||||
except ValueError:
|
||||
await wordcloud_cmd.finish("请输入正确的日期,不然我没法理解呢!")
|
||||
else:
|
||||
await wordcloud_cmd.finish()
|
||||
|
||||
|
||||
@wordcloud_cmd.got(
|
||||
"start",
|
||||
prompt="请输入你要查询的起始日期(如 2022-01-01)",
|
||||
parameterless=[Depends(parse_datetime("start"))],
|
||||
)
|
||||
@wordcloud_cmd.got(
|
||||
"stop",
|
||||
prompt="请输入你要查询的结束日期(如 2022-02-22)",
|
||||
parameterless=[Depends(parse_datetime("stop"))],
|
||||
)
|
||||
async def handle_message(
|
||||
event: GroupMessageEvent,
|
||||
start: datetime = Arg(),
|
||||
stop: datetime = Arg(),
|
||||
my: bool = Arg(),
|
||||
):
|
||||
# 是否只查询自己的记录
|
||||
if my:
|
||||
user_id = int(event.user_id)
|
||||
else:
|
||||
user_id = None
|
||||
# 将时间转换到 东八 时区
|
||||
messages = await get_list_msg(user_id, int(event.group_id),
|
||||
days=(start.astimezone(pytz.timezone("Asia/Shanghai")),
|
||||
stop.astimezone(pytz.timezone("Asia/Shanghai"))))
|
||||
if messages:
|
||||
image_bytes = await draw_word_cloud(messages, get_driver().config)
|
||||
if image_bytes:
|
||||
await wordcloud_cmd.finish(MessageSegment.image(image_bytes), at_sender=my)
|
||||
else:
|
||||
await wordcloud_cmd.finish("生成词云失败", at_sender=my)
|
||||
else:
|
||||
await wordcloud_cmd.finish("没有获取到词云数据", at_sender=my)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user