refactor code

This commit is contained in:
hibiki
2021-07-30 21:21:51 +08:00
parent 2ad891aa1e
commit cc24822dca
165 changed files with 7815 additions and 8174 deletions
+49 -7
View File
@@ -61,6 +61,7 @@
- [x] p站排行榜
- [x] p站搜图
- [x] 翻译(日英韩)
- [x] pix图库(一个自己的图库,含有增删查改,黑名单等命令)
- [x] 查看当前群欢迎消息
- [x] 查看该群自己的权限
@@ -100,7 +101,7 @@
- [x] 上传/删除/修改商品(需要编写对应的商品功能)
- [x] 节日红包发送
- [x] 修改群权限
#### 超级用户的被动技能
- [x] 邀请入群提醒(别人邀请真寻入群)
- [x] 添加好友提醒(别人添加真寻好友)
@@ -123,6 +124,7 @@
- [x] 群聊时间检测(当群聊最后一人发言时间大于当前36小时后将关闭该群所有通知(即被动技能))
- [x] 群管理员监控,自动为新晋管理员增加权限,为失去群管理员的用户删除权限
- [x] 群权限系统
- [x] 定时更新权限
</details>
## 功能具体指令
@@ -150,7 +152,7 @@
| 原神黄历 | 原神黄历 | 查看今日原神黄历,含有每日10:25的定时任务
| 原神材料 | 今日素材 | 发送可莉特调的截图
| 丘丘语翻译 | 丘丘翻译/丘丘一下/丘丘语翻译 | 示例:丘丘一下 mimi
| 原神资源查询 | 原神资源查询 \[资源名称]/\[资源名称]在哪/哪里有\[资源名称]/原神资源列表 | 示例:嘟嘟莲在哪
| 原神资源查询 | 原神资源查询 \[资源名称] \[路线]?/\[资源名称]在哪/哪里有\[资源名称]/原神资源列表 | 如果资源名称末尾添加‘路线’的话将生成残缺缺缺版的优先路径<br>示例:嘟嘟莲在哪<br>原神资源查询嘟嘟莲路线
| 俄罗斯轮盘 | 装弹\[子弹数] \[金额](默认200)/开枪/结算/我的战绩/胜场排行/败场排行/欧洲人排行/慈善家排行 | 紧张刺激的群内小游戏,使用每日签到的金币作为赌注,具体玩法请发送 真寻帮助 俄罗斯轮盘
| 红包系统 | 塞红包\[金额] \[数量](默认5)/抢/开/戳一戳/退回 | 仿微信明日方舟红包的样式(pil拼图大师!),每个红包金额随机生成,最多会是红包总金额的1/3,退回用于退回一分钟后还未开完的红包
| 金币排行 | 金币排行 | 字面意思
@@ -179,6 +181,10 @@
| 撤回 | 撤回 \[消息位置](默认为最新一条消息) | 按顺序撤回发送的消息,示例:撤回 1
| 滴滴滴- | 滴滴滴- \[文本] | 用于用户联系真寻的超级用户
|功能调用统计可视化 | 功能调用统计(自记录以来的功能调用统计)<br>周功能调用统计 [plugin_name]<br>月功能调用统计 [plugin_name]| 当plugin_name为空时为7天或30内的所有功能统计
| pix | pix/PIX [tags/uid/pid:pid] [num] | 无参数时随机查看pix图库的图片(无r18),num数量默认=1,tags:查看相关tags图片,uid:查找相关画师图片,pid:pid:指定查看pid图片<br>示例:pix原神 3<br>pix23493844<br>pixpid:29429933
| 添加pix关键词/uid/pid | 添加pix关键词/uid/pid *[关键词/uid/pid]| 添加关键词或uid或pid用于下次搜索,关键词搜索相关tag,uid会收录作者下收藏符合标准的作品,pid收录单张作品<br>示例:添加pix关键词 原神<br> 添加pixuid 123441<br>添加pixpid 2748937|
| 查看pix图库 | 查看pix图库 [tags] | 查看已收录的tag相关图片数量<br>示例:查看pix图库 原神 莫娜
|显示pix关键词 | 显示pix关键词 | 查看已收录的所有关键词/UID/PID
### 管理员功能
@@ -186,7 +192,7 @@
| 功能 | 权限等级 | 指令 | 说明
| -------------| --------------| :--------------------------------------:| :------------------------:
| 更新群组成员信息 | 1 | 更新群组成员信息/更新群组成员列表 | 存储群员的基本信息,虽然有自动更新,但备个命令以防万一
| 更新群组成员信息 | 1 | 更新群组成员信息/更新群组成员列表 | 存储群员的基本信息,虽然有自动更新,但备个命令以防万一
| 群功能开关 | 2 | 开启/关闭\[指令名]功能 | 群帮助中左边带有√的功能都可以通过此命令开启或关闭,示例:开启色图
| 查看群被动技能 | 2 | 群通知状态 | 详细请查看被动技能列表
| 被动技能开关 | 2 | 开启/关闭被动技能 | 有时候花里胡哨通知也会很烦人
@@ -211,14 +217,21 @@
| 退群 | 退群 \[群号] | 用于退出某一些群
| 检查系统状态 | 自检 | 略
| 更新好友/群组信息| 更新好友/群组信息 | 包含自动更新,被t出群等等有更好的可视信息
| 重载卡池 | 略 | 重载抽卡的游戏卡池,请查看 [nonebot_plugin_gamedraw](https://github.com/HibiKier/nonebot_plugin_gamedraw)
| 添加商品 | 添加商品 \[名称] \[价格] \[描述] \[折扣](小数)(可选) \[限时时间](分钟)(可选) | 为真寻的商店添加一点点道具<br>示例:添加商品 昏睡红茶 300 一杯上好的奇怪红茶 0.9 60
| 重载卡池 | 略 | 重载抽卡的游戏卡池,请查看 \[nonebot_plugin_gamedraw](https://github.com/HibiKier/nonebot_plugin_gamedraw)
| 添加商品 | 添加商品 \[名称]-\[价格]-\[描述]-\[折扣](小数)(可选)-\[限时时间](分钟)(可选) | 为真寻的商店添加一点点道具<br>示例:添加商品-昏睡红茶-300-一杯上好的奇怪红茶-0.9-60
| 删除商品 | 删除商品 \[名称或序号] | 在真寻的商店中删除一点东西
| 修改商品 | 修改商品 -name \[名称或序号] -price \[价格] -des \[描述] -discount \[折扣] -time \[限时]| 注意空格,不需要的参数可以不加<br>示例:修改商品 -name 1 -price 900 【修改序号为1的商品的价格为900】
| 修改商品 | 修改商品 -name \[名称或序号] -price \[价格] -des \[描述] -discount \[折扣] -time \[限时]| 注意空格,不需要的参数可以不加<br>示例:修改商品 -name 1 -price 900 【修改序号为1的商品的价格为900】
| 节日红包 | 节日红包 \[金额] \[数量] \[祝福语](可选) \[群号](可选)... | 群号支持批量,使用空格隔开,不使用群号则对所有群发送节日红包,节日红包有效时间为24小时,祝福语默认为“恭喜发财 大吉大利”<br>示例:节日红包 10000 15 真寻真可爱 123324423 23423423
| 修改群权限 | 修改群权限 \[group] \[level] | 所以说这功能是对内鬼的无奈,默认群权限为5,默认无法使用 色图/coser/p站排行/搜图(这些功能都要9级权限)
|更新原神今日素材| 更新原神今日素材 | 自动更新原神每日素材失败时可以手动触发
|更新原神资源信息| 更新原神资源信息 | 除了每日自动更新的资源外,额外更新大地图
| 清理数据 | 清理数据 | 清理 temp,rar,r18_rar 文件夹的文件数据
|添加pix关键词/uid/pid | 添加pix关键词/uid/pid [keyword/pid:pid/uid:uid] [-f]? | 与普通功能相同,额外可以通过参数 -f 强制通过检测
|删除pix关键词 | 删除pix关键词 *[keyword/uid/pid:pid] | 删除已收录的keyword/uid/pid
|更新pix关键词 | 更新pix关键词 [keyword/pid:pid/uid:uid] [num]| 更新keyword,uid,pid或指定uid,pid,未指定时,则更新全部,当num未指定时为keyword/uid/pid更新全部<br>示例:更新pix关键词<br>更新pix关键词uid 8<br>更新pix关键词pid:83457477
|删除pix图片 | 删除pix图片 [*pid] [-b]? | [-b]参数为删除的同时加入黑名单(不再更新),虽然是pid,但是_p也可以<br>示例:删除pix图片3458344 8235234_p1 -b
|显示pix关键词 | 显示pix关键词 | 与普通功能相同,额外显示待收录和黑名单
|pix检测更新 | pix检测更新 [update]? | 检测从未更新过的pid或uid,-update参数将在检测后直接更新未更新过的pid或uid<br>示例:pix检测更新 update
</details>
@@ -639,6 +652,35 @@ python bot.py
## 更新
### 2021/7/30
* 重构代码,进行优化,添加注释,删除冗余代码,降低代码耦合
* 添加功能:PIX(一套快捷的pixiv存图命令,自建图库存储url等信息?意在获取不色的图?)
* 添加功能:清理临时图片文件(temp/rar/r18_rar文件夹)
* 添加额外定时任务(5分钟检测一次),解决加入新群时无法及时为管理员提供权限
* 添加配置ALAPI_AI_CHECK,开关AI回复文本检测
* 添加配置IMPORT_DEFAULT_SHOP_GOODS,控制是否导入内置的三个商品(好感度加持卡ⅠⅡⅢ)
* 添加配置ONLY_USE_LOCAL_SETU,仅仅使用本地色图(有的话),提升速度,但无法在线搜索色图和保存链接
* 添加配置WITHDRAW_SETU_TIME,是否需要延迟撤回色图,可配置仅群里,私聊或全部
* 好友请求,入群请求,滴滴滴-,/t,被踢出群提醒,的提示消息更加丰富
* 彻底重写原神资源查找,添加规划路线(路线残缺缺缺缺版,有空补)添加命令‘更新原神资源信息’,强制更新地图等资源
* 优化色图和P站排行/搜图检测用户是否正在触发命令代码
* 当群最后发言大于36小时,也会关闭广播通知
* 功能维护时超级用户依然可以调用(苦了谁都不能苦了自己)
* 修复获取赛马娘UP公告
* 重写 色图/更新色图
* 色图数据存储改为数据库,启动时会更新之前的色图数据(有的话),更新完毕后会删除原数据文件,如果需要保留请提前备份,
* lolicon api改为v2
* 取消r18次数限制
* 单次搜索至多保存100条链接
* 添加定时撤回
* 暂时取消上传/删除色图
*
* 更新建议(不要替换你的data和resources文件夹!)
* 删除configs,plugins,services,utils,models文件夹重新clone
* 删除多余文件夹,resources/img/genshin/seek_god_eye
* 清空resources/img/genshin/genshin_icon文件夹,仅保留box.png和box_alpha.png
### 2021/7/27
* 原神今日素材改为单张截图+拼图,更新文件utils/img_utils.py及plugins/genshin/material_remind/__init__.py
+2 -2
View File
@@ -1,7 +1,7 @@
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
from services.db_context import init, disconnect
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter("cqhttp", CQHTTPBot)
@@ -13,8 +13,8 @@ nonebot.load_plugins("plugins")
nonebot.load_plugins("plugins/shop")
nonebot.load_plugins("plugins/genshin")
nonebot.load_plugins("plugins/alapi")
nonebot.load_plugins("plugins/pix_gallery")
if __name__ == "__main__":
nonebot.run()
+135 -227
View File
@@ -1,6 +1,7 @@
from .utils.util import get_config_data
from typing import List, Union
from services.service_config import TL_M_KEY, SYSTEM_PROXY, ALAPI_M_TOKEN
from typing import List, Optional, Tuple
from services.service_config import TL_M_KEY, SYSTEM_M_PROXY, ALAPI_M_TOKEN
try:
import ujson as json
except ModuleNotFoundError:
@@ -8,27 +9,30 @@ except ModuleNotFoundError:
# 是否使用配置文件
USE_CONFIG_FILE = False
USE_CONFIG_FILE: bool = False
# API KEY(必要)
LOLICON_KEY: str = "" # lolicon(不需要了,可不填)
RSSHUBAPP: str = "https://rsshub.app/" # rsshub
ALAPI_TOKEN: str = "" # ALAPI
RSSHUBAPP: str = "https://rsshub.app" # rsshub
ALAPI_TOKEN: str = "" # ALAPI https://admin.alapi.cn/user/login
HIBIAPI: str = "https://api.obfs.dev"
# 图灵
TL_KEY: List[str] = []
# 数据库(必要)
# 如果填写了bind就不需要再填写后面的字段了#)
# 示例:"bind": "postgresql://user:password@127.0.0.1:5432/database"
bind: str = '' # 数据库url
sql_name: str = 'postgresql'
user: str = '' # 数据用户名
password: str = '' # 数据库密码
address: str = '' # 数据库地址
port: str = '' # 数据库端口
database: str = '' # 数据库名称
bind: str = "" # 数据库连接链接
sql_name: str = "postgresql"
user: str = "" # 数据用户名
password: str = "" # 数据库密码
address: str = "" # 数据库地址
port: str = "" # 数据库端口
database: str = "" # 数据库名称
# 代理
SYSTEM_PROXY: Optional[str] = None # 全局代理
BUFF_PROXY: Optional[str] = None # Buff代理
# 公开图库列表
IMAGE_DIR_LIST: List[str] = ["色图", "美图", "萝莉", "壁纸"]
@@ -38,252 +42,161 @@ BAN_RESULT: str = "才不会给你发消息."
# 插件配置
MAXINFO_REIMU: int = 7 # 上车(reimu)功能查找目的地的最大数
COUNT_PER_DAY_REIMU: int = 5 # 每日上车(reimu)次数限制
MAXINFO_BT: int = 10 # bt功能单次查找最大数
MAXINFO_PRIVATE_ANIME: int = 20 # 私聊搜索动漫返回的最大数量
MAXINFO_GROUP_ANIME: int = 5 # 群搜索动漫返回的最大数量
MAX_FIND_IMG_COUNT: int = 3 # 识图最大返回数
MAX_SETU_R_COUNT: int = 5 # 每日色图r次数限制
MAXINFO_REIMU: int = 7 # 上车(reimu)功能查找目的地的最大数
COUNT_PER_DAY_REIMU: int = 5 # 每日上车(reimu)次数限制
MAXINFO_BT: int = 10 # bt功能单次查找最大数
MAXINFO_PRIVATE_ANIME: int = 20 # 私聊搜索动漫返回的最大数量
MAXINFO_GROUP_ANIME: int = 5 # 群搜索动漫返回的最大数量
MAX_FIND_IMG_COUNT: int = 3 # 识图最大返回数
# 参1:延迟撤回色图时间(秒),0 为关闭 | 参2:监控聊天类型,0(私聊) 1(群聊) 2(群聊+私聊)
WITHDRAW_SETU_TIME: Tuple[int, int] = (0, 1)
# 各种卡池的开关
PRTS_FLAG = True # 明日方舟
GENSHIN_FLAG = True # 原神
PRETTY_FLAG = True # 赛马娘
GUARDIAN_FLAG = True # 坎公骑冠剑
PCR_FLAG = True # 公主连结
AZUR_FLAG = True # 碧蓝航线
FGO_FLAG = True # 命运-冠位指定(FGO)
ONMYOJI_FLAG = True # 阴阳师
PRTS_FLAG = True # 明日方舟
GENSHIN_FLAG = True # 原神
PRETTY_FLAG = True # 赛马娘
GUARDIAN_FLAG = True # 坎公骑冠剑
PCR_FLAG = True # 公主连结
AZUR_FLAG = True # 碧蓝航线
FGO_FLAG = True # 命运-冠位指定(FGO)
ONMYOJI_FLAG = True # 阴阳师
PCR_TAI = True # pcr是否开启台服卡池
SEMAPHORE = 5 # 限制碧蓝航线和FGO并发数
PCR_TAI = True # pcr是否开启台服卡池
SEMAPHORE = 5 # 限制碧蓝航线和FGO并发数
ADMIN_DEFAULT_AUTH: int = 5 # 默认群管理员权限
MAX_SIGN_GOLD: int = 200 # 签到好感度加成额外获得的最大金币数
MAX_SIGN_GOLD: int = 200 # 签到好感度加成额外获得的最大金币数
INITIAL_SETU_PROBABILITY: float = 0.7 # 色图概率
FUDU_PROBABILITY: float = 0.7 # 复读概率
INITIAL_OPEN_CASE_COUNT: int = 20 # 初始开箱次数
MUTE_DEFAULT_COUNT: int = 10 # 刷屏禁言默认检测次数
MUTE_DEFAULT_TIME: int = 7 # 刷屏检测默认规定时间
INITIAL_SETU_PROBABILITY: float = 0.7 # 色图概率
FUDU_PROBABILITY: float = 0.7 # 复读概率
INITIAL_OPEN_CASE_COUNT: int = 20 # 初始开箱次数
MUTE_DEFAULT_COUNT: int = 10 # 刷屏禁言默认检测次数
MUTE_DEFAULT_TIME: int = 7 # 刷屏检测默认规定时间
MUTE_DEFAULT_DURATION: int = 10 # 刷屏检测默禁言时长(分钟)
# 注:即在 MALICIOUS_CHECK_TIME 时间内触发相同命令 MALICIOUS_BAN_COUNT 将被 ban MALICIOUS_BAN_TIME 分钟
MALICIOUS_BAN_TIME: int = 30 # 恶意命令触发检测触发后ban的时长(分钟)
MALICIOUS_BAN_COUNT: int = 8 # 恶意命令触发检测最大触发次数
MALICIOUS_CHECK_TIME: int = 5 # 恶意命令触发检测规定时间内(秒)
# 注:即在 MALICIOUS_CHECK_TIME 时间内触发相同命令 MALICIOUS_BAN_COUNT 将被ban MALICIOUS_BAN_TIME 分钟
MALICIOUS_BAN_TIME: int = 30 # 恶意命令触发检测触发后ban的时长(分钟)
MALICIOUS_BAN_COUNT: int = 8 # 恶意命令触发检测最大触发次数
MALICIOUS_CHECK_TIME: int = 5 # 恶意命令触发检测规定时间内(秒)
# LEVEL
DELETE_IMG_LEVEL: int = 7 # 删除图片权限
MOVE_IMG_LEVEL: int = 7 # 移动图片权限
UPLOAD_LEVEL: int = 6 # 上传图片权限
BAN_LEVEL: int = 5 # BAN权限
OC_LEVEL: int = 2 # 开关群功能权限
MUTE_LEVEL: int = 5 # 更改禁言设置权限
MEMBER_ACTIVITY_LEVEL = 5 # 群员活跃检测设置权限
DELETE_IMG_LEVEL: int = 7 # 删除图片权限
MOVE_IMG_LEVEL: int = 7 # 移动图片权限
UPLOAD_LEVEL: int = 6 # 上传图片权限
BAN_LEVEL: int = 5 # BAN权限
OC_LEVEL: int = 2 # 开关群功能权限
MUTE_LEVEL: int = 5 # 更改禁言设置权限
MEMBER_ACTIVITY_LEVEL = 5 # 群员活跃检测设置权限
# 是否开启HIBIAPI搜图功能(该功能会搜索群友提交的xp)
HIBIAPI_FLAG: bool = True
# HIBIAPI搜图图片的最低收藏
HIBIAPI_BOOKMARKS: int = 5000
# 需要为哪些群更新最新版gocq吗?(上传最新版gocq)
# 示例:[434995955, 239483248]
UPDATE_GOCQ_GROUP: List[int] = []
# 代理
system_proxy: Union[str, None] = None
buff_proxy: Union[str, None] = None
# 是否存储色图
DOWNLOAD_SETU: bool = True
# 仅仅使用本地色图
ONLY_USE_LOCAL_SETU: bool = False
# 是否自动同意好友添加
AUTO_ADD_FRIEND: bool = True
# 当含有ALAPI_TOKEN时是否检测文本合规,开启检测会减慢回复速度
ALAPI_AI_CHECK: bool = True
# 导入商店自带的三个商品
IMPORT_DEFAULT_SHOP_GOODS: bool = True
# 群管理员功能 与 对应权限
admin_plugins_auth = {
'admin_bot_manage': OC_LEVEL,
'ban': BAN_LEVEL,
'delete_img': DELETE_IMG_LEVEL,
'move_img': MOVE_IMG_LEVEL,
'upload_img': UPLOAD_LEVEL,
'admin_help': 1,
'mute': MUTE_LEVEL,
'member_activity_handle': MEMBER_ACTIVITY_LEVEL
"admin_bot_manage": OC_LEVEL,
"ban": BAN_LEVEL,
"delete_img": DELETE_IMG_LEVEL,
"move_img": MOVE_IMG_LEVEL,
"upload_img": UPLOAD_LEVEL,
"admin_help": 1,
"mute": MUTE_LEVEL,
"member_activity_handle": MEMBER_ACTIVITY_LEVEL,
}
# 模块与对应命令和对应群权限
# 用于生成帮助图片 和 开关功能 以及 群权限
# 用于生成帮助图片 和 开关功能
plugins2info_dict = {
'sign_in': {
'level': 5,
'cmd': ['签到']
"sign_in": {"level": 5, "cmd": ["签到"]},
"send_img": {"level": 5, "cmd": ["发送图片", "发图", "萝莉", "美图", "壁纸"]},
"send_setu": {"level": 9, "cmd": ["色图", "涩图", "瑟图", "查色图"]},
"white2black": {"level": 5, "cmd": ["黑白图", "黑白草图"]},
"coser": {"level": 9, "cmd": ["coser", "cos"]},
"quotations": {"level": 5, "cmd": ["语录"]},
"jitang": {"level": 5, "cmd": ["鸡汤"]},
"send_dinggong_voice": {"level": 5, "cmd": ["骂我", "骂老子", "骂劳资"]},
"open_cases": {"level": 5, "cmd": ["开箱", "我的开箱", "群开箱统计", "我的金色"]},
"luxun": {"level": 5, "cmd": ["鲁迅说", "鲁迅说过"]},
"fake_msg": {"level": 5, "cmd": ["假消息"]},
"buy": {"level": 5, "cmd": ["购买", "购买道具"]},
"my_gold": {"level": 5, "cmd": ["我的金币"]},
"my_props": {"level": 5, "cmd": ["我的道具"]},
"shop_handle": {"level": 5, "cmd": ["商店"]},
"update_pic": {"level": 5, "cmd": ["图片", "操作图片", "修改图片"]},
"search_buff_skin_price": {"level": 5, "cmd": ["查询皮肤"]},
"weather": {"level": 5, "cmd": ["天气", "查询天气", "天气查询"]},
"yiqing": {"level": 5, "cmd": ["疫情", "疫情查询", "查询疫情"]},
"what_anime": {"level": 5, "cmd": ["识番"]},
"search_anime": {"level": 5, "cmd": ["搜番"]},
"songpicker2": {"level": 5, "cmd": ["点歌"]},
"epic": {"level": 5, "cmd": ["epic"]},
"pixiv": {"level": 9, "cmd": ["pixiv", "p站排行", "搜图"]},
"poke": {"level": 5, "cmd": ["戳一戳", "拍一拍"]},
"draw_card": {
"level": 5,
"cmd": [
"抽卡",
"游戏抽卡",
"原神抽卡",
"方舟抽卡",
"坎公骑冠剑抽卡",
"pcr抽卡",
"fgo抽卡",
"碧蓝抽卡",
"碧蓝航线抽卡",
"阴阳师抽卡",
],
},
'send_img': {
'level': 5,
'cmd': ['发送图片', '发图', '萝莉', '美图', '壁纸']
"ai": {"level": 5, "cmd": ["ai", "Ai", "AI", "aI"]},
"one_friend": {"level": 5, "cmd": ["我有一个朋友", "我有一个朋友想问问"]},
"translate": {"level": 5, "cmd": ["翻译", "英翻", "翻英", "日翻", "翻日", "韩翻", "翻韩"]},
"nonebot_plugin_picsearcher": {"level": 5, "cmd": ["识图"]},
"almanac": {"level": 5, "cmd": ["原神黄历", "黄历"]},
"material_remind": {"level": 5, "cmd": ["今日素材", "天赋材料"]},
"qiu_qiu_translation": {"level": 5, "cmd": ["丘丘翻译", "丘丘一下", "丘丘语翻译"]},
"query_resource_points": {"level": 5, "cmd": ["原神资源查询", "原神资源列表"]},
"russian": {"level": 5, "cmd": ["俄罗斯轮盘", "俄罗斯转盘", "装弹"]},
"gold_redbag": {"level": 5, "cmd": ["塞红包", "红包", "抢红包"]},
"poetry": {"level": 5, "cmd": ["念诗", "来首诗", "念首诗"]},
"comments_163": {"level": 5, "cmd": ["到点了", "12点了", "网易云热评", "网易云评论"]},
"cover": {"level": 5, "cmd": ["b封面", "B封面"]},
"pid_search": {"level": 9, "cmd": ["p搜", "P搜"]},
"pix": {
"level": 5,
"cmd": ["pix", "PIX", "pIX", "Pix", "PIx"],
},
'send_setu': {
'level': 9,
'cmd': ['色图', '涩图', '瑟图', '查色图']
},
'white2black': {
'level': 5,
'cmd': ['黑白图', '黑白草图']
},
'coser': {
'level': 9,
'cmd': ['coser', 'cos']
},
'quotations': {
'level': 5,
'cmd': ['语录']
},
'jitang': {
'level': 5,
'cmd': ['鸡汤']
},
'send_dinggong_voice': {
'level': 5,
'cmd': ['骂我', '骂老子', '骂劳资']
},
'open_cases': {
'level': 5,
'cmd': ['开箱', '我的开箱', '群开箱统计', '我的金色']
},
'luxun': {
'level': 5,
'cmd': ['鲁迅说', '鲁迅说过']
},
'fake_msg': {
'level': 5,
'cmd': ['假消息']
},
'buy': {
'level': 5,
'cmd': ['购买', '购买道具']
},
'my_gold': {
'level': 5,
'cmd': ['我的金币']
},
'my_props': {
'level': 5,
'cmd': ['我的道具']
},
'shop_handle': {
'level': 5,
'cmd': ['商店']
},
'update_pic': {
'level': 5,
'cmd': ['图片', '操作图片', '修改图片']
},
'search_buff_skin_price': {
'level': 5,
'cmd': ['查询皮肤']
},
'weather': {
'level': 5,
'cmd': ['天气', '查询天气', '天气查询']
},
'yiqing': {
'level': 5,
'cmd': ['疫情', '疫情查询', '查询疫情']
},
'what_anime': {
'level': 5,
'cmd': ['识番']
},
'search_anime': {
'level': 5,
'cmd': ['搜番']
},
'songpicker2': {
'level': 5,
'cmd': ['点歌']
},
'epic': {
'level': 5,
'cmd': ['epic']
},
'pixiv': {
'level': 9,
'cmd': ['pixiv', 'p站排行', '搜图']
},
'poke': {
'level': 5,
'cmd': ['戳一戳', '拍一拍']
},
'draw_card': {
'level': 5,
'cmd': ['抽卡', '游戏抽卡', '原神抽卡', '方舟抽卡', '坎公骑冠剑抽卡', 'pcr抽卡', 'fgo抽卡', '碧蓝抽卡', '碧蓝航线抽卡', '阴阳师抽卡']
},
'ai': {
'level': 5,
'cmd': ['ai', 'Ai', 'AI', 'aI']
},
'one_friend': {
'level': 5,
'cmd': ['我有一个朋友', '我有一个朋友想问问']
},
'translate': {
'level': 5,
'cmd': ['翻译', '英翻', '翻英', '日翻', '翻日', '韩翻', '翻韩']
},
'nonebot_plugin_picsearcher': {
'level': 5,
'cmd': ['识图']
},
'almanac': {
'level': 5,
'cmd': ['原神黄历', '黄历']
},
'material_remind': {
'level': 5,
'cmd': ['今日素材', '天赋材料']
},
'qiu_qiu_translation': {
'level': 5,
'cmd': ['丘丘翻译', '丘丘一下', '丘丘语翻译']
},
'query_resource_points': {
'level': 5,
'cmd': ['原神资源查询', '原神资源列表']
},
'russian': {
'level': 5,
'cmd': ['俄罗斯轮盘', '俄罗斯转盘', '装弹']
},
'gold_redbag': {
'level': 5,
'cmd': ['塞红包', '红包', '抢红包']
},
'poetry': {
'level': 5,
'cmd': ['念诗', '来首诗', '念首诗']
},
'comments_163': {
'level': 5,
'cmd': ['到点了', '12点了', '网易云热评', '网易云评论']
},
'cover': {
'level': 5,
'cmd': ['b封面', 'B封面']
},
'pid_search': {
'level': 9,
'cmd': ['p搜', 'P搜']
}
}
if TL_M_KEY:
TL_KEY = TL_M_KEY
if SYSTEM_PROXY:
system_proxy = SYSTEM_PROXY
if SYSTEM_M_PROXY:
SYSTEM_PROXY = SYSTEM_M_PROXY
if ALAPI_M_TOKEN:
ALAPI_TOKEN = ALAPI_M_TOKEN
HIBIAPI = HIBIAPI[:-1] if HIBIAPI[-1] == "/" else HIBIAPI
RSSHUBAPP = RSSHUBAPP[:-1] if RSSHUBAPP[-1] == "/" else RSSHUBAPP
# 配置文件应用
if USE_CONFIG_FILE:
config = get_config_data()
@@ -291,14 +204,9 @@ if USE_CONFIG_FILE:
for key in config.keys():
if isinstance(config[key], str):
config[key] = config[key].strip()
if key.find('proxy') != -1:
if key.find("proxy") != -1:
if not config[key]:
config[key] = None
# if not configs[key] and key.find("PATH") == -1:
# configs[key] = None
globals().update(config)
+90 -46
View File
@@ -1,10 +1,9 @@
from services.db_context import db
from typing import Optional, List
class BagUser(db.Model):
__tablename__ = 'bag_users'
__tablename__ = "bag_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
belonging_group = db.Column(db.BigInteger(), nullable=False)
@@ -15,25 +14,41 @@ class BagUser(db.Model):
get_today_gold = db.Column(db.Integer(), default=0)
spend_today_gold = db.Column(db.Integer(), default=0)
_idx1 = db.Index('bag_group_users_idx1', 'user_qq', 'belonging_group', unique=True)
_idx1 = db.Index("bag_group_users_idx1", "user_qq", "belonging_group", unique=True)
@classmethod
async def get_my_total_gold(cls, user_qq: int, belonging_group: int) -> str:
"""
说明:
获取金币概况
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
user = await query.gino.first()
if not user:
user = await cls.create(
user_qq=user_qq,
belonging_group=belonging_group,
)
return f'当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}' \
f'\n今日收益:{user.get_today_gold - user.spend_today_gold}' \
f'\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}'
user_qq=user_qq,
belonging_group=belonging_group,
)
return (
f"当前金币:{user.gold}\n今日获取金币:{user.get_today_gold}\n今日花费金币:{user.spend_today_gold}"
f"\n今日收益:{user.get_today_gold - user.spend_today_gold}"
f"\n总赚取金币:{user.get_total_gold}\n总花费金币:{user.spend_total_gold}"
)
@classmethod
async def get_gold(cls, user_qq: int, belonging_group: int) -> int:
"""
说明:
获取当前金币
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -42,13 +57,20 @@ class BagUser(db.Model):
return user.gold
else:
await cls.create(
user_qq=user_qq,
belonging_group=belonging_group,
)
user_qq=user_qq,
belonging_group=belonging_group,
)
return 100
@classmethod
async def get_props(cls, user_qq: int, belonging_group: int) -> str:
"""
说明:
获取当前道具
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -57,13 +79,21 @@ class BagUser(db.Model):
return user.props
else:
await cls.create(
user_qq=user_qq,
belonging_group=belonging_group,
)
return ''
user_qq=user_qq,
belonging_group=belonging_group,
)
return ""
@classmethod
async def add_gold(cls, user_qq: int, belonging_group: int, num: int) -> bool:
"""
说明:
增加金币
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
:param num: 金币数量
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -74,7 +104,7 @@ class BagUser(db.Model):
await user.update(
gold=user.gold + num,
get_total_gold=user.get_total_gold + num,
get_today_gold=user.get_today_gold + num
get_today_gold=user.get_today_gold + num,
).apply()
else:
await cls.create(
@@ -90,6 +120,14 @@ class BagUser(db.Model):
@classmethod
async def spend_gold(cls, user_qq: int, belonging_group: int, num: int) -> bool:
"""
说明:
花费金币
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
:param num: 金币数量
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -100,7 +138,7 @@ class BagUser(db.Model):
await user.update(
gold=user.gold - num,
spend_total_gold=user.spend_total_gold + num,
spend_today_gold=user.spend_today_gold + num
spend_today_gold=user.spend_today_gold + num,
).apply()
else:
await cls.create(
@@ -108,7 +146,7 @@ class BagUser(db.Model):
belonging_group=belonging_group,
gold=100 - num,
spend_total_gold=num,
spend_today_gold=num
spend_today_gold=num,
)
return True
except Exception:
@@ -116,6 +154,14 @@ class BagUser(db.Model):
@classmethod
async def add_props(cls, user_qq: int, belonging_group: int, name: str) -> bool:
"""
说明:
增加道具
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
:param name: 道具名称
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -123,14 +169,10 @@ class BagUser(db.Model):
user = await query.gino.first()
try:
if user:
await user.update(
props=user.props + f'{name},'
).apply()
await user.update(props=user.props + f"{name},").apply()
else:
await cls.create(
user_qq=user_qq,
belonging_group=belonging_group,
props=f'{name},'
user_qq=user_qq, belonging_group=belonging_group, props=f"{name},"
)
return True
except Exception:
@@ -138,6 +180,14 @@ class BagUser(db.Model):
@classmethod
async def del_props(cls, user_qq: int, belonging_group: int, name: str) -> bool:
"""
说明:
使用道具
参数:
:param user_qq: qq号
:param belonging_group: 所在群号
:param name: 道具名称
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -145,21 +195,19 @@ class BagUser(db.Model):
user = await query.gino.first()
try:
if user:
rst = ''
rst = ""
props = user.props
if props.find(name) != -1:
props = props.split(',')
props = props.split(",")
try:
index = props.index(name)
except ValueError:
return False
props = props[:index] + props[index + 1:]
props = props[:index] + props[index + 1 :]
for p in props:
if p != '':
rst += p + ','
await user.update(
props=rst
).apply()
if p != "":
rst += p + ","
await user.update(props=rst).apply()
return True
else:
return False
@@ -169,19 +217,15 @@ class BagUser(db.Model):
return False
@classmethod
async def get_user_all(cls, group_id: int = None) -> list:
async def get_all_users(cls, group_id: Optional[int] = None) -> List["BagUser"]:
"""
说明:
获取所有用户数据
参数:
:param group_id: 群号
"""
if not group_id:
query = await cls.query.gino.all()
else:
query = await cls.query.where(
(cls.belonging_group == group_id)
).gino.all()
query = await cls.query.where((cls.belonging_group == group_id)).gino.all()
return query
+48 -25
View File
@@ -3,20 +3,25 @@ import time
class BanUser(db.Model):
__tablename__ = 'ban_users'
__tablename__ = "ban_users"
user_qq = db.Column(db.BigInteger(), nullable=False, primary_key=True)
ban_level = db.Column(db.Integer(), nullable=False)
ban_time = db.Column(db.BigInteger())
duration = db.Column(db.BigInteger())
_idx1 = db.Index('ban_group_users_idx1', 'user_qq', unique=True)
_idx1 = db.Index("ban_group_users_idx1", "user_qq", unique=True)
@classmethod
async def check_ban_level(cls, user_qq: int, level: int) -> 'bool':
user = await cls.query.where(
(cls.user_qq == user_qq)
).gino.first()
async def check_ban_level(cls, user_qq: int, level: int) -> bool:
"""
说明:
检测ban掉目标的用户与unban用户的权限等级大小
参数:
:param user_qq: unban用户的qq号
:param level: ban掉目标用户的权限等级
"""
user = await cls.query.where((cls.user_qq == user_qq)).gino.first()
if not user:
return False
if user.ban_level > level:
@@ -24,21 +29,31 @@ class BanUser(db.Model):
return False
@classmethod
async def check_ban_time(cls, user_qq: int) -> 'str':
query = cls.query.where(
(cls.user_qq == user_qq)
)
async def check_ban_time(cls, user_qq: int) -> str:
"""
说明:
检测用户被ban时长
参数:
:param user_qq: qq号
"""
query = cls.query.where((cls.user_qq == user_qq))
user = await query.gino.first()
if not user:
return ''
return ""
if time.time() - (user.ban_time + user.duration) > 0 and user.duration != -1:
return ''
return ""
if user.duration == -1:
return '∞'
return "∞"
return time.time() - user.ban_time - user.duration
@classmethod
async def isban(cls, user_qq: int) -> 'bool':
async def is_ban(cls, user_qq: int) -> bool:
"""
说明:
判断用户是否被ban
参数:
:param user_qq: qq号
"""
if await cls.check_ban_time(user_qq):
return True
else:
@@ -46,10 +61,16 @@ class BanUser(db.Model):
return False
@classmethod
async def ban(cls, user_qq: int, ban_level: int, duration: int) -> 'bool':
query = cls.query.where(
(cls.user_qq == user_qq)
)
async def ban(cls, user_qq: int, ban_level: int, duration: int) -> bool:
"""
说明:
ban掉目标用户
参数:
:param user_qq: 目标用户qq号
:param ban_level: 使用ban命令用户的权限
:param duration: ban时长
"""
query = cls.query.where((cls.user_qq == user_qq))
query = query.with_for_update()
user = await query.gino.first()
if not await cls.check_ban_time(user_qq):
@@ -67,16 +88,18 @@ class BanUser(db.Model):
return False
@classmethod
async def unban(cls, user_qq: int) -> 'bool':
query = cls.query.where(
(cls.user_qq == user_qq)
)
async def unban(cls, user_qq: int) -> bool:
"""
说明:
unban用户
参数:
:param user_qq: qq号
"""
query = cls.query.where((cls.user_qq == user_qq))
query = query.with_for_update()
user = await query.gino.first()
if user is None:
return False
else:
await cls.delete.where(
(cls.user_qq == user_qq)
).gino.status()
await cls.delete.where((cls.user_qq == user_qq)).gino.status()
return True
+1 -1
View File
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime
from services.db_context import db
+41 -56
View File
@@ -1,78 +1,63 @@
from services.db_context import db
class UserCount(db.Model):
__tablename__ = 'count_users'
__tablename__ = "count_users"
user_qq = db.Column(db.BigInteger(), nullable=False, primary_key=True)
reimu_count = db.Column(db.Integer(), nullable=False, default=0)
setu_r18_count = db.Column(db.Integer(), nullable=False, default=0)
_idx1 = db.Index('sign_reimu_users_idx1', 'user_qq', unique=True)
@classmethod
async def add_user(cls, user_qq: int):
query = cls.query.where(
(cls.user_qq == user_qq)
)
query = query.with_for_update()
if not await query.gino.first():
await cls.create(
user_qq=user_qq,
)
_idx1 = db.Index("sign_reimu_users_idx1", "user_qq", unique=True)
@classmethod
async def add_count(cls, user_qq: int, name: str, count: int = 1):
query = cls.query.where(
(cls.user_qq == user_qq)
)
"""
说明:
用户添加次数
参数:
:param user_qq: qq号
:param name: 目标名称
:param count: 增加次数
"""
query = cls.query.where((cls.user_qq == user_qq))
query = query.with_for_update()
user = await query.gino.first()
if user:
if name == 'reimu':
await user.update(
reimu_count=cls.reimu_count + count
).apply()
if name == 'setu_r18':
await user.update(
setu_r18_count=cls.setu_r18_count + count
).apply()
else:
await cls.create(
user_qq=user_qq
)
user = user if user else await cls.create(user_qq=user_qq)
if name == "reimu":
await user.update(reimu_count=cls.reimu_count + count).apply()
if name == "setu_r18":
await user.update(setu_r18_count=cls.setu_r18_count + count).apply()
@classmethod
async def check_count(cls, user_qq: int, name: str, max_count: int) -> bool:
query = cls.query.where(
(cls.user_qq == user_qq)
)
"""
说明:
检测次数是否到达最大值
参数:
:param user_qq: qq号
:param name: 目标名称
:param max_count: 最大值
"""
query = cls.query.where((cls.user_qq == user_qq))
user = await query.gino.first()
if user:
if name == 'reimu':
if user.reimu_count == max_count:
return True
else:
return False
if name == 'setu_r18':
if user.setu_r18_count == max_count:
return True
else:
return False
else:
await cls.add_user(user_qq)
return False
user = user if user else await cls.create(user_qq=user_qq)
if name == "reimu":
if user.reimu_count == max_count:
return True
else:
return False
if name == "setu_r18":
if user.setu_r18_count == max_count:
return True
else:
return False
@classmethod
async def reset_count(cls):
"""
说明:
重置每日次数
"""
for user in await cls.query.gino.all():
await user.update(
reimu_count=0,
setu_r18_count=0
).apply()
await user.update(reimu_count=0, setu_r18_count=0).apply()
+45 -23
View File
@@ -2,32 +2,41 @@ from services.db_context import db
class FriendUser(db.Model):
__tablename__ = 'friend_users'
__tablename__ = "friend_users"
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.BigInteger(), nullable=False)
user_name = db.Column(db.Unicode(), nullable=False, default="")
nickname = db.Column(db.Unicode())
_idx1 = db.Index('friend_users_idx1', 'user_id', unique=True)
_idx1 = db.Index("friend_users_idx1", "user_id", unique=True)
@classmethod
async def get_user_name(cls, user_id: int) -> str:
query = cls.query.where(
cls.user_id == user_id
)
"""
说明:
获取好友用户名称
参数:
:param user_id: qq号
"""
query = cls.query.where(cls.user_id == user_id)
user = await query.gino.first()
if user:
return user.user_name
else:
return ''
return ""
@classmethod
async def add_friend_info(cls, user_id: int, user_name: str) -> 'bool':
async def add_friend_info(cls, user_id: int, user_name: str) -> bool:
"""
说明:
添加好友信息
参数:
:param user_id: qq号
:param user_name: 用户名称
"""
try:
query = cls.query.where(
cls.user_id == user_id
)
query = cls.query.where(cls.user_id == user_id)
user = await query.with_for_update().gino.first()
if not user:
await cls.create(
@@ -43,11 +52,15 @@ class FriendUser(db.Model):
return False
@classmethod
async def delete_friend_info(cls, user_id: int) -> 'bool':
async def delete_friend_info(cls, user_id: int) -> bool:
"""
说明:
删除好友信息
参数:
:param user_id: qq号
"""
try:
query = cls.query.where(
cls.user_id == user_id
)
query = cls.query.where(cls.user_id == user_id)
user = await query.with_for_update().gino.first()
if user:
await user.delete()
@@ -56,22 +69,31 @@ class FriendUser(db.Model):
return False
@classmethod
async def get_friend_nickname(cls, user_id: int) -> 'str':
query = cls.query.where(
cls.user_id == user_id
)
async def get_friend_nickname(cls, user_id: int) -> str:
"""
说明:
获取用户昵称
参数:
:param user_id: qq号
"""
query = cls.query.where(cls.user_id == user_id)
user = await query.gino.first()
if user:
if user.nickname:
return user.nickname
return ''
return ""
@classmethod
async def set_friend_nickname(cls, user_id: int, nickname: str) -> 'bool':
async def set_friend_nickname(cls, user_id: int, nickname: str) -> bool:
"""
说明:
设置用户昵称
参数:
:param user_id: qq号
:param nickname: 昵称
"""
try:
query = cls.query.where(
cls.user_id == user_id
)
query = cls.query.where(cls.user_id == user_id)
user = await query.with_for_update().gino.first()
if not user:
await cls.create(
+89 -58
View File
@@ -1,83 +1,124 @@
from services.db_context import db
from typing import Optional, List
class GoodsInfo(db.Model):
__tablename__ = 'goods_info'
__tablename__ = "goods_info"
id = db.Column(db.Integer(), primary_key=True)
goods_name = db.Column(db.TEXT(), nullable=False) # 名称
goods_price = db.Column(db.Integer(), nullable=False) # 价格
goods_description = db.Column(db.TEXT(), nullable=False) # 商品描述
goods_name = db.Column(db.TEXT(), nullable=False) # 名称
goods_price = db.Column(db.Integer(), nullable=False) # 价格
goods_description = db.Column(db.TEXT(), nullable=False) # 商品描述
goods_discount = db.Column(db.Numeric(scale=3, asdecimal=False), default=1) # 打折
goods_limit_time = db.Column(db.BigInteger(), default=0) # 限时
goods_limit_time = db.Column(db.BigInteger(), default=0) # 限时
_idx1 = db.Index('goods_group_users_idx1', 'goods_name', unique=True)
_idx1 = db.Index("goods_group_users_idx1", "goods_name", unique=True)
@classmethod
async def add_goods(cls, goods_name: str, goods_price: int,
goods_description: str, goods_discount: float = 1, goods_limit_time: int = 0) -> bool:
# try:
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time
async def add_goods(
cls,
goods_name: str,
goods_price: int,
goods_description: str,
goods_discount: float = 1,
goods_limit_time: int = 0,
) -> bool:
"""
说明:
添加商品
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时
"""
try:
await cls.create(
goods_name=goods_name,
goods_price=goods_price,
goods_description=goods_description,
goods_discount=goods_discount,
goods_limit_time=goods_limit_time,
)
return True
except Exception:
return False
@classmethod
async def delete_goods(cls, goods_name: str) -> bool:
"""
说明:
删除商品
参数:
:param goods_name: 商品名称
"""
query = (
await cls.query.where(cls.goods_name == goods_name)
.with_for_update()
.gino.first()
)
return True
# except Exception:
# return False
@classmethod
async def del_goods(cls, goods_name: str) -> bool:
query = await cls.query.where(
cls.goods_name == goods_name
).with_for_update().gino.first()
if not query:
return False
await query.delete()
return True
@classmethod
async def update_goods(cls, goods_name: str, goods_price: int = None,
goods_description: str = None, goods_discount: float = None,
goods_limit_time: int = None) -> bool:
async def update_goods(
cls,
goods_name: str,
goods_price: Optional[int] = None,
goods_description: Optional[str] = None,
goods_discount: Optional[float] = None,
goods_limit_time: Optional[int] = None,
) -> bool:
"""
说明:
更新商品信息
参数:
:param goods_name: 商品名称
:param goods_price: 商品价格
:param goods_description: 商品简介
:param goods_discount: 商品折扣
:param goods_limit_time: 商品限时时间
"""
try:
query = await cls.query.where(
cls.goods_name == goods_name
).with_for_update().gino.first()
query = (
await cls.query.where(cls.goods_name == goods_name)
.with_for_update()
.gino.first()
)
if not query:
return False
if goods_price:
await query.update(
goods_price=goods_price
).apply()
await query.update(goods_price=goods_price).apply()
if goods_description:
await query.update(
goods_description=goods_description
).apply()
await query.update(goods_description=goods_description).apply()
if goods_discount:
await query.update(
goods_discount=goods_discount
).apply()
await query.update(goods_discount=goods_discount).apply()
if goods_limit_time:
await query.update(
goods_limit_time=goods_limit_time
).apply()
await query.update(goods_limit_time=goods_limit_time).apply()
return True
except Exception:
return False
@classmethod
async def get_goods_info(cls, goods_name: str) -> 'GoodsInfo':
query = await cls.query.where(
cls.goods_name == goods_name
).gino.first()
async def get_goods_info(cls, goods_name: str) -> "GoodsInfo":
"""
说明:
获取商品对象
参数:
:param goods_name: 商品名称
"""
query = await cls.query.where(cls.goods_name == goods_name).gino.first()
return query
@classmethod
async def get_all_goods(cls) -> list:
async def get_all_goods(cls) -> List["GoodsInfo"]:
"""
说明:
获得全部有序商品对象
"""
query = await cls.query.gino.all()
id_lst = [x.id for x in query]
goods_lst = []
@@ -86,13 +127,3 @@ class GoodsInfo(db.Model):
goods_lst.append([x for x in query if x.id == min_id][0])
id_lst.remove(min_id)
return goods_lst
+43 -15
View File
@@ -1,30 +1,47 @@
from services.db_context import db
from typing import List
class GroupInfo(db.Model):
__tablename__ = 'group_info'
__tablename__ = "group_info"
group_id = db.Column(db.BigInteger(), nullable=False, primary_key=True)
group_name = db.Column(db.Unicode(), nullable=False, default="")
max_member_count = db.Column(db.Integer(), nullable=False, default=0)
member_count = db.Column(db.Integer(), nullable=False, default=0)
_idx1 = db.Index('group_info_idx1', 'group_id', unique=True)
_idx1 = db.Index("group_info_idx1", "group_id", unique=True)
@classmethod
async def get_group_info(cls, group_id: int) -> 'GroupInfo':
query = cls.query.where(
cls.group_id == group_id
)
async def get_group_info(cls, group_id: int) -> "GroupInfo":
"""
说明:
获取群信息
参数:
:param group_id: 群号
"""
query = cls.query.where(cls.group_id == group_id)
return await query.gino.first()
@classmethod
async def add_group_info(cls, group_id: int, group_name: str, max_member_count: int, member_count: int) -> bool:
async def add_group_info(
cls, group_id: int, group_name: str, max_member_count: int, member_count: int
) -> bool:
"""
说明:
添加群信息
参数:
:param group_id: 群号
:param group_name: 群名称
:param max_member_count: 群员最大数量
:param member_count: 群员数量
"""
try:
group = await cls.query.where(
cls.group_id == group_id
).with_for_update().gino.first()
group = (
await cls.query.where(cls.group_id == group_id)
.with_for_update()
.gino.first()
)
if group:
await cls.update(
group_id=group_id,
@@ -45,12 +62,23 @@ class GroupInfo(db.Model):
@classmethod
async def delete_group_info(cls, group_id: int) -> bool:
"""
说明:
删除群信息
参数:
:param group_id: 群号
"""
try:
await cls.delete.where(
cls.group_id == group_id
).gino.status()
await cls.delete.where(cls.group_id == group_id).gino.status()
return True
except Exception:
return False
@classmethod
async def get_all_group(cls) -> List["GroupInfo"]:
"""
说明:
获取所有群对象
"""
query = await cls.query.gino.all()
return query
+69 -25
View File
@@ -1,10 +1,11 @@
from datetime import datetime
from services.db_context import db
from typing import List
class GroupInfoUser(db.Model):
__tablename__ = 'group_info_users'
__tablename__ = "group_info_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
@@ -13,16 +14,30 @@ class GroupInfoUser(db.Model):
user_join_time = db.Column(db.DateTime(), nullable=False)
nickname = db.Column(db.Unicode())
_idx1 = db.Index('info_group_users_idx1', 'user_qq', 'belonging_group', unique=True)
_idx1 = db.Index("info_group_users_idx1", "user_qq", "belonging_group", unique=True)
@classmethod
async def insert(cls, user_qq: int, belonging_group: int, user_name: str, user_join_time: datetime) -> 'bool':
async def add_member_info(
cls,
user_qq: int,
belonging_group: int,
user_name: str,
user_join_time: datetime,
) -> bool:
"""
说明:
添加群内用户信息
参数:
:param user_qq: qq号
:param belonging_group: 群号
:param user_name: 用户名称
:param user_join_time: 入群时间
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
query = query.with_for_update()
try:
if await query.gino.first() is None:
if not await query.gino.first():
await cls.create(
user_qq=user_qq,
user_name=user_name,
@@ -30,18 +45,34 @@ class GroupInfoUser(db.Model):
user_join_time=user_join_time,
)
return True
except:
except Exception:
return False
@classmethod
async def select_member_info(cls, user_qq: int, belonging_group: int) -> 'GroupInfoUser':
async def get_member_info(
cls, user_qq: int, belonging_group: int
) -> "GroupInfoUser":
"""
说明:
查询群员信息
参数:
:param user_qq: qq号
:param belonging_group: 群号
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
return await query.gino.first()
@classmethod
async def delete_member_info(cls, user_qq: int, belonging_group: int) -> 'bool':
async def delete_member_info(cls, user_qq: int, belonging_group: int) -> bool:
"""
说明:
删除群员信息
参数:
:param user_qq: qq号
:param belonging_group: 群号
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -55,34 +86,53 @@ class GroupInfoUser(db.Model):
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
).gino.status()
return True
except:
except Exception:
return False
@classmethod
async def query_group_member_list(cls, belonging_group: int) -> 'list':
async def get_group_member_id_list(cls, belonging_group: int) -> List[int]:
"""
说明:
获取该群所有用户qq
参数:
:param belonging_group: 群号
"""
member_list = []
query = cls.query.where(
(cls.belonging_group == belonging_group)
)
query = cls.query.where((cls.belonging_group == belonging_group))
for user in await query.gino.all():
member_list.append(user.user_qq)
return member_list
@classmethod
async def set_group_member_nickname(cls, user_qq: int, belonging_group: int, nickname: str) -> 'bool':
async def set_group_member_nickname(
cls, user_qq: int, belonging_group: int, nickname: str
) -> bool:
"""
说明:
设置群员在该群内的昵称
参数:
:param user_qq: qq号
:param belonging_group: 群号
:param nickname: 昵称
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
user = await query.with_for_update().gino.first()
if user:
await user.update(
nickname=nickname
).apply()
await user.update(nickname=nickname).apply()
return True
return False
@classmethod
async def get_group_member_nickname(cls, user_qq: int, belonging_group: int) -> 'str':
async def get_group_member_nickname(cls, user_qq: int, belonging_group: int) -> str:
"""
说明:
获取用户在该群的昵称
参数:
:param user_qq: qq号
:param belonging_group: 群号
"""
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -90,10 +140,4 @@ class GroupInfoUser(db.Model):
if user:
if user.nickname:
return user.nickname
return ''
return ""
+47 -42
View File
@@ -2,99 +2,104 @@ from services.db_context import db
class GroupRemind(db.Model):
__tablename__ = 'group_reminds'
__tablename__ = "group_reminds"
id = db.Column(db.Integer(), primary_key=True)
group_id = db.Column(db.BigInteger(), nullable=False)
hy = db.Column(db.Boolean(), default=False) # 进群欢迎
kxcz = db.Column(db.Boolean(), default=False) # 开箱重置
zwa = db.Column(db.Boolean(), default=False) # 早晚安
gb = db.Column(db.Boolean(), default=True) # 广播
blpar = db.Column(db.Boolean(), default=True) # bilibili转发解析
pa = db.Column(db.Boolean(), default=True) # 爬
epic = db.Column(db.Boolean(), default=False) # epic
almanac = db.Column(db.Boolean(), default=False) # 原神黄历
hy = db.Column(db.Boolean(), default=False) # 进群欢迎
kxcz = db.Column(db.Boolean(), default=False) # 开箱重置
zwa = db.Column(db.Boolean(), default=False) # 早晚安
gb = db.Column(db.Boolean(), default=True) # 广播
blpar = db.Column(db.Boolean(), default=True) # bilibili转发解析
pa = db.Column(db.Boolean(), default=True) # 爬
epic = db.Column(db.Boolean(), default=False) # epic
almanac = db.Column(db.Boolean(), default=False) # 原神黄历
_idx1 = db.Index('info_group_reminds_idx1', 'group_id', unique=True)
_idx1 = db.Index("info_group_reminds_idx1", "group_id", unique=True)
@classmethod
async def get_status(cls, group_id: int, name: str) -> bool:
group = await cls.query.where(
(cls.group_id == group_id)
).gino.first()
"""
说明:
获取群通知状态
参数:
:param group_id: 群号
:param name: 目标名称
"""
group = await cls.query.where((cls.group_id == group_id)).gino.first()
if not group:
group = await cls.create(
group_id=group_id,
)
if name == 'hy':
if name == "hy":
return group.hy
if name == 'kxcz':
if name == "kxcz":
return group.kxcz
if name == 'zwa':
if name == "zwa":
return group.zwa
if name == 'gb':
if name == "gb":
return group.gb
if name == 'blpar':
if name == "blpar":
return group.blpar
if name == 'epic':
if name == "epic":
return group.epic
if name == 'pa':
if name == "pa":
return group.pa
if name == 'almanac':
if name == "almanac":
return group.almanac
@classmethod
async def set_status(cls, group_id: int, name: str, status: bool) -> bool:
"""
说明:
设置群通知状态
参数:
:param group_id: 群号
:param name: 目标名称
:param status: 通知状态
"""
try:
group = await cls.query.where(
(cls.group_id == group_id)
).with_for_update().gino.first()
group = (
await cls.query.where((cls.group_id == group_id))
.with_for_update()
.gino.first()
)
if not group:
group = await cls.create(
group_id=group_id,
)
if name == 'hy':
if name == "hy":
await group.update(
hy=status,
).apply()
if name == 'kxcz':
if name == "kxcz":
await group.update(
kxcz=status,
).apply()
if name == 'zwa':
if name == "zwa":
await group.update(
zwa=status,
).apply()
if name == 'gb':
if name == "gb":
await group.update(
gb=status,
).apply()
if name == 'blpar':
if name == "blpar":
await group.update(
blpar=status,
).apply()
if name == 'epic':
if name == "epic":
await group.update(
epic=status,
).apply()
if name == 'pa':
if name == "pa":
await group.update(
pa=status,
).apply()
if name == 'almanac':
if name == "almanac":
await group.update(
almanac=status,
).apply()
return True
except Exception as e:
return False
+50 -19
View File
@@ -2,7 +2,7 @@ from services.db_context import db
class LevelUser(db.Model):
__tablename__ = 'level_users'
__tablename__ = "level_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
@@ -10,13 +10,18 @@ class LevelUser(db.Model):
user_level = db.Column(db.BigInteger(), nullable=False)
group_flag = db.Column(db.Integer(), nullable=False, default=0)
_idx1 = db.Index('level_group_users_idx1', 'user_qq', 'group_id', unique=True)
_idx1 = db.Index("level_group_users_idx1", "user_qq", "group_id", unique=True)
@classmethod
async def get_user_level(cls, user_qq: int, group_id: int) -> int:
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
"""
说明:
获取用户在群内的等级
参数:
:param user_qq: qq号
:param group_id: 群号
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
user = await query.gino.first()
if user:
return user.user_level
@@ -24,10 +29,19 @@ class LevelUser(db.Model):
return -1
@classmethod
async def set_level(cls, user_qq: int, group_id: int, level: int, group_flag: int = 0) -> 'bool':
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
async def set_level(
cls, user_qq: int, group_id: int, level: int, group_flag: int = 0
) -> bool:
"""
说明:
设置用户在群内的权限
参数:
:param user_qq: qq号
:param group_id: 群号
:param level: 权限等级
:param group_flag: 是否被自动更新刷新权限 0:是,1:否
"""
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:
@@ -43,10 +57,15 @@ class LevelUser(db.Model):
return False
@classmethod
async def delete_level(cls, user_qq: int, group_id: int) -> 'bool':
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
async def delete_level(cls, user_qq: int, group_id: int) -> bool:
"""
说明:
删除用户权限
参数:
:param user_qq: qq号
:param group_id: 群号
"""
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:
@@ -56,7 +75,15 @@ class LevelUser(db.Model):
return True
@classmethod
async def check_level(cls, user_qq: int, group_id: int, level: int) -> 'bool':
async def check_level(cls, user_qq: int, group_id: int, level: int) -> bool:
"""
说明:
检查用户权限等级是否大于 level
参数:
:param user_qq: qq号
:param group_id: 群号
:param level: 权限等级
"""
if group_id != 0:
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
@@ -66,9 +93,7 @@ class LevelUser(db.Model):
return False
user_level = user.user_level
else:
query = cls.query.where(
cls.user_qq == user_qq
)
query = cls.query.where(cls.user_qq == user_qq)
highest_level = 0
for user in await query.gino.all():
if user.user_level > highest_level:
@@ -80,7 +105,14 @@ class LevelUser(db.Model):
return False
@classmethod
async def is_group_flag(cls, user_qq: int, group_id: int) -> 'bool':
async def is_group_flag(cls, user_qq: int, group_id: int) -> bool:
"""
说明:
检测是否会被自动更新刷新权限
参数:
:param user_qq: qq号
:param group_id: 群号
"""
user = await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
).gino.first()
@@ -90,4 +122,3 @@ class LevelUser(db.Model):
return True
else:
return False
+165
View File
@@ -0,0 +1,165 @@
from typing import Optional, List
from services.db_context import db
class Pixiv(db.Model):
__tablename__ = "pixiv"
id = db.Column(db.Integer(), primary_key=True)
pid = db.Column(db.BigInteger(), nullable=False)
title = db.Column(db.String(), nullable=False)
width = db.Column(db.Integer(), nullable=False)
height = db.Column(db.Integer(), nullable=False)
view = db.Column(db.Integer(), nullable=False)
bookmarks = db.Column(db.Integer(), nullable=False)
img_url = db.Column(db.String(), nullable=False)
img_p = db.Column(db.String(), nullable=False)
uid = db.Column(db.BigInteger(), nullable=False)
author = db.Column(db.String(), nullable=False)
is_r18 = db.Column(db.Boolean(), nullable=False)
tags = db.Column(db.String(), nullable=False)
_idx1 = db.Index("pixiv_idx1", "pid", "img_url", unique=True)
@classmethod
async def add_image_data(
cls,
pid: int,
title: str,
width: int,
height: int,
view: int,
bookmarks: int,
img_url: str,
img_p: str,
uid: int,
author: str,
tags: str,
):
"""
说明:
添加图片信息
参数:
:param pid: pid
:param title: 标题
:param width: 宽度
:param height: 长度
:param view: 被查看次数
:param bookmarks: 收藏数
:param img_url: url链接
:param img_p: 张数
:param uid: 作者uid
:param author: 作者名称
:param tags: 相关tag
"""
if not await cls.check_exists(pid, img_p):
await cls.create(
pid=pid,
title=title,
width=width,
height=height,
view=view,
bookmarks=bookmarks,
img_url=img_url,
img_p=img_p,
uid=uid,
author=author,
is_r18=True if 'R-18' in tags else False,
tags=tags,
)
return True
return False
@classmethod
async def remove_image_data(cls, pid: int, img_p: str) -> bool:
"""
说明:
删除图片数据
参数:
:param pid: 图片pid
:param img_p: 图片pid的张数,如:p0,p1
"""
try:
if img_p:
await cls.delete.where(
(cls.pid == pid) & (cls.img_p == img_p)
).gino.status()
else:
await cls.delete.where(cls.pid == pid).gino.status()
return True
except Exception:
return False
@classmethod
async def get_all_pid(cls) -> List[int]:
"""
说明:
获取所有PID
"""
pid = []
query = await cls.query.gino.all()
for image in query:
if image.pid not in pid:
pid.append(image.pid)
return pid
# 0:非r18 1:r18 2:混合
@classmethod
async def query_images(
cls,
keyword: Optional[List[str]] = None,
uid: Optional[int] = None,
pid: Optional[int] = None,
r18: int = 0,
) -> List[Optional["Pixiv"]]:
"""
说明:
查找符合条件的图片
参数:
:param keyword: 关键词
:param uid: 画师uid
:param pid: 图片pid
:param r18: 是否r18,0:非r18 1:r18 2:混合
"""
if r18 == 0:
query = await cls.query.where(cls.is_r18 == False).gino.all()
elif r18 == 1:
query = await cls.query.where(cls.is_r18 == True).gino.all()
else:
query = await cls.query.gino.all()
if keyword:
query = [x for x in query if set(x.tags.split(',')) > set(keyword)]
elif uid:
query = [x for x in query if x.uid == uid]
elif pid:
query = [x for x in query if x.pid == pid]
return query
@classmethod
async def check_exists(cls, pid: int, img_p: str) -> bool:
"""
说明:
检测pid是否已存在
参数:
:param pid: 图片PID
:param img_p: 张数
"""
query = await cls.query.where(
(cls.pid == pid) & (cls.img_p == img_p)
).gino.all()
return bool(query)
@classmethod
async def get_keyword_num(cls, keyword: List[str]) -> "int, int":
"""
说明:
获取相关关键词(keyword, tag)在图库中的数量
参数:
:param keyword: 关键词/Tag
"""
query = await cls.query.gino.all()
query = [x for x in query if set(x.tags.split(',')) > set(keyword)]
r18_count = len([x for x in query if x.is_r18])
return len(query) - r18_count, r18_count
+126
View File
@@ -0,0 +1,126 @@
from services.db_context import db
from typing import Set, List
class PixivKeywordUser(db.Model):
__tablename__ = "pixiv_keyword_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.BigInteger(), nullable=False)
keyword = db.Column(db.String(), nullable=False)
is_pass = db.Column(db.Boolean(), default=False)
_idx1 = db.Index("pixiv_keyword_users_idx1", "keyword", unique=True)
@classmethod
async def add_keyword(
cls, user_qq: int, group_id: int, keyword: str, superusers: Set[str]
) -> bool:
"""
说明:
添加搜图的关键词
参数:
:param user_qq: qq号
:param group_id: 群号
:param keyword: 关键词
:param superusers: 是否为超级用户
"""
is_pass = True if str(user_qq) in superusers else False
if not await cls._check_keyword_exists(keyword):
await cls.create(
user_qq=user_qq, group_id=group_id, keyword=keyword, is_pass=is_pass
)
return True
return False
@classmethod
async def delete_keyword(cls, keyword: str) -> bool:
"""
说明:
删除关键词
参数:
:param keyword: 关键词
"""
if await cls._check_keyword_exists(keyword):
query = cls.query.where(cls.keyword == keyword).with_for_update()
query = await query.gino.first()
await query.delete()
return True
return False
@classmethod
async def set_keyword_pass(cls, keyword: str, is_pass: bool) -> "int, int":
"""
说明:
通过或禁用关键词
参数:
:param keyword: 关键词
:param is_pass: 通过状态
"""
if await cls._check_keyword_exists(keyword):
query = cls.query.where(cls.keyword == keyword).with_for_update()
query = await query.gino.first()
await query.update(
is_pass=is_pass,
).apply()
return query.user_qq, query.group_id
return 0, 0
@classmethod
async def get_all_user_dict(cls) -> dict:
"""
说明:
获取关键词数据库各个用户贡献的关键词字典
"""
tmp = {}
query = await cls.query.gino.all()
for user in query:
if not tmp.get(user.user_qq):
tmp[user.user_qq] = {"keyword": []}
tmp[user.user_qq]["keyword"].append(user.keyword)
return tmp
@classmethod
async def get_current_keyword(cls) -> "List[str], List[str]":
"""
说明:
获取当前通过与未通过的关键词
"""
pass_keyword = []
not_pass_keyword = []
query = await cls.query.gino.all()
for user in query:
if user.is_pass:
pass_keyword.append(user.keyword)
else:
not_pass_keyword.append(user.keyword)
return pass_keyword, not_pass_keyword
@classmethod
async def get_black_pid(cls) -> List[str]:
"""
说明:
获取黑名单PID
"""
black_pid = []
query = await cls.query.where(cls.user_qq == 114514).gino.all()
for image in query:
black_pid.append(image.keyword[6:])
return black_pid
@classmethod
async def _check_keyword_exists(cls, keyword: str) -> bool:
"""
说明:
检测关键词是否已存在
参数:
:param keyword: 关键词
"""
current_keyword = []
query = await cls.query.gino.all()
for user in query:
current_keyword.append(user.keyword)
if keyword in current_keyword:
return True
return False
+33 -25
View File
@@ -1,9 +1,9 @@
from services.db_context import db
from typing import List
class RedbagUser(db.Model):
__tablename__ = 'redbag_users'
__tablename__ = "redbag_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
@@ -13,18 +13,25 @@ class RedbagUser(db.Model):
spend_gold = db.Column(db.Integer(), default=0)
get_gold = db.Column(db.Integer(), default=0)
_idx1 = db.Index('redbag_group_users_idx1', 'user_qq', 'group_id', unique=True)
_idx1 = db.Index("redbag_group_users_idx1", "user_qq", "group_id", unique=True)
@classmethod
async def add_redbag_data(cls, user_qq: int, group_id: int, itype: str, money: int):
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
"""
说明:
添加收发红包数据
参数:
:param user_qq: qq号
:param group_id: 群号
:param itype: 收或发
:param money: 金钱数量
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
user = await query.with_for_update().gino.first() or await cls.create(
user_qq=user_qq,
group_id=group_id,
)
if itype == 'get':
user_qq=user_qq,
group_id=group_id,
)
if itype == "get":
await user.update(
get_redbag_count=user.get_redbag_count + 1,
get_gold=user.get_gold + money,
@@ -37,9 +44,14 @@ class RedbagUser(db.Model):
@classmethod
async def ensure(cls, user_qq: int, group_id: int) -> bool:
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
"""
说明:
获取用户对象
参数:
:param user_qq: qq号
:param group_id: 群号
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
user = await query.gino.first() or await cls.create(
user_qq=user_qq,
group_id=group_id,
@@ -47,19 +59,15 @@ class RedbagUser(db.Model):
return user
@classmethod
async def get_user_all(cls, group_id: int = None) -> list:
async def get_user_all(cls, group_id: int = None) -> List["RedbagUser"]:
"""
说明:
获取所有用户对象
参数:
:param group_id: 群号
"""
if not group_id:
query = await cls.query.gino.all()
else:
query = await cls.query.where(
(cls.group_id == group_id)
).gino.all()
query = await cls.query.where((cls.group_id == group_id)).gino.all()
return query
+60 -32
View File
@@ -3,7 +3,7 @@ from typing import List
class RussianUser(db.Model):
__tablename__ = 'russian_users'
__tablename__ = "russian_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
@@ -13,34 +13,49 @@ class RussianUser(db.Model):
make_money = db.Column(db.Integer(), default=0)
lose_money = db.Column(db.Integer(), default=0)
_idx1 = db.Index('russian_group_users_idx1', 'user_qq', 'group_id', unique=True)
_idx1 = db.Index("russian_group_users_idx1", "user_qq", "group_id", unique=True)
@classmethod
async def ensure(cls, user_qq: int, group_id: int) -> 'RussianUser':
user = await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
).with_for_update().gino.first()
return user or await cls.create(
user_qq=user_qq,
group_id=group_id
async def ensure(cls, user_qq: int, group_id: int) -> "RussianUser":
"""
说明:
获取用户对象
参数:
:param user_qq: qq号
:param group_id: 群号
"""
user = (
await cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
.with_for_update()
.gino.first()
)
return user or await cls.create(user_qq=user_qq, group_id=group_id)
@classmethod
async def add_count(cls, user_qq: int, group_id: int, itype: str) -> bool:
"""
说明:
添加用户输赢次数
说明:
:param user_qq: qq号
:param group_id: 群号
:param itype: 输或赢 'win' or 'lose'
"""
try:
user = await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
).with_for_update().gino.first()
if not user:
user = await cls.create(
user_qq=user_qq,
group_id=group_id
user = (
await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
if itype == 'win':
.with_for_update()
.gino.first()
)
if not user:
user = await cls.create(user_qq=user_qq, group_id=group_id)
if itype == "win":
await user.update(
win_count=user.win_count + 1,
).apply()
elif itype == 'lose':
elif itype == "lose":
await user.update(
fail_count=user.fail_count + 1,
).apply()
@@ -50,20 +65,30 @@ class RussianUser(db.Model):
@classmethod
async def money(cls, user_qq: int, group_id: int, itype: str, count: int) -> bool:
"""
说明:
添加用户输赢金钱
参数:
:param user_qq: qq号
:param group_id: 群号
:param itype: 输或赢 'win' or 'lose'
:param count: 金钱数量
"""
try:
user = await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
).with_for_update().gino.first()
if not user:
user = await cls.create(
user_qq=user_qq,
group_id=group_id
user = (
await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
if itype == 'win':
.with_for_update()
.gino.first()
)
if not user:
user = await cls.create(user_qq=user_qq, group_id=group_id)
if itype == "win":
await user.update(
make_money=user.make_money + count,
).apply()
elif itype == 'lose':
elif itype == "lose":
await user.update(
lose_money=user.lose_money + count,
).apply()
@@ -72,9 +97,12 @@ class RussianUser(db.Model):
return False
@classmethod
async def all_user(cls, group_id: int) -> List['RussianUser']:
users = await cls.query.where(
(cls.group_id == group_id)
).gino.all()
async def get_all_user(cls, group_id: int) -> List["RussianUser"]:
"""
说明:
获取该群所有用户对象
参数:
:param group_id: 群号
"""
users = await cls.query.where((cls.group_id == group_id)).gino.all()
return users
+168
View File
@@ -0,0 +1,168 @@
from services.db_context import db
from typing import List, Optional
class Setu(db.Model):
__tablename__ = "setu"
id = db.Column(db.Integer(), primary_key=True)
local_id = db.Column(db.Integer(), nullable=False)
title = db.Column(db.String(), nullable=False)
author = db.Column(db.String(), nullable=False)
pid = db.Column(db.BigInteger(), nullable=False)
img_hash = db.Column(db.String(), nullable=False)
img_url = db.Column(db.String(), nullable=False)
is_r18 = db.Column(db.Boolean(), nullable=False)
tags = db.Column(db.String())
_idx1 = db.Index("setu_pid_img_url_idx1", "pid", "img_url", unique=True)
@classmethod
async def add_setu_data(
cls,
local_id: int,
title: str,
author: str,
pid: int,
img_hash: str,
img_url: str,
tags: str,
):
"""
说明:
添加一份色图数据
参数:
:param local_id: 本地存储id
:param title: 标题
:param author: 作者
:param pid: 图片pid
:param img_hash: 图片hash值
:param img_url: 图片链接
:param tags: 图片标签
"""
if not await cls._check_exists(pid, img_url):
await cls.create(
local_id=local_id,
title=title,
author=author,
pid=pid,
img_hash=img_hash,
img_url=img_url,
is_r18=True if "R-18" in tags else False,
tags=tags,
)
@classmethod
async def query_image(
cls,
local_id: Optional[int] = None,
tags: Optional[List[str]] = None,
r18: int = 0,
):
"""
说明:
通过tag查找色图
参数:
:param local_id: 本地色图 id
:param tags: tags
:param r18: 是否 r18,0:非r18 1:r18 2:混合
"""
if local_id:
flag = True if r18 == 1 else False
return await cls.query.where(
(cls.local_id == local_id) & (cls.is_r18 == flag)
).gino.first()
if r18 == 0:
query = await cls.query.where(cls.is_r18 == False).gino.all()
elif r18 == 1:
query = await cls.query.where(cls.is_r18 == True).gino.all()
else:
query = await cls.query.gino.all()
if tags:
query = [x for x in query if set(x.tags.split(",")) > set(tags)]
return query
@classmethod
async def get_image_count(cls, r18: int = 0):
"""
说明:
查询图片数量
"""
return len(await cls.query_image(r18=r18))
# return await db.func.count(cls.local_id).gino.scalar()
@classmethod
async def get_image_in_hash(cls, img_hash: str) -> "Setu":
"""
说明:
通过图像hash获取图像信息
参数:
:param img_hash: = 图像hash值
"""
query = await cls.query.where(cls.img_hash == img_hash).gino.first()
return query
@classmethod
async def _check_exists(cls, pid: int, img_url: str) -> bool:
"""
说明:
检测图片是否存在
参数:
:param pid: 图片pid
:param img_url: 图片链接
"""
return bool(
await cls.query.where(
(cls.pid == pid) & (cls.img_url == img_url)
).gino.first()
)
@classmethod
async def update_setu_data(
cls,
pid: int,
*,
local_id: Optional[int] = None,
title: Optional[str] = None,
author: Optional[str] = None,
img_hash: Optional[str] = None,
img_url: Optional[str] = None,
tags: Optional[str] = None,
) -> bool:
"""
说明:
根据PID修改图片数据
参数:
:param local_id: 本地id
:param pid: 图片pid
:param title: 标题
:param author: 作者
:param img_hash: 图片hash值
:param img_url: 图片链接
:param tags: 图片标签
"""
query = cls.query.where(cls.pid == pid).with_for_update()
image_list = await query.gino.all()
if image_list:
for image in image_list:
if local_id:
await image.update(local_id=local_id).apply()
if title:
await image.update(title=title).apply()
if author:
await image.update(author=author).apply()
if img_hash:
await image.update(img_hash=img_hash).apply()
if img_url:
await image.update(img_url=img_url).apply()
if tags:
await image.update(tags=tags).apply()
return True
return False
@classmethod
async def get_all_setu(cls) -> List["Setu"]:
"""
说明:
获取所有图片对象
"""
return await cls.query.gino.all()
+19 -10
View File
@@ -4,7 +4,7 @@ from services.db_context import db
class SignGroupUser(db.Model):
__tablename__ = 'sign_group_users'
__tablename__ = "sign_group_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
@@ -13,13 +13,19 @@ class SignGroupUser(db.Model):
checkin_count = db.Column(db.Integer(), nullable=False)
checkin_time_last = db.Column(db.DateTime(timezone=True), nullable=False)
impression = db.Column(db.Numeric(scale=3, asdecimal=False), nullable=False)
add_probability = db.Column(db.Numeric(scale=3, asdecimal=False), nullable=False, default=0)
specify_probability = db.Column(db.Numeric(scale=3, asdecimal=False), nullable=False, default=0)
add_probability = db.Column(
db.Numeric(scale=3, asdecimal=False), nullable=False, default=0
)
specify_probability = db.Column(
db.Numeric(scale=3, asdecimal=False), nullable=False, default=0
)
_idx1 = db.Index('sign_group_users_idx1', 'user_qq', 'belonging_group', unique=True)
_idx1 = db.Index("sign_group_users_idx1", "user_qq", "belonging_group", unique=True)
@classmethod
async def ensure(cls, user_qq: int, belonging_group: int, for_update: bool = False) -> 'SignGroupUser':
async def ensure(
cls, user_qq: int, belonging_group: int, for_update: bool = False
) -> "SignGroupUser":
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
@@ -35,14 +41,18 @@ class SignGroupUser(db.Model):
)
@classmethod
async def query_impression_all(cls, belonging_group: int) -> 'list,list':
async def get_all_impression(cls, belonging_group: int) -> "list, list":
"""
说明:
获取该群所有用户 id 及对应 好感度
参数:
:param belonging_group: 群号
"""
impression_list = []
user_qq_list = []
user_group = []
if belonging_group:
query = cls.query.where(
(cls.belonging_group == belonging_group)
)
query = cls.query.where(cls.belonging_group == belonging_group)
else:
query = cls.query
for user in await query.gino.all():
@@ -50,4 +60,3 @@ class SignGroupUser(db.Model):
user_qq_list.append(user.user_qq)
user_group.append(user.belonging_group)
return user_qq_list, impression_list, user_group
+22 -35
View File
@@ -1,7 +1,7 @@
import random
from nonebot import on_keyword
import os
from utils.init_result import image
from utils.message_builder import image
from configs.path_config import IMAGE_PATH
from nonebot import on_command
from nonebot.rule import to_me
@@ -11,14 +11,14 @@ from nonebot.adapters.cqhttp.permission import GROUP
from utils.utils import FreqLimiter
__plugin_name__ = '基本设置 [Hidden]'
__plugin_usage__ = '用法: 无'
__plugin_name__ = "基本设置 [Hidden]"
__plugin_usage__ = "用法: 无"
_flmt = FreqLimiter(300)
config_playgame = on_keyword({'打游戏'}, permission=GROUP, priority=1, block=True)
config_playgame = on_keyword({"打游戏"}, permission=GROUP, priority=1, block=True)
@config_playgame.handle()
@@ -26,46 +26,33 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if not _flmt.check(event.group_id):
return
_flmt.start_cd(event.group_id)
await config_playgame.finish(image(
random.choice(os.listdir(IMAGE_PATH + "dayouxi/")
), "dayouxi"))
await config_playgame.finish(
image(random.choice(os.listdir(IMAGE_PATH + "dayouxi/")), "dayouxi")
)
self_introduction = on_command("自我介绍", aliases={'介绍', '你是谁', '你叫什么'},
rule=to_me(), priority=5, block=True)
self_introduction = on_command(
"自我介绍", aliases={"介绍", "你是谁", "你叫什么"}, rule=to_me(), priority=5, block=True
)
@self_introduction.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
result = "我叫绪山真寻\n" \
"你们可以叫我真寻,小真寻,哪怕你们叫我小寻子我也能接受!\n" \
"年龄的话我还是个**岁初中生(至少现在是)\n" \
"身高保密!!!(也就比美波里(姐姐..(妹妹))矮一点)\n" \
"我生日是在3月6号, 能记住的话我会很高兴的\n现在是自宅警备系的现役JC\n" \
"最好的朋友是椛!\n"\
+ image("zhenxun")
result = (
"我叫绪山真寻\n"
"你们可以叫我真寻,小真寻,哪怕你们叫我小寻子我也能接受!\n"
"年龄的话我还是个**岁初中生(至少现在是)\n"
"身高保密!!!(也就比美波里(姐姐..(妹妹))矮一点)\n"
"我生日是在3月6号, 能记住的话我会很高兴的\n现在是自宅警备系的现役JC\n"
"最好的朋友是椛!\n" + image("zhenxun")
)
await self_introduction.finish(result)
laopo = on_keyword({'老婆'}, rule=to_me(), priority=5, block=True)
my_wife = on_keyword({"老婆"}, rule=to_me(), priority=5, block=True)
@laopo.handle()
@my_wife.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
await laopo.finish(image('laopo.jpg', 'other'))
await my_wife.finish(image("laopo.jpg", "other"))
# config_robot = on_keyword({"机器人"}, permission=GROUP, priority=5, block=True)
# @config_robot.handle()
# async def _(bot: Bot, event: Event, state: T_State):
# if not _flmt.check(event.group_id) or event.group_id == 774261838:
# return
# _flmt.start_cd(event.group_id)
# await config_robot.send("小真寻才不是机器人!")
# result = "我叫绪山真寻\n" \
# "你们可以叫我真寻,小真寻,哪怕你们叫我小寻子我也能接受!\n" \
# "年龄的话我还是个**岁初中生(至少现在是)\n" \
# "身高保密!!!(也就比美波里(姐姐..(妹妹))矮一点)\n" \
# "我生日是在3月6号, 能记住的话我会很高兴的\n现在是自宅警备系的现役JC\n" \
# "最好的朋友是椛!\n"\
# + image("zhenxun", "")
# await config_jieshao.finish(result)
+6 -84
View File
@@ -1,89 +1,11 @@
from nonebot import on_command
from utils.utils import get_message_text, get_message_imgs, scheduler, get_bot
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from .data_source import set_group_status, custom_group_welcome, change_group_switch, \
update_member_info, group_current_status
from nonebot.adapters.cqhttp.permission import GROUP
from services.log import logger
from configs.config import plugins2info_dict
from nonebot.plugin import export
from .data_source import update_member_info
from .custom_welcome_message import *
from .group_notification_state import *
from .switch_rule import *
from .update_group_member_info import *
from .timing_task import *
__plugin_name__ = '自定义进群欢迎消息'
__plugin_usage__ = '''自定义进群欢迎消息 [消息] [图片](可省略)
\t示例:自定义进群欢迎消息 欢迎新人![图片]'''
export = export()
export.update_member_info = update_member_info
cmds = []
for cmd_list in plugins2info_dict.values():
for cmd in cmd_list['cmd']:
cmds.append(f'开启{cmd}')
cmds.append(f'关闭{cmd}')
cmds = set(cmds)
group_status = on_command('oc_reminds', aliases={'开启早晚安', '关闭早晚安',
'开启进群欢迎', '关闭进群欢迎',
'开启每日开箱重置提醒', '关闭每日开箱重置提醒',
'开启b站转发解析', '关闭b站转发解析',
'开启epic通知', '关闭epic通知',
'开启丢人爬', '关闭丢人爬',
'开启原神黄历提醒', '关闭原神黄历提醒',
'开启全部通知', '开启所有通知', '关闭全部通知', '关闭所有通知',
'群通知状态'}, permission=GROUP, priority=1, block=True)
switch_rule = on_command('switch_rule', aliases=cmds, permission=GROUP, priority=4, block=True)
custom_welcome = on_command('自定义进群欢迎消息', aliases={'自定义欢迎消息', '自定义群欢迎消息', '设置群欢迎消息'}, permission=GROUP, priority=5, block=True)
refresh_member_group = on_command("更新群组成员列表", aliases={"更新群组成员信息"}, permission=GROUP, priority=5, block=True)
@switch_rule.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
await switch_rule.send(await change_group_switch(state["_prefix"]["raw_command"].strip(), event.group_id))
logger.info(f'USER {event.user_id} GROUP {event.group_id} 使用群功能管理命令 {state["_prefix"]["raw_command"]}')
@group_status.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if state["_prefix"]["raw_command"] in ['群通知状态']:
await group_status.finish(await group_current_status(event.group_id))
await group_status.send(await set_group_status(state["_prefix"]["raw_command"], event.group_id),
at_sender=True)
logger.info(f'USER {event.user_id} GROUP {event.group_id} 使用群通知管理命令 {state["_prefix"]["raw_command"]}')
@custom_welcome.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
msg = get_message_text(event.json())
imgs = get_message_imgs(event.json())
if not msg and not imgs:
await custom_welcome.finish('格式:自定义群欢迎消息 [文本] [图片]\n\t示例:自定义群欢迎消息 我们都是萝莉控,你呢? [图片]')
await custom_welcome.finish(await custom_group_welcome(msg, imgs, event.user_id, event.group_id), at_sender=True)
@refresh_member_group.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if await update_member_info(event.group_id):
await refresh_member_group.finish("更新群员信息成功!", at_sender=True)
else:
await refresh_member_group.finish("更新群员信息失败!", at_sender=True)
# 自动更新群员信息
@scheduler.scheduled_job(
'cron',
hour=2,
minute=1,
)
async def _():
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
for g in gl:
try:
await update_member_info(g)
logger.info(f'更新群组 g:{g} 成功')
except Exception as e:
logger.error(f'更新群组错误 g:{g} e:{e}')
@@ -0,0 +1,37 @@
from nonebot import on_command
from utils.utils import get_message_text, get_message_imgs
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from .data_source import custom_group_welcome
from nonebot.adapters.cqhttp.permission import GROUP
from services.log import logger
__plugin_name__ = "自定义进群欢迎消息"
__plugin_usage__ = """
自定义进群欢迎消息 [消息] [图片](可省略)
示例:自定义进群欢迎消息 欢迎新人![图片]
"""
custom_welcome = on_command(
"自定义进群欢迎消息",
aliases={"自定义欢迎消息", "自定义群欢迎消息", "设置群欢迎消息"},
permission=GROUP,
priority=5,
block=True,
)
@custom_welcome.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
msg = get_message_text(event.json())
imgs = get_message_imgs(event.json())
if not msg and not imgs:
await custom_welcome.finish(__plugin_usage__)
await custom_welcome.send(
await custom_group_welcome(msg, imgs, event.user_id, event.group_id),
at_sender=True,
)
logger.info(f"USER {event.user_id} GROUP {event.group_id} 自定义群欢迎消息:{msg}")
+4 -4
View File
@@ -4,7 +4,7 @@ from configs.path_config import DATA_PATH
import os
import aiofiles
import aiohttp
from utils.init_result import image
from utils.message_builder import image
from utils.utils import get_local_proxy, get_bot
from pathlib import Path
from nonebot import require
@@ -173,7 +173,7 @@ async def update_member_info(group_id: int) -> bool:
await LevelUser.set_level(user_info['user_id'], user_info['group_id'], 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)
user = await GroupInfoUser.select_member_info(user_info['user_id'], user_info['group_id'])
user = await GroupInfoUser.get_member_info(user_info['user_id'], user_info['group_id'])
if user:
if user.user_name != nickname:
await user.update(user_name=nickname).apply()
@@ -182,7 +182,7 @@ async def update_member_info(group_id: int) -> bool:
continue
join_time = datetime.strptime(
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user_info['join_time'])), "%Y-%m-%d %H:%M:%S")
if await GroupInfoUser.insert(
if await GroupInfoUser.add_member_info(
user_info['user_id'],
user_info['group_id'],
nickname,
@@ -191,7 +191,7 @@ async def update_member_info(group_id: int) -> bool:
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新成功")
else:
_error_member_list.append(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新失败\n")
_del_member_list = list(set(_exist_member_list).difference(set(await GroupInfoUser.query_group_member_list(group_id))))
_del_member_list = list(set(_exist_member_list).difference(set(await GroupInfoUser.get_group_member_id_list(group_id))))
if _del_member_list:
for del_user in _del_member_list:
if await GroupInfoUser.delete_member_info(del_user, group_id):
@@ -0,0 +1,57 @@
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from .data_source import set_group_status, group_current_status
from nonebot.adapters.cqhttp.permission import GROUP
from services.log import logger
from nonebot import on_command
__plugin_name__ = "群通知开关"
__plugin_usage__ = """
示例:
开启早晚安
关闭早晚安
"""
group_status = on_command(
"oc_reminds",
aliases={
"开启早晚安",
"关闭早晚安",
"开启进群欢迎",
"关闭进群欢迎",
"开启每日开箱重置提醒",
"关闭每日开箱重置提醒",
"开启b站转发解析",
"关闭b站转发解析",
"开启epic通知",
"关闭epic通知",
"开启丢人爬",
"关闭丢人爬",
"开启原神黄历提醒",
"关闭原神黄历提醒",
"开启全部通知",
"开启所有通知",
"关闭全部通知",
"关闭所有通知",
"群通知状态",
},
permission=GROUP,
priority=1,
block=True,
)
@group_status.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if state["_prefix"]["raw_command"] in ["群通知状态"]:
await group_status.finish(await group_current_status(event.group_id))
await group_status.send(
await set_group_status(state["_prefix"]["raw_command"], event.group_id),
at_sender=True,
)
logger.info(
f'USER {event.user_id} GROUP {event.group_id} 使用群通知管理命令 {state["_prefix"]["raw_command"]}'
)
+41
View File
@@ -0,0 +1,41 @@
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from .data_source import change_group_switch
from nonebot.adapters.cqhttp.permission import GROUP
from services.log import logger
from configs.config import plugins2info_dict
__plugin_name__ = "群功能开关"
__plugin_usage__ = """
示例:
开启色图
关闭色图
"""
cmds = []
for cmd_list in plugins2info_dict.values():
for cmd in cmd_list["cmd"]:
cmds.append(f"开启{cmd}")
cmds.append(f"关闭{cmd}")
cmds = set(cmds)
switch_rule = on_command(
"switch_rule", aliases=cmds, permission=GROUP, priority=4, block=True
)
@switch_rule.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
await switch_rule.send(
await change_group_switch(
state["_prefix"]["raw_command"].strip(), event.group_id
)
)
logger.info(
f'USER {event.user_id} GROUP {event.group_id} 使用群功能管理命令 {state["_prefix"]["raw_command"]}'
)
+38
View File
@@ -0,0 +1,38 @@
from utils.utils import scheduler, get_bot
from .data_source import update_member_info
from services.log import logger
from models.group_info import GroupInfo
# 自动更新群员信息
@scheduler.scheduled_job(
"cron",
hour=2,
minute=1,
)
async def _():
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g["group_id"] for g in gl]
for g in gl:
try:
await update_member_info(g)
logger.info(f"更新群组 g:{g} 成功")
except Exception as e:
logger.error(f"更新群组错误 g:{g} e:{e}")
# 快速更新群员信息以及管理员权限
@scheduler.scheduled_job(
"interval",
minutes=5,
)
async def _():
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g["group_id"] for g in gl]
all_group = [x.group_id for x in await GroupInfo.get_all_group()]
for g in gl:
if g not in all_group:
await update_member_info(g)
logger.info(f"快速更新群信息以及权限:{g}")
@@ -0,0 +1,27 @@
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from .data_source import update_member_info
__plugin_name__ = "更新群组成员列表"
__plugin_usage__ = """
说明:
更新群组成员的基本信息
示例:
更新群组成员列表
"""
from nonebot.adapters.cqhttp.permission import GROUP
refresh_member_group = on_command(
"更新群组成员列表", aliases={"更新群组成员信息"}, permission=GROUP, priority=5, block=True
)
@refresh_member_group.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if await update_member_info(event.group_id):
await refresh_member_group.finish("更新群员信息成功!", at_sender=True)
else:
await refresh_member_group.finish("更新群员信息失败!", at_sender=True)
+9 -10
View File
@@ -7,9 +7,9 @@ from models.group_member_info import GroupInfoUser
from configs.config import ADMIN_DEFAULT_AUTH
__plugin_name__ = '群管理员监测'
__plugin_name__ = "群管理员监测"
__plugin_usage__ = '无'
__plugin_usage__ = "无"
admin_notice = on_notice(priority=5)
@@ -18,15 +18,14 @@ admin_notice = on_notice(priority=5)
@admin_notice.handle()
async def _(bot: Bot, event: GroupAdminNoticeEvent, state: T_State):
try:
nickname = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
nickname = (
await GroupInfoUser.get_member_info(event.user_id, event.group_id)
).user_name
except AttributeError:
nickname = event.user_id
if event.sub_type == 'set':
if event.sub_type == "set":
await LevelUser.set_level(event.user_id, event.group_id, ADMIN_DEFAULT_AUTH)
logger.info(f'为新晋管理员 {nickname}({event.user_id}) 添加权限等级:{ADMIN_DEFAULT_AUTH}')
elif event.sub_type == 'unset':
logger.info(f"为新晋管理员 {nickname}({event.user_id}) 添加权限等级:{ADMIN_DEFAULT_AUTH}")
elif event.sub_type == "unset":
await LevelUser.delete_level(event.user_id, event.group_id)
logger.info(f'将非管理员 {nickname}({event.user_id}) 取消权限等级')
logger.info(f"将非管理员 {nickname}({event.user_id}) 取消权限等级")
+6 -3
View File
@@ -2,9 +2,9 @@ from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters import Bot
from nonebot.adapters.cqhttp import GroupMessageEvent
from utils.img_utils import CreateImg
from utils.image_utils import CreateImg
from configs.path_config import IMAGE_PATH
from utils.init_result import image
from utils.message_builder import image
__plugin_name__ = '管理帮助 [Hidden]'
@@ -28,6 +28,7 @@ __plugin_usage__ = '''管理帮助(权限等级):
'''
passive_help = '''【被动技能开关(2):
开启/关闭早晚安
开启/关闭进群欢迎
开启/关闭每日开箱重置提醒
开启/关闭b站转发解析
@@ -41,7 +42,9 @@ admin_help = on_command("管理员帮助", aliases={"管理帮助"}, priority=5,
admin_help_img = CreateImg(1000, 600, font_size=24)
admin_help_img.text((10, 10), __plugin_usage__)
admin_help_img.paste(CreateImg(450, 600, font_size=24).text((0, 0), passive_help), (650, 50))
text_img = CreateImg(450, 600, font_size=24)
text_img.text((0, 0), passive_help)
admin_help_img.paste(text_img, (650, 50))
admin_help_img.save(IMAGE_PATH + 'admin_help_img.png')
+36 -37
View File
@@ -1,61 +1,60 @@
from .data_source import get_qqbot_chat_result, hello, no_result
from .data_source import get_chat_result, hello, no_result
from services.log import logger
from nonebot import on_message
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, PrivateMessageEvent, Message
from nonebot.adapters.cqhttp import (
Bot,
PrivateMessageEvent,
Message,
MessageEvent,
)
from utils.utils import get_message_text, get_message_imgs
from models.friend_user import FriendUser
from models.group_member_info import GroupInfoUser
__plugin_name__ = 'AI [Hidden]'
__plugin_name__ = "AI [Hidden]"
ai = on_message(rule=to_me(), priority=8)
@ai.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
imgs = get_message_imgs(event.json())
if str(event.get_message()).find('CQ:xml') != -1:
if "CQ:xml" in msg:
return
# 打招呼
if (not msg and not imgs) or msg in ['你好啊', '你好', '在吗', '在不在', '您好', '您好啊', '你好', '在']:
if (not msg and not imgs) or msg in [
"你好啊",
"你好",
"在吗",
"在不在",
"您好",
"您好啊",
"你好",
"在",
]:
await ai.finish(hello())
img = imgs[0] if imgs else ''
nickname = await FriendUser.get_friend_nickname(event.user_id)
img = imgs[0] if imgs else ""
if isinstance(event, PrivateMessageEvent):
nickname = await FriendUser.get_friend_nickname(event.user_id)
else:
nickname = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
if not nickname:
nickname = await FriendUser.get_user_name(event.user_id)
if not nickname:
nickname = "你"
result = await get_qqbot_chat_result(msg, img, event.user_id, nickname)
logger.info(f"USER {event.user_id} 问题:{msg}\n回答:{result}")
if isinstance(event, PrivateMessageEvent):
nickname = event.sender.nickname
else:
nickname = event.sender.card if event.sender.card else event.sender.nickname
result = await get_chat_result(msg, img, event.user_id, nickname)
logger.info(
f"USER {event.user_id} GROUP {event.group_id if not isinstance(event, PrivateMessageEvent) else ''} "
f"问题:{msg}\n回答:{result}"
)
if result:
await ai.finish(Message(result))
else:
await ai.finish(no_result())
@ai.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
# if await GroupRemind.get_status(event.group_id, 'ai'):
msg = get_message_text(event.json())
imgs = get_message_imgs(event.json())
# 打招呼
if not msg and not imgs:
await ai.finish(hello())
img = imgs[0] if imgs else ''
nickname = await GroupInfoUser.get_group_member_nickname(event.user_id, event.group_id)
if not nickname:
try:
nickname = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
except AttributeError:
nickname = "你"
result = await get_qqbot_chat_result(msg, img, event.user_id, nickname)
logger.info(f"问题:{msg}\n回答:{result}")
if result:
await ai.finish(Message(result))
else:
await ai.finish(no_result())
+123 -123
View File
@@ -1,12 +1,13 @@
from configs.config import TL_KEY, ALAPI_TOKEN
from configs.config import TL_KEY, ALAPI_TOKEN, ALAPI_AI_CHECK
from configs.path_config import IMAGE_PATH, DATA_PATH
from aiohttp.client import ClientSession
from services.log import logger
from utils.message_builder import image, face
from utils.utils import get_bot
import re
import aiohttp
import random
import os
from configs.path_config import IMAGE_PATH, DATA_PATH
from services.log import logger
from utils.init_result import image, face
from utils.utils import get_bot
import re
try:
import ujson as json
@@ -19,11 +20,11 @@ check_url = "https://v2.alapi.cn/api/censor/text"
index = 0
anime_data = json.load(open(DATA_PATH + 'anime.json', 'r', encoding='utf8'))
anime_data = json.load(open(DATA_PATH + "anime.json", "r", encoding="utf8"))
# 图灵AI
async def get_qqbot_chat_result(text: str, img_url: str, user_id: int, user_name: str) -> str:
async def get_chat_result(text: str, img_url: str, user_id: int, nickname: str) -> str:
global index
if index == 5:
index = 0
@@ -31,112 +32,110 @@ async def get_qqbot_chat_result(text: str, img_url: str, user_id: int, user_name
keys = anime_data.keys()
for key in keys:
if text.find(key) != -1:
return random.choice(anime_data[key]).replace('你', user_name)
return random.choice(anime_data[key]).replace("你", nickname)
async with aiohttp.ClientSession() as sess:
rst = await tu_ling(text, img_url, user_id, sess)
if not rst:
rst = await xie_ai(text, sess)
if not rst:
return no_result()
if nickname:
if len(nickname) < 5:
if random.random() < 0.5:
nickname = "~".join(nickname) + "~"
if random.random() < 0.2:
if nickname.find("大人") == -1:
nickname += "大~人~"
rst = rst.replace("小主人", nickname).replace("小朋友", nickname)
return rst
# 图灵接口
async def tu_ling(text: str, img_url: str, user_id: int, sess: ClientSession):
global index
try:
if text:
req = {
"perception":
{
"inputText":
{
"text": text
},
"selfInfo":
{
"location":
{
"city": "陨石坑",
"province": "火星",
"street": "第5坑位"
}
}
"perception": {
"inputText": {"text": text},
"selfInfo": {
"location": {"city": "陨石坑", "province": "火星", "street": "第5坑位"}
},
"userInfo":
{
"apiKey": TL_KEY[index],
"userId": str(user_id)
}
},
"userInfo": {"apiKey": TL_KEY[index], "userId": str(user_id)},
}
elif img_url:
req = {
"reqType": 1,
"perception":
{
"inputImage": {
"url": img_url
},
"selfInfo":
{
"location":
{
"city": "陨石坑",
"province": "火星",
"street": "第5坑位"
}
}
"perception": {
"inputImage": {"url": img_url},
"selfInfo": {
"location": {"city": "陨石坑", "province": "火星", "street": "第5坑位"}
},
"userInfo":
{
"apiKey": TL_KEY[index],
"userId": str(user_id)
}
},
"userInfo": {"apiKey": TL_KEY[index], "userId": str(user_id)},
}
except IndexError:
index = 0
return no_result()
async with aiohttp.ClientSession() as sess:
async with sess.post(url, json=req) as response:
if response.status != 200:
return ''
resp_payload = json.loads(await response.text())
if resp_payload['intent']:
if int(resp_payload['intent']['code']) in [4003]:
index += 1
# 该AI很屑!!!!!!!!!!!!
async with sess.get(f'http://api.qingyunke.com/api.php?key=free&appid=0&msg={text}') as res:
data = json.loads(await res.text())
if data['result'] == 0:
content = data['content']
if content.find('菲菲') != -1:
content = content.replace('菲菲', list(get_bot().config.nickname)[0])
if content.find('公众号') != -1:
content = ''
if content.find('{br}') != -1:
content = content.replace('{br}', '\n')
if content.find('提示') != -1:
content = content[:content.find('提示')]
while True:
r = re.search('{face:(.*)}', content)
if r:
id_ = r.group(1)
content = content.replace('{' + f'face:{id_}' + '}', str(face(id_)))
else:
break
return content
if resp_payload['results']:
for result in resp_payload['results']:
if result['resultType'] == 'text':
text = result['values']['text']
if user_name:
text = text.replace('小朋友', user_name)
if len(user_name) < 5:
if random.random() < 0.5:
user_name = "~".join(user_name) + '~'
if random.random() < 0.2:
if user_name.find('大人') == -1:
user_name += '大~人~'
text = text.replace('小主人', user_name)
return text
return ""
text = ""
async with sess.post(url, json=req) as response:
if response.status != 200:
return no_result()
resp_payload = json.loads(await response.text())
if int(resp_payload["intent"]["code"]) in [4003]:
return ""
if resp_payload["results"]:
for result in resp_payload["results"]:
if result["resultType"] == "text":
text = result["values"]["text"]
if "请求次数超过" in text:
text = ""
return text
# 屑 AI
async def xie_ai(text: str, sess: ClientSession):
async with sess.get(
f"http://api.qingyunke.com/api.php?key=free&appid=0&msg={text}"
) as res:
content = ""
data = json.loads(await res.text())
if data["result"] == 0:
content = data["content"]
if "菲菲" in content:
content = content.replace("菲菲", "真寻")
if "公众号" in content:
content = ""
if "{br}" in content:
content = content.replace("{br}", "\n")
if "提示" in content:
content = content[: content.find("提示")]
if "淘宝" 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 ALAPI_AI_CHECK else await check_text(content, sess)
# 打招呼内容
def hello() -> str:
result = random.choice((
"哦豁?!",
"你好!Ov<",
f"库库库,呼唤{list(get_bot().config.nickname)[0]}做什么呢",
"我在呢!",
"呼呼,叫俺干嘛"
))
result = random.choice(
(
"哦豁?!",
"你好!Ov<",
f"库库库,呼唤{list(get_bot().config.nickname)[0]}做什么呢",
"我在呢!",
"呼呼,叫俺干嘛",
)
)
img = random.choice(os.listdir(IMAGE_PATH + "zai/"))
if img[-4:] == ".gif":
result += image(img, "zai")
@@ -145,32 +144,33 @@ def hello() -> str:
return result
# 没有回答时回复内容
def no_result() -> str:
return random.choice([
'你在说啥子?',
f'纯洁的{list(get_bot().config.nickname)[0]}没听懂',
'下次再告诉你(下次一定)',
'你觉得我听懂了吗?嗯?',
'我!不!知!道!'
]) + image(
random.choice(os.listdir(IMAGE_PATH + "noresult/")
), "noresult")
return (
random.choice(
[
"你在说啥子?",
f"纯洁的{list(get_bot().config.nickname)[0]}没听懂",
"下次再告诉你(下次一定)",
"你觉得我听懂了吗?嗯?",
"我!不!知!道!",
]
)
+ image(random.choice(os.listdir(IMAGE_PATH + "noresult/")), "noresult")
)
async def check_text(text: str):
# 检测屑AI回复的文本是否是 *话
async def check_text(text: str, sess: ClientSession) -> str:
if not ALAPI_TOKEN:
return text
params = {
'token': ALAPI_TOKEN,
'text': text
}
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=2, params=params) as response:
data = await response.json()
if data['code'] == 200:
if data['conclusion_type'] == 2:
return no_result()
except Exception as e:
logger.error(f'检测违规文本错误...e:{e}')
return text
params = {"token": ALAPI_TOKEN, "text": text}
try:
async with sess.get(check_url, timeout=2, params=params) as response:
data = await response.json()
if data["code"] == 200:
if data["conclusion_type"] == 2:
return ''
except Exception as e:
logger.error(f"检测违规文本错误...e:{e}")
return text
+1 -1
View File
@@ -2,7 +2,7 @@ from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, MessageEvent, Message
from nonebot.typing import T_State
from configs.config import ALAPI_TOKEN
from utils.init_result import image
from utils.message_builder import image
from utils.utils import get_message_text
from .util import get_data
from services.log import logger
+30 -17
View File
@@ -5,23 +5,26 @@ from datetime import datetime
from configs.config import AUTO_ADD_FRIEND
from nonebot.adapters.cqhttp.exception import ActionFailed
__plugin_name__ = '好友群聊处理请求 [Hidden]'
__plugin_name__ = "好友群聊处理请求 [Hidden]"
friend_req = on_request(priority=5)
@friend_req.handle()
async def _(bot: Bot, event: FriendRequestEvent, state: dict):
user = await bot.get_stranger_info(user_id=event.user_id)
nickname = user["nickname"]
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"*****一份好友申请*****\n"
f"昵称:{nickname}({event.user_id})\n"
f"自动同意:{'√' if AUTO_ADD_FRIEND else '×'}\n"
f"日期:{str(datetime.now()).split('.')[0]}\n"
f"备注:{event.comment}",
)
if AUTO_ADD_FRIEND:
nickname = ''
for user in await bot.get_friend_list():
if user['user_id'] == event.user_id:
nickname = user['nickname']
await FriendUser.add_friend_info(user['user_id'], user['nickname'])
break
await bot.send_private_msg(user_id=int(list(bot.config.superusers)[0]), message=f"{nickname}({event.user_id})"
f" 添加小真寻好友(已自动同意)")
await bot.set_friend_add_request(flag=event.flag, approve=True)
await FriendUser.add_friend_info(user["user_id"], user["nickname"])
group_req = on_request(priority=5, block=True)
@@ -29,16 +32,26 @@ group_req = on_request(priority=5, block=True)
@group_req.handle()
async def _(bot: Bot, event: GroupRequestEvent, state: dict):
if event.sub_type == 'invite':
nickname = await FriendUser.get_user_name(event.user_id)
if event.sub_type == "invite":
if str(event.user_id) in bot.config.superusers:
try:
await bot.set_group_add_request(flag=event.flag, sub_type='invite', approve=True)
await bot.set_group_add_request(
flag=event.flag, sub_type="invite", approve=True
)
except ActionFailed:
pass
else:
await bot.send_private_msg(user_id=int(list(bot.config.superusers)[0]),
message=f"报告..\n{nickname}({event.user_id})"
f" 希望邀请我加入 {event.group_id}\n邀请日期:{str(datetime.now()).split('.')[0]}")
await bot.send_private_msg(user_id=event.user_id,
message="想要邀请我偷偷入群嘛~~已经提醒管理员了\n等待管理员处理吧~")
nickname = await FriendUser.get_user_name(event.user_id)
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"*****一份入群申请*****\n"
f"申请人:{nickname}({event.user_id})\n"
f"群聊:{event.group_id}\n"
f"邀请日期:{str(datetime.now()).split('.')[0]}",
)
await bot.send_private_msg(
user_id=event.user_id,
message="想要邀请我偷偷入群嘛~已经提醒真寻的管理员大人了\n"
"请确保已经群主或群管理沟通过!\n"
"等待管理员处理吧!",
)
+58 -39
View File
@@ -2,82 +2,101 @@ from nonebot import on_command
from models.ban_user import BanUser
from models.level_user import LevelUser
from nonebot.typing import T_State
from nonebot.adapters import Bot
from nonebot.adapters.cqhttp import Bot
from nonebot.adapters.cqhttp import GroupMessageEvent
from nonebot.adapters.cqhttp.permission import GROUP
from utils.utils import get_message_at, get_message_text, is_number
from services.log import logger
from models.group_member_info import GroupInfoUser
__plugin_name__ = 'Ban/unBan'
__plugin_usage__ = '用法:\n' \
'(不是禁言!是针对真寻是否处理封禁用户消息)\n' \
'封禁/解封用户 [小时] [分钟]\n' \
'示例:.ban @djdsk\n' \
'示例:.ban @djdsk 0 30\n' \
'示例:.ban @sdasf 4\n' \
'示例:.unban @sdasf'
__plugin_name__ = "Ban/unBan"
__plugin_usage__ = (
"用法:\n"
"(不是禁言!是针对真寻是否处理封禁用户消息)\n"
"封禁/解封用户 [小时] [分钟]\n"
"示例:.ban @djdsk\n"
"示例:.ban @djdsk 0 30\n"
"示例:.ban @sdasf 4\n"
"示例:.unban @sdasf"
)
ban = on_command(".ban", aliases={'.unban', '/ban', '/unban'}, priority=5, permission=GROUP, block=True)
ban = on_command(
".ban",
aliases={".unban", "/ban", "/unban"},
priority=5,
permission=GROUP,
block=True,
)
@ban.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
# try:
result = ''
qq = int(get_message_at(event.json())[0])
result = ""
qq = get_message_at(event.json())[0]
if qq:
try:
user_name = (await GroupInfoUser.select_member_info(qq, event.group_id)).user_name
except AttributeError:
user_name = '用户'
user_name = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
user_name = user_name['card'] if user_name['card'] else user_name['nickname']
msg = get_message_text(event.json())
if msg:
msg = msg.split(" ")
msg = msg.split()
if len(msg) == 2:
if not is_number(msg[0].strip()) or not is_number(msg[1].strip()):
await ban.finish('参数必须是数字!', at_sender=True)
await ban.finish("参数必须是数字!", at_sender=True)
time = int(msg[0]) * 60 * 60 + int(msg[1]) * 60
else:
if not is_number(msg[0].strip()):
await ban.finish('参数必须是数字!', at_sender=True)
await ban.finish("参数必须是数字!", at_sender=True)
time = int(msg[0]) * 60 * 60
else:
time = -1
if state["_prefix"]["raw_command"] in [".ban", '/ban']:
if await LevelUser.get_user_level(event.user_id, event.group_id) <= await \
LevelUser.get_user_level(qq, event.group_id) and str(event.user_id) not in bot.config.superusers:
await ban.finish(f"您的权限等级比对方低或相等, {list(bot.config.nickname)[0]}不能为您使用此功能!", at_sender=True)
if await BanUser.ban(qq, await LevelUser.get_user_level(event.user_id, event.group_id), time):
logger.info(f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 封禁 时长 {time/60} 分钟")
if state["_prefix"]["raw_command"] in [".ban", "/ban"]:
if (
await LevelUser.get_user_level(event.user_id, event.group_id)
<= await LevelUser.get_user_level(qq, event.group_id)
and str(event.user_id) not in bot.config.superusers
):
await ban.finish(
f"您的权限等级比对方低或相等, {list(bot.config.nickname)[0]}不能为您使用此功能!",
at_sender=True,
)
if await BanUser.ban(
qq, await LevelUser.get_user_level(event.user_id, event.group_id), time
):
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 封禁 时长 {time/60} 分钟"
)
result = f"已经将 {user_name} 加入{list(bot.config.nickname)[0]}的黑名单了!"
if time != -1:
result += f"将在 {time/60} 分钟后解封"
else:
time = await BanUser.check_ban_time(qq)
if is_number(time):
time = abs(time)
time = abs(int(time))
if time < 60:
time = str(int(time)) + ' 秒'
time = str(time) + " 秒"
else:
time = str(int(time / 60)) + ' 分钟'
time = str(int(time / 60)) + " 分钟"
else:
time += ' 分钟'
time += " 分钟"
result = f"{user_name} 已在黑名单!预计 {time}后解封"
else:
if await BanUser.check_ban_level(qq, await LevelUser.get_user_level(event.user_id, event.group_id)) and\
str(event.user_id) not in bot.config.superusers:
await ban.finish(f"ban掉 {user_name} 的管理员权限比您高,无法进行unban", at_sender=True)
if (
await BanUser.check_ban_level(
qq, await LevelUser.get_user_level(event.user_id, event.group_id)
)
and str(event.user_id) not in bot.config.superusers
):
await ban.finish(
f"ban掉 {user_name} 的管理员权限比您高,无法进行unban", at_sender=True
)
if await BanUser.unban(qq):
logger.info(f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 解禁")
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 解禁"
)
result = f"已经把 {user_name} 从黑名单中删除了!"
else:
result = f"{user_name} 不在黑名单!"
else:
await ban.finish('艾特人了吗??', at_sender=True)
# except Exception as e:
# result = 'ban/unban执行出错,确定艾特人了吗?'
# logger.error(f'ban/unban执行出错 e:{e}')
await ban.finish("艾特人了吗??", at_sender=True)
await ban.finish(result, at_sender=True)
+1 -1
View File
@@ -6,7 +6,7 @@ import asyncio
from utils.utils import get_message_text, get_message_imgs
from services.log import logger
from models.group_remind import GroupRemind
from utils.init_result import image
from utils.message_builder import image
__plugin_name__ = "广播 [Hidden]"
+32 -33
View File
@@ -10,7 +10,7 @@ from utils.utils import UserExistLimiter
from asyncio.exceptions import TimeoutError
from aiohttp.client_exceptions import ServerDisconnectedError
__plugin_name__ = '磁力搜索'
__plugin_name__ = "磁力搜索"
__plugin_usage__ = r"""
* 请各位使用后不要转发 *
* 拒绝反冲斗士! *
@@ -22,67 +22,66 @@ bt 钢铁侠 3
_ulmt = UserExistLimiter()
bt = on_command('bt', permission=PRIVATE, priority=5, block=True)
bt = on_command("bt", permission=PRIVATE, priority=5, block=True)
@bt.args_parser
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
if str(event.get_message()) in ['取消', '算了']:
if str(event.get_message()) in ["取消", "算了"]:
await bt.finish("已取消操作..", at_sender=True)
msg = get_message_text(event.json())
if not msg:
await bt.reject('你想搜索什么呢?', at_sender=True)
state['keyword'] = msg
state['page'] = '1'
await bt.reject("你想搜索什么呢?", at_sender=True)
state["keyword"] = msg
state["page"] = "1"
@bt.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
if _ulmt.check(event.user_id):
await bt.finish('您有bt任务正在进行,请等待结束.', at_sender=True)
await bt.finish("您有bt任务正在进行,请等待结束.", at_sender=True)
mp = get_message_text(event.json())
if not mp:
return
mp = mp.split(' ')
mp = mp.split()
if len(mp) == 2:
state['keyword'] = mp[0]
state['page'] = mp[1]
state["keyword"] = mp[0]
state["page"] = mp[1]
else:
state['keyword'] = mp[0]
state['page'] = '1'
state["keyword"] = mp[0]
state["page"] = "1"
@bt.got('keyword', prompt='虚空磁力?查什么GKD')
@bt.got("keyword", prompt="虚空磁力?查什么GKD")
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
_ulmt.set_True(event.user_id)
keyword = state['keyword']
page = state['page']
await bt.send('开始搜索....', at_sender=True)
keyword = state["keyword"]
page = state["page"]
await bt.send("开始搜索....", at_sender=True)
send_flag = False
try:
async for title, itype, create_time, file_size, link in get_bt_info(keyword, page):
await bt.send(f'标题:{title}\n'
f'类型:{itype}\n'
f'创建时间:{create_time}\n'
f'文件大小:{file_size}\n'
f'种子:{link}')
async for title, itype, create_time, file_size, link in get_bt_info(
keyword, page
):
await bt.send(
f"标题:{title}\n"
f"类型:{itype}\n"
f"创建时间:{create_time}\n"
f"文件大小:{file_size}\n"
f"种子:{link}"
)
send_flag = True
except TimeoutError:
_ulmt.set_False(event.user_id)
await bt.finish(f'搜索 {keyword} 超时...')
await bt.finish(f"搜索 {keyword} 超时...")
except ServerDisconnectedError:
_ulmt.set_False(event.user_id)
await bt.finish(f'搜索 {keyword} 连接失败')
await bt.finish(f"搜索 {keyword} 连接失败")
except Exception as e:
_ulmt.set_False(event.user_id)
await bt.finish(f'bt 其他未知错误..')
logger.error(f'bt 错误 e:{e}')
await bt.finish(f"bt 其他未知错误..")
logger.error(f"bt 错误 e:{e}")
if not send_flag:
await bt.send(f'{keyword} 未搜索到...')
logger.info(f'USER {event.user_id} BT搜索 {keyword} 第 {page} 页')
await bt.send(f"{keyword} 未搜索到...")
logger.info(f"USER {event.user_id} BT搜索 {keyword} 第 {page} 页")
_ulmt.set_False(event.user_id)
+26 -19
View File
@@ -4,38 +4,45 @@ from configs.config import MAXINFO_BT
from bs4 import BeautifulSoup
from utils.utils import get_local_proxy
import platform
if platform.system() == 'Windows':
if platform.system() == "Windows":
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
url = 'http://www.eclzz.world'
url = "http://www.eclzz.world"
async def get_bt_info(keyword: str, page: str):
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(f"{url}/s/{keyword}_rel_{page}.html", proxy=get_local_proxy(), timeout=5) as response:
async with session.get(
f"{url}/s/{keyword}_rel_{page}.html", proxy=get_local_proxy(), timeout=5
) as response:
text = await response.text()
if text.find('大约0条结果') != -1:
if text.find("大约0条结果") != -1:
return
soup = BeautifulSoup(text, 'lxml')
item_lst = soup.find_all('div', {'class': 'search-item'})
soup = BeautifulSoup(text, "lxml")
item_lst = soup.find_all("div", {"class": "search-item"})
for item in item_lst[:MAXINFO_BT]:
divs = item.find_all('div')
title = str(divs[0].find('a').text).replace('<em>', '').replace('</em>', '').strip()
spans = divs[2].find_all('span')
divs = item.find_all("div")
title = (
str(divs[0].find("a").text)
.replace("<em>", "")
.replace("</em>", "")
.strip()
)
spans = divs[2].find_all("span")
itype = spans[0].text
create_time = spans[1].find('b').text
file_size = spans[2].find('b').text
link = await get_download_link(divs[0].find('a')['href'], session)
create_time = spans[1].find("b").text
file_size = spans[2].find("b").text
link = await get_download_link(divs[0].find("a")["href"], session)
yield title, itype, create_time, file_size, link
async def get_download_link(_url: str, session) -> str:
async with session.get(f"{url}{_url}", proxy=get_local_proxy(), timeout=30) as response:
soup = BeautifulSoup(await response.text(), 'lxml')
return soup.find('a', {'id': 'down-url'})['href']
async with session.get(
f"{url}{_url}", proxy=get_local_proxy(), timeout=30
) as response:
soup = BeautifulSoup(await response.text(), "lxml")
return soup.find("a", {"id": "down-url"})["href"]
+5 -4
View File
@@ -1,4 +1,3 @@
from nonebot import on_command
from .data_source import Check
from nonebot.adapters.cqhttp import Bot, Event
@@ -7,14 +6,16 @@ from nonebot.rule import to_me
from nonebot.permission import SUPERUSER
__plugin_name__ = '自我检查 [Hidden]'
__plugin_name__ = "自我检查 [Hidden]"
__plugin_usage__ = '用法:自检'
__plugin_usage__ = "用法:自检"
check = Check()
check_ = on_command('自检', aliases={'check'}, rule=to_me(), permission=SUPERUSER, block=True, priority=1)
check_ = on_command(
"自检", aliases={"check"}, rule=to_me(), permission=SUPERUSER, block=True, priority=1
)
@check_.handle()
+20 -15
View File
@@ -33,35 +33,40 @@ class Check:
async def check_network(self):
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
try:
async with session.get('https://www.baidu.com/', proxy=get_local_proxy(), timeout=3) as response:
async with session.get(
"https://www.baidu.com/", proxy=get_local_proxy(), timeout=3
) as response:
pass
except (TimeoutError, ClientConnectorError) as e:
logger.warning(f'访问BaiDu失败... e: {e}')
logger.warning(f"访问BaiDu失败... e: {e}")
self.baidu = 404
try:
async with session.get('https://www.google.com/', proxy=get_local_proxy(), timeout=3) as response:
async with session.get(
"https://www.google.com/", proxy=get_local_proxy(), timeout=3
) as response:
pass
except (TimeoutError, ClientConnectorError) as e:
logger.warning(f'访问Google失败... e: {e}')
logger.warning(f"访问Google失败... e: {e}")
self.google = 404
def check_user(self):
rst = ''
rst = ""
for user in psutil.users():
rst += f'[{user.name}] {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.started))}\n'
self.user = rst[:-1]
async def show(self):
await self.check_all()
rst = f'[Time] {str(datetime.now()).split(".")[0]}\n' \
f'-----System-----\n' \
f'[CPU] {self.cpu}%\n' \
f'[Memory] {self.memory}%\n' \
f'[Disk] {self.disk}%\n' \
f'-----Network-----\n' \
f'[BaiDu] {self.baidu}\n' \
f'[Google] {self.google}\n'
rst = (
f'[Time] {str(datetime.now()).split(".")[0]}\n'
f"-----System-----\n"
f"[CPU] {self.cpu}%\n"
f"[Memory] {self.memory}%\n"
f"[Disk] {self.disk}%\n"
f"-----Network-----\n"
f"[BaiDu] {self.baidu}\n"
f"[Google] {self.google}\n"
)
if self.user:
rst += '-----User-----\n' + self.user
rst += "-----User-----\n" + self.user
return rst
+11 -23
View File
@@ -1,39 +1,27 @@
from nonebot import on_command
from utils.utils import get_message_text
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from services.log import logger
from utils.init_result import image
from utils.message_builder import image
import requests
__plugin_name__ = 'coser'
__plugin_name__ = "coser"
__plugin_usage__ = '用法:发送‘coser’'
__plugin_usage__ = "用法:发送‘coser’"
coser = on_command('cos', aliases={'coser', '括丝', 'COS', 'Cos', 'cOS', 'coS'}, priority=5, block=True)
coser = on_command(
"cos", aliases={"coser", "括丝", "COS", "Cos", "cOS", "coS"}, priority=5, block=True
)
url_2 = 'http://api.rosysun.cn/cos'
url_2 = "http://api.rosysun.cn/cos"
@coser.handle()
async def _(bot: Bot, event: Event, state: T_State):
async def _(bot: Bot, event: MessageEvent, state: T_State):
img_url = requests.get(url_2).text
await coser.send(image(img_url))
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'}) 发送COSER")
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 发送COSER"
)
+27 -23
View File
@@ -1,54 +1,56 @@
from configs.path_config import IMAGE_PATH, TEMP_PATH
import os
from utils.init_result import image
from utils.message_builder import image
from services.log import logger
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from configs.config import IMAGE_DIR_LIST
from utils.utils import is_number, cn2py
import os
__plugin_name__ = '删除图片'
__plugin_usage__ = '删除图片帮助:\n\t' \
'1.查看列表 --> 指令: 删除图片 列表/目录\n\t' \
'2.删除图片 图库 id, 即在相应目录下删除图片\n\t\t示例: 删除图片 色图 1 '
__plugin_name__ = "删除图片"
__plugin_usage__ = (
"删除图片帮助:\n\t"
"1.查看列表 --> 指令: 删除图片 列表/目录\n\t"
"2.删除图片 图库 id, 即在相应目录下删除图片\n\t\t示例: 删除图片 色图 1 "
)
delete_img = on_command("删除图片", priority=5, rule=to_me(), block=True)
@delete_img.args_parser
async def parse(bot: Bot, event: Event, state: T_State):
if str(event.get_message()) in ['取消', '算了']:
async def parse(bot: Bot, event: MessageEvent, state: T_State):
if str(event.get_message()) in ["取消", "算了"]:
await delete_img.finish("已取消操作..", at_sender=True)
if state["_current_key"] in ['path']:
if state["_current_key"] in ["path"]:
if str(event.get_message()) not in IMAGE_DIR_LIST:
await delete_img.reject("此目录不正确,请重新输入目录!")
state[state["_current_key"]] = str(event.get_message())
if state["_current_key"] == 'id':
if state["_current_key"] == "id":
if not is_number(str(event.get_message())):
await delete_img.reject("id不正确!请重新输入数字...")
state[state["_current_key"]] = str(event.get_message())
@delete_img.handle()
async def _(bot: Bot, event: Event, state: T_State):
async def _(bot: Bot, event: MessageEvent, state: T_State):
raw_arg = str(event.get_message()).strip()
if raw_arg:
args = raw_arg.split(" ")
if args[0] in ['帮助']:
if args[0] in ["帮助"]:
await delete_img.finish(__plugin_usage__)
if len(args) >= 2 and args[0] in IMAGE_DIR_LIST and is_number(args[1]):
state['path'] = args[0]
state['id'] = args[1]
state["path"] = args[0]
state["id"] = args[1]
@delete_img.got("path", prompt="请输入要删除的目标图库?")
@delete_img.got("id", prompt="请输入要删除的图片id?")
async def arg_handle(bot: Bot, event: Event, state: T_State):
path = cn2py(state['path'])
img_id = state['id']
async def arg_handle(bot: Bot, event: MessageEvent, state: T_State):
path = cn2py(state["path"])
img_id = state["id"]
path = IMAGE_PATH + path
max_id = len(os.listdir(path)) - 1
if int(img_id) > max_id or int(img_id) < 0:
@@ -71,9 +73,11 @@ async def arg_handle(bot: Bot, event: Event, state: T_State):
except FileExistsError:
logger.error(f"{path}{max_id}.jpg 替换 {path}{img_id}.jpg 失败 e:{e}")
logger.info(f"{path}{max_id}.jpg 替换 {path}{img_id}.jpg 成功")
logger.info(f"USER {event.user_id} GROUP {event.group_id if event.message_type != 'private' else 'private'}"
f" -> id: {img_id} 删除成功")
await delete_img.finish(f"id: {img_id} 删除成功" + image("delete.jpg", TEMP_PATH), at_sender=True)
logger.info(
f"USER {event.user_id} GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}"
f" -> id: {img_id} 删除成功"
)
await delete_img.finish(
f"id: {img_id} 删除成功" + image("delete.jpg", TEMP_PATH), at_sender=True
)
await delete_img.finish(f"id: {img_id} 删除失败!")
+66 -34
View File
@@ -1,22 +1,22 @@
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent, Message
from nonebot.adapters.cqhttp import Bot, MessageEvent, Message, GroupMessageEvent
from nonebot.permission import SUPERUSER
from utils.utils import get_message_text, is_number, get_message_imgs
from utils.init_result import image
from utils.message_builder import image
from services.log import logger
from utils.init_result import at
from utils.message_builder import at
__plugin_name__ = '联系管理员'
__plugin_usage__ = '用法:滴滴滴- [消息]'
__plugin_name__ = "联系管理员"
__plugin_usage__ = "用法:滴滴滴- [消息]"
dialogue_data = {}
dialogue = on_command("[滴滴滴]", aliases={"滴滴滴-"}, priority=1, block=True)
reply = on_command("/t", priority=1, permission=SUPERUSER, block=True)
reply = on_command("/t", priority=1, permission=SUPERUSER, block=True)
@dialogue.handle()
@@ -24,21 +24,41 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
uid = event.user_id
coffee = int(list(bot.config.superusers)[0])
text = get_message_text(event.json())
img_msg = ''
img_msg = ""
for img in get_message_imgs(event.json()):
img_msg += image(img)
if not text or text in ['帮助']:
if not text or text in ["帮助"]:
await dialogue.send("请发送[滴滴滴]+您要说的内容~", at_sender=True)
else:
if event.get_event_name() == "message.private.friend":
group_id = 0
else:
group_id = 0
group_name = "None"
nickname = event.sender.nickname
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
await bot.send_private_msg(user_id=coffee, message=Message(f'Q{uid}@群{group_id}\n{text} {img_msg}'))
await dialogue.send(Message(f'您的话已发送至管理员!\n======\n{text}{img_msg}'), at_sender=True)
group_name = (await bot.get_group_info(group_id=event.group_id))[
"group_name"
]
nickname = event.sender.card if event.sender.card else event.sender.nickname
await bot.send_private_msg(
user_id=coffee,
message=Message(
f"*****一份交流报告*****\n"
f"昵称:{nickname}({uid})\n"
f"群聊:{group_name}({group_id})\n"
f"消息:{text} {img_msg}"
),
)
await dialogue.send(
Message(f"您的话已发送至管理员!\n======\n{text}{img_msg}"), at_sender=True
)
nickname = event.sender.nickname if event.sender.nickname else event.sender.card
dialogue_data[len(dialogue_data)] = {'nickname': nickname, 'user_id': event.user_id,
'group_id': group_id, 'msg': text}
dialogue_data[len(dialogue_data)] = {
"nickname": nickname,
"user_id": event.user_id,
"group_id": group_id,
"group_name": group_name,
"msg": f'{text} {img_msg}',
}
# print(dialogue_data)
logger.info(f"Q{uid}@群{group_id} 联系管理员:{coffee} text:{text}")
@@ -46,19 +66,26 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
@reply.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if msg in ['帮助']:
await reply.finish(f'/t [qq] [group] [text] -> 回复指定用户\n'
f'/t [qq] [text] -> 私聊用户\n'
f'/t -1 [group] -> 在某群发送消息\n'
f'/t [id] [text] -> 回复指定id的对话')
if msg in ["帮助"]:
await reply.finish(
f"/t [qq] [group] [text] -> 回复指定用户\n"
f"/t [qq] [text] -> 私聊用户\n"
f"/t -1 [group] -> 在某群发送消息\n"
f"/t [id] [text] -> 回复指定id的对话"
)
if not msg:
result = ''
result = "*****待回复消息总览*****\n"
for key in dialogue_data.keys():
result += f'{key}:{dialogue_data[key]["nickname"]}({dialogue_data[key]["user_id"]})' \
f' @群 {dialogue_data[key]["group_id"]}\n-------\n{dialogue_data[key]["msg"]}\n-------\n'
await reply.finish(result[:-1])
msg = msg.split(" ")
text = ''
result += (
f'id:{key}\n'
f'\t昵称:{dialogue_data[key]["nickname"]}({dialogue_data[key]["user_id"]})\n'
f'\t群群:{dialogue_data[key]["group_name"]}({dialogue_data[key]["group_id"]})\n'
f'\t消息:{dialogue_data[key]["msg"]}'
f'\n--------------------\n'
)
await reply.finish(Message(result[:-1]))
msg = msg.split()
text = ""
group_id = 0
user_id = -1
if is_number(msg[0]):
@@ -76,7 +103,7 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
group_id = int(msg[1])
text = msg[2]
else:
await reply.finish('群号错误...', at_sender=True)
await reply.finish("群号错误...", at_sender=True)
else:
user_id = int(msg[0])
if is_number(msg[1]) and len(msg[1]) > 5:
@@ -86,19 +113,24 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
group_id = 0
text = msg[1]
else:
await reply.finish('请输入数字..', at_sender=True)
await reply.finish("第一参数,请输入数字.....", at_sender=True)
for img in get_message_imgs(event.json()):
text += image(img)
if group_id:
if user_id:
await bot.send_group_msg(group_id=group_id, message=at(user_id) + "\n管理员回复\n=======\n" + text)
await reply.finish("发送成功", at_sender=True)
await bot.send_group_msg(
group_id=group_id, message=at(user_id) + "\n管理员回复\n=======\n" + text
)
else:
await bot.send_group_msg(group_id=group_id, message=text)
await reply.finish("发送成功", at_sender=True)
await reply.finish("消息发送成功...", at_sender=True)
else:
if user_id in [qq['user_id'] for qq in await bot.get_friend_list()]:
await bot.send_private_msg(user_id=user_id, message="管理员回复\n=======\n" + text)
if user_id in [qq["user_id"] for qq in await bot.get_friend_list()]:
await bot.send_private_msg(
user_id=user_id, message="管理员回复\n=======\n" + text
)
await reply.finish("发送成功", at_sender=True)
else:
await reply.send(f"对象不是{list(bot.config.nickname)[0]}的好友...", at_sender=True)
await reply.send(
f"对象不是{list(bot.config.nickname)[0]}的好友...", at_sender=True
)
+2 -2
View File
@@ -10,7 +10,7 @@ from .config import path_dict
from configs.path_config import IMAGE_PATH
import nonebot
import pypinyin
from utils.img_utils import CreateImg
from utils.image_utils import CreateImg
import platform
from services.log import logger
import random
@@ -321,5 +321,5 @@ def remove_prohibited_str(name: str):
tmp += i
name = tmp
else:
name = name.replace('/', '')
name = name.replace('/', '\\')
return name
+14 -29
View File
@@ -7,9 +7,9 @@ from .data_source import get_epic_game
from models.group_remind import GroupRemind
from nonebot.adapters.cqhttp.exception import ActionFailed
__plugin_name__ = 'epic免费游戏提醒'
__plugin_name__ = "epic免费游戏提醒"
__plugin_usage__ = '用法:发送’epic‘'
__plugin_usage__ = "用法:发送’epic‘"
epic = on_command("epic", priority=5, block=True)
@@ -17,44 +17,29 @@ epic = on_command("epic", priority=5, block=True)
@epic.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
# try:
try:
result = await get_epic_game()
except:
result = '网络出错了!'
result, code = await get_epic_game()
await epic.send(result)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 获取epic免费游戏")
# except Exception as e:
# logger.error(f'epic 出错 e:{e}')
# await epic.finish('网络好像炸了,再试一次?', at_sender=True)
f" 获取epic免费游戏"
)
# epic免费游戏
@scheduler.scheduled_job(
'cron',
"cron",
hour=12,
minute=1,
)
async def _():
# try:
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
gl = [g["group_id"] for g in gl]
for g in gl:
if await GroupRemind.get_status(g, 'epic'):
result = await get_epic_game()
if result == '今天没有游戏可以白嫖了!':
return
try:
await bot.send_group_msg(group_id=g,
message=result)
except ActionFailed:
logger.error(f'{g}群 epic免费游戏推送错误')
# except Exception as e:
# logger.error(f'epic免费游戏推送错误 e:{e}')
if await GroupRemind.get_status(g, "epic"):
result, code = await get_epic_game()
if code == 200:
try:
await bot.send_group_msg(group_id=g, message=result)
except ActionFailed:
logger.error(f"{g}群 epic免费游戏推送错误")
+43 -32
View File
@@ -3,43 +3,54 @@ import aiofiles
from utils.utils import get_local_proxy
import feedparser
import platform
from utils.init_result import image
from utils.message_builder import image
from configs.path_config import IMAGE_PATH
from utils.user_agent import get_user_agent
if platform.system() == 'Windows':
from asyncio.exceptions import TimeoutError
from configs.config import RSSHUBAPP
if platform.system() == "Windows":
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
url = 'https://rsshub.app/epicgames/freegames'
async def get_epic_game() -> str:
result = '今天没有游戏可以白嫖了!'
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, proxy=get_local_proxy(), timeout=7) as response:
data = feedparser.parse(await response.text())['entries']
if len(data) == 0:
return result
index = 0
for item in data:
title = item['title']
img_url = item['summary'][item['summary'].find('src="')+5: item['summary'].rfind('"')]
async with session.get(img_url, proxy=get_local_proxy(), timeout=7) as res:
async with aiofiles.open(IMAGE_PATH + f'temp/epic_{index}.jpg', 'wb') as f:
await f.write(await res.read())
link = item['link']
result += image(f'epic_{index}.jpg', 'temp') + f'\n【游戏】| {title}\n【链接】 | {link}\n'
index += 1
if result != '':
result = 'epic限免游戏(速速白嫖):\n' + result
else:
result = '今天没有游戏可以白嫖了!'
return result
# print(asyncio.get_event_loop().run_until_complete(get_epic_game()))
url = f"{RSSHUBAPP}/epicgames/freegames"
async def get_epic_game() -> "str, int":
result = "今天没有游戏可以白嫖了!"
code = 999
try:
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, proxy=get_local_proxy(), timeout=7) as response:
data = feedparser.parse(await response.text())["entries"]
if len(data) == 0:
return result
index = 0
for item in data:
title = item["title"]
img_url = item["summary"][
item["summary"].find('src="') + 5 : item["summary"].rfind('"')
]
async with session.get(
img_url, proxy=get_local_proxy(), timeout=7
) as res:
async with aiofiles.open(
IMAGE_PATH + f"temp/epic_{index}.jpg", "wb"
) as f:
await f.write(await res.read())
link = item["link"]
result += (
image(f"epic_{index}.jpg", "temp")
+ f"\n【游戏】| {title}\n【链接】 | {link}\n"
)
code = 200
index += 1
if result != "":
result = "epic限免游戏(速速白嫖):\n" + result
else:
result = "今天没有游戏可以白嫖了!"
except TimeoutError:
return "请求超时!", code
return result, code
+17 -28
View File
@@ -1,29 +1,31 @@
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot import on_command
from utils.utils import get_message_imgs, get_message_text
from utils.init_result import share
from utils.message_builder import share
from services.log import logger
__plugin_name = '假消息'
__plugin_name = "假消息"
__plugin_usage__ = '用法:\n格式:假消息 [网址] [标题] [内容](可省) [图片](可省)\n' \
'示例:假消息 www.4399.com 我喜欢萝莉 为什么我喜欢... [图片]'
__plugin_usage__ = (
"用法:\n格式:假消息 [网址] [标题] [内容](可省) [图片](可省)\n"
"示例:假消息 www.4399.com 我喜欢萝莉 为什么我喜欢... [图片]"
)
fake_msg = on_command('假消息', priority=5, block=True)
fake_msg = on_command("假消息", priority=5, block=True)
@fake_msg.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json()).split(' ')
msg = get_message_text(event.json()).split(" ")
img = get_message_imgs(event.json())
if len(msg) > 1:
if len(msg) == 2:
url = msg[0]
title = msg[1]
content = ''
content = ""
else:
url = msg[0]
title = msg[1]
@@ -31,26 +33,13 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
if img:
img = img[0]
else:
img = ''
if url.find('http://') == -1:
url = 'http://' + url
img = ""
if "http" not in url:
url = "http://" + url
await fake_msg.send(share(url, title, content, img))
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 构造假消息 url {url}, title {title}, content {content}")
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 构造假消息 url {url}, title {title}, content {content}"
)
else:
await fake_msg.finish('消息格式错误:\n网址 标题 内容(可省略) 图片(可省略)')
await fake_msg.finish("消息格式错误:\n网址 标题 内容(可省略) 图片(可省略)")
+21 -15
View File
@@ -1,8 +1,8 @@
from nonebot.adapters.cqhttp.permission import GROUP
from configs.path_config import IMAGE_PATH
from utils.img_utils import get_img_hash
from utils.image_utils import get_img_hash
import random
from utils.init_result import image
from utils.message_builder import image
from nonebot import on_message
from utils.utils import get_message_text, get_message_imgs, get_local_proxy
from nonebot.typing import T_State
@@ -10,6 +10,7 @@ from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
import aiohttp
import aiofiles
from collections import defaultdict
from asyncio.exceptions import TimeoutError
from configs.config import FUDU_PROBABILITY
@@ -44,8 +45,8 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if event.is_tome() or state["_prefix"]["raw_command"]:
return
if get_message_text(event.json()):
if get_message_text(event.json()).find('@可爱的小真寻') != -1:
await fudu.finish('复制粘贴的虚空艾特?', at_sender=True)
if get_message_text(event.json()).find("@可爱的小真寻") != -1:
await fudu.finish("复制粘贴的虚空艾特?", at_sender=True)
imgs = get_message_imgs(event.json())
msg = get_message_text(event.json())
if not imgs and not msg:
@@ -53,8 +54,8 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if imgs:
img_hash = await get_fudu_img_hash(imgs[0], event.group_id)
else:
img_hash = ''
add_msg = msg + '|-|' + img_hash
img_hash = ""
add_msg = msg + "|-|" + img_hash
if _fudulist.size(event.group_id) == 0:
_fudulist.append(event.group_id, add_msg)
elif _fudulist.check(event.group_id, add_msg):
@@ -67,22 +68,27 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if random.random() < 0.2:
await fudu.finish("打断施法!")
if imgs and msg:
rst = msg + image(f'compare_{event.group_id}_img.jpg', 'temp')
rst = msg + image(f"compare_{event.group_id}_img.jpg", "temp")
elif imgs:
rst = image(f'compare_{event.group_id}_img.jpg', 'temp')
rst = image(f"compare_{event.group_id}_img.jpg", "temp")
elif msg:
rst = msg
else:
rst = ''
rst = ""
if rst:
await fudu.send(rst)
_fudulist.clear(event.group_id)
async def get_fudu_img_hash(url, group_id):
async with aiohttp.ClientSession() as session:
async with session.get(url, proxy=get_local_proxy(), timeout=5) as response:
async with aiofiles.open(IMAGE_PATH + f"temp/compare_{group_id}_img.jpg", 'wb') as f:
await f.write(await response.read())
img_hash = get_img_hash(IMAGE_PATH + f"temp/compare_{group_id}_img.jpg")
return str(img_hash)
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, proxy=get_local_proxy(), timeout=5) as response:
async with aiofiles.open(
IMAGE_PATH + f"temp/compare_{group_id}_img.jpg", "wb"
) as f:
await f.write(await response.read())
img_hash = get_img_hash(IMAGE_PATH + f"temp/compare_{group_id}_img.jpg")
return str(img_hash)
except TimeoutError:
return ''
+11 -10
View File
@@ -4,26 +4,27 @@ from utils.utils import get_bot, scheduler
from nonebot import on_command
from models.level_user import LevelUser
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from utils.init_result import image
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, MessageEvent
from utils.message_builder import image
from services.log import logger
from models.group_remind import GroupRemind
FILE_PATH = os.path.dirname(__file__)
almanac = on_command('原神黄历', priority=5, block=True)
reload = on_command('重载原神黄历数据', priority=5, block=True)
almanac = on_command("原神黄历", priority=5, block=True)
reload = on_command("重载原神黄历数据", priority=5, block=True)
@almanac.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
async def _(bot: Bot, event: MessageEvent, state: T_State):
almanac_base64 = get_almanac_base64_str()
mes = image(b64=almanac_base64) + "\n ※ 黄历数据来源于 genshin.pub"
await almanac.send(mes)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 发送查看原神黄历")
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送查看原神黄历"
)
@reload.handle()
@@ -34,7 +35,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
@scheduler.scheduled_job(
'cron',
"cron",
hour=10,
minute=25,
)
@@ -42,9 +43,9 @@ async def _():
# 每日提醒
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
gl = [g["group_id"] for g in gl]
almanac_base64 = get_almanac_base64_str()
mes = image(b64=almanac_base64) + "\n ※ 黄历数据来源于 genshin.pub"
for gid in gl:
if await GroupRemind.get_status(gid, 'almanac'):
if await GroupRemind.get_status(gid, "almanac"):
await bot.send_group_msg(group_id=int(gid), message=mes)
+2 -3
View File
@@ -1,8 +1,8 @@
from nonebot import on_command, Driver
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent, Message
from utils.img_utils import CreateImg
from utils.init_result import image
from utils.message_builder import image
from utils.image_utils import CreateImg
from utils.browser import get_browser
from configs.path_config import IMAGE_PATH
import nonebot
@@ -109,7 +109,6 @@ def get_background_height(weapons_imgs: List[str]) -> int:
height += CreateImg(0, 0, background=weapons).size[1]
last_weapon = CreateImg(0, 0, background=weapons_imgs[-1])
w, h = last_weapon.size
print(w, h)
last_weapon.crop((0, 0, w, h - 10))
last_weapon.save(weapons_imgs[-1])
@@ -1,19 +1,17 @@
from .qiu_translation import qiu_qiu_word_translation, qiu_qiu_phrase_translation
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from nonebot import on_command
from utils.utils import get_message_text
from services.log import logger
__plugin_name__ = '丘丘语翻译'
__plugin_name__ = "丘丘语翻译"
__plugin_usage__ = '用法:丘丘翻译 [消息]'
__plugin_usage__ = "用法:丘丘翻译 [消息]"
qiuqiu = on_command("丘丘语翻译", aliases={"丘丘一下", "丘丘翻译"}, priority=5, block=True)
suffix = "\n※ 只能从丘丘语翻译为中文,不能反向翻译\n" \
"※ 注意空格,不要加入任何标点符号\n" \
"※ 翻译数据来源于 米游社论坛"
suffix = "\n※ 只能从丘丘语翻译为中文,不能反向翻译\n" "※ 注意空格,不要加入任何标点符号\n" "※ 翻译数据来源于 米游社论坛"
@qiuqiu.handle()
@@ -28,13 +26,6 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
# print(mes)
await qiuqiu.send(mes, at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 发送丘丘翻译:" + txt)
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送丘丘翻译:" + txt
)
@@ -6,7 +6,9 @@ FILE_PATH = os.path.dirname(__file__)
QIU_QIU_WORD = {}
QIU_QIU_PHRASE = {}
with open(os.path.join(FILE_PATH, 'qiu_qiu_dictionary.json'), 'r', encoding='UTF-8') as f:
with open(
os.path.join(FILE_PATH, "qiu_qiu_dictionary.json"), "r", encoding="UTF-8"
) as f:
data = json.load(f)
QIU_QIU_WORD = data["word"]
QIU_QIU_PHRASE = data["phrase"]
@@ -1,96 +1,92 @@
from nonebot import on_command, on_regex
from nonebot.rule import to_me
from .query_resource import get_resource_map_mes, get_resource_list_mes, up_label_and_point_list
from .query_resource import get_resource_type_list, query_resource, init
from utils.utils import get_message_text, scheduler
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.typing import T_State
import os
from services.log import logger
import re
try:
import ujson as json
except ModuleNotFoundError:
import json
__plugin_name__ = '原神资源查询'
__plugin_name__ = "原神资源查询"
__plugin_usage__ = '用法:\n' \
'\t原神资源查询 [消息]\n' \
'\t原神资源列表\n' \
'\t[消息]在哪\n' \
'\t哪有[消息]\n' \
'[消息] = 资源名称'
__plugin_usage__ = (
"用法:\n" "\t原神资源查询 [消息]\n" "\t原神资源列表\n" "\t[消息]在哪\n" "\t哪有[消息]\n" "[消息] = 资源名称"
)
qr = on_command("原神资源查询", priority=5, block=True)
qr_lst = on_command("原神资源列表", priority=5, block=True)
rex_qr = on_regex('.*?(在哪|在哪里|哪有|哪里有).*?', rule=to_me(), priority=5, block=True)
with open(os.path.dirname(__file__) + '/resource_type_id.json', 'r', encoding='utf-8') as f:
in_list = [n['name'] for n in json.load(f).values()]
rex_qr = on_regex(".*?(在哪|在哪里|哪有|哪里有).*?", rule=to_me(), priority=5, block=True)
update_info = on_command('更新原神资源信息', priority=1, block=True)
@qr.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
resource_name = get_message_text(event.json())
if resource_name == "" or resource_name not in in_list:
return
await qr.send(await get_resource_map_mes(resource_name), at_sender=True)
await qr.send('正在生成位置....')
rst = await query_resource(resource_name)
await qr.send(Message(rst), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 查询原神材料:" + resource_name)
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
@rex_qr.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if msg.find('在哪') != -1:
rs = re.search('(.*)在哪.*?', msg)
resource_name = rs.group(1) if rs else ''
if msg.find("在哪") != -1:
rs = re.search("(.*)在哪.*?", msg)
resource_name = rs.group(1) if rs else ""
else:
rs = re.search('.*?(哪有|哪里有)(.*)', msg)
resource_name = rs.group(2) if rs else ''
rs = re.search(".*?(哪有|哪里有)(.*)", msg)
resource_name = rs.group(2) if rs else ""
if resource_name:
msg = await get_resource_map_mes(resource_name)
if msg == '发送 原神资源列表 查看所有资源名称':
return
await rex_qr.send(msg, at_sender=True)
await qr.send('正在生成位置....')
msg = await query_resource(resource_name)
await rex_qr.send(Message(msg), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 查询原神材料:" + resource_name)
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
@qr_lst.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
# 长条消息经常发送失败,所以只能这样了
mes_list = []
txt = get_resource_list_mes()
txt = get_resource_type_list()
txt_list = txt.split("\n")
if event.message_type == 'group':
if event.message_type == "group":
for txt in txt_list:
data = {
"type": "node",
"data": {
"name": f"这里是{list(bot.config.nickname)[0]}酱",
"uin": f"{bot.self_id}",
"content": txt
}
"content": txt,
},
}
mes_list.append(data)
# await bot.send(ev, get_resource_list_mes(), at_sender=True)
if event.message_type == 'group':
if isinstance(event, GroupMessageEvent):
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
else:
rst = ''
rst = ""
for i in range(len(txt_list)):
rst += txt_list[i] + '\n'
rst += txt_list[i] + "\n"
if i % 5 == 0:
if rst:
await qr_lst.send(rst)
rst = ''
rst = ""
# await qr_lst.send(Message(mes_list))
@update_info.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
await init(True)
await update_info.send('更新原神资源信息完成...')
@scheduler.scheduled_job(
@@ -100,7 +96,7 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
)
async def _():
try:
await up_label_and_point_list()
await init()
logger.info(f'每日更新原神材料信息成功!')
except Exception as e:
logger.error(f'每日更新原神材料信息错误:{e}')
@@ -0,0 +1,158 @@
from pathlib import Path
from configs.path_config import IMAGE_PATH, TXT_PATH
from utils.image_utils import CreateImg
from typing import Tuple
from math import sqrt, pow
import random
try:
import ujson as json
except ModuleNotFoundError:
import json
icon_path = Path(IMAGE_PATH) / "genshin" / "genshin_icon"
map_path = Path(IMAGE_PATH) / "genshin" / "map" / "map.png"
resource_label_file = Path(TXT_PATH) / "genshin" / "resource_label_file.json"
resource_point_file = Path(TXT_PATH) / "genshin" / "resource_point_file.json"
class Map:
"""
原神资源生成类
"""
def __init__(
self,
resource_name: str,
center_point: Tuple[int, int],
deviation: Tuple[int, int] = (25, 51),
padding: int = 100,
planning_route: bool = False,
):
"""
参数:
:param resource_name: 资源名称
:param center_point: 中心点
:param deviation: 坐标误差
:param padding: 截图外边距
:param planning_route: 是否规划最佳线路
"""
self.map = CreateImg(0, 0, background=map_path)
self.resource_name = resource_name
self.center_x = center_point[0]
self.center_y = center_point[1]
self.deviation = deviation
self.padding = padding
self.planning_route = planning_route
data = json.load(open(resource_label_file, "r", encoding="utf8"))
# 资源 id
self.resource_id = [
data[x]["id"]
for x in data
if x != "CENTER_POINT" and data[x]["name"] == resource_name
][0]
# 传送锚点 id
self.teleport_anchor_id = [
data[x]["id"]
for x in data
if x != "CENTER_POINT" and data[x]["name"] == "传送锚点"
][0]
# 神像 id
self.teleport_god_id = [
data[x]["id"]
for x in data
if x != "CENTER_POINT" and data[x]["name"] == "七天神像"
][0]
# 资源坐标
data = json.load(open(resource_point_file, "r", encoding="utf8"))
self.resource_point = [
(
self.center_x + int(data[x]["x_pos"]),
self.center_y + int(data[x]["y_pos"]),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.resource_id
]
# 传送锚点坐标
self.teleport_anchor_point = [
(
self.center_x + int(data[x]["x_pos"]),
self.center_y + int(data[x]["y_pos"]),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_anchor_id
]
# 神像坐标
self.teleport_god_point = [
(
self.center_x + int(data[x]["x_pos"]),
self.center_y + int(data[x]["y_pos"]),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_god_id
]
# 将地图上生成资源图标
def generate_resource_icon_in_map(self) -> int:
x_list = [x[0] for x in self.resource_point]
y_list = [x[1] for x in self.resource_point]
min_width = min(x_list) - self.padding
max_width = max(x_list) + self.padding
min_height = min(y_list) - self.padding
max_height = max(y_list) + self.padding
if self.planning_route:
self._generate_best_route()
self._generate_transfer_icon((min_width, min_height, max_width, max_height))
for x, y in self.resource_point:
icon = self._get_icon_image(self.resource_id)
self.map.paste(icon, (x - self.deviation[0], y - self.deviation[1]), True)
self.map.crop((min_width, min_height, max_width, max_height))
rand = random.randint(1, 10000)
self.map.save(f'{IMAGE_PATH}/temp/genshin_map_{rand}.png')
return rand
# 资源数量
def get_resource_count(self) -> int:
return len(self.resource_point)
# 生成传送锚点和神像
def _generate_transfer_icon(self, box: Tuple[int, int, int, int]):
min_width, min_height, max_width, max_height = box
for points in [self.teleport_anchor_point, self.teleport_god_point]:
id_ = (
self.teleport_anchor_id
if points == self.teleport_anchor_point
else self.teleport_god_id
)
for x, y in points:
if min_width < x < max_width and min_height < y < max_height:
icon = self._get_icon_image(id_)
self.map.paste(
icon, (x - self.deviation[0], y - self.deviation[1]), True
)
# 生成最优路线(说是最优其实就是直线最短)
def _generate_best_route(self):
for x, y in self.resource_point:
min_deviation = 999999
xy = None
for points in [
self.resource_point,
self.teleport_anchor_point,
self.teleport_god_point,
]:
for r_x, r_y in points:
distance = int(sqrt(pow(abs(r_x - x), 2) + pow(abs(r_y - y), 2)))
if distance < min_deviation and x != r_x and y != r_y:
min_deviation = distance
xy = (x, y, r_x, r_y)
self.map.line(xy, (255, 0, 0), width=3)
# 获取资源图标
def _get_icon_image(self, id_: int) -> "CreateImg":
icon = icon_path / f"{id_}.png"
if icon.exists():
return CreateImg(50, 50, background=icon)
return CreateImg(50, 50, background=f"{icon_path}/box.png")
@@ -1,312 +1,240 @@
from urllib import request
from PIL import Image, ImageMath
from io import BytesIO
import json
import os
import time
import base64
from configs.path_config import IMAGE_PATH
from utils.init_result import image
from typing import Tuple, Optional, List
from configs.path_config import IMAGE_PATH, TXT_PATH
from PIL.Image import UnidentifiedImageError
from utils.message_builder import image
from services.log import logger
from .map import Map
from utils.image_utils import CreateImg
import asyncio
from pathlib import Path
from asyncio.exceptions import TimeoutError
from asyncio import Semaphore
from aiohttp.client import ClientSession
from utils.user_agent import get_user_agent
from utils.image_utils import is_valid
import nonebot
import aiohttp
import aiofiles
import os
try:
import ujson as json
except ModuleNotFoundError:
import json
driver: nonebot.Driver = nonebot.get_driver()
LABEL_URL = 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/map/label/tree?app_sn=ys_obc'
POINT_LIST_URL = 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/map/point/list?map_id=2&app_sn=ys_obc'
LABEL_URL = "https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/map/label/tree?app_sn=ys_obc"
POINT_LIST_URL = "https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/map/point/list?map_id=2&app_sn=ys_obc"
MAP_URL = "https://api-static.mihoyo.com/common/map_user/ys_obc/v1/map/info?map_id=2&app_sn=ys_obc&lang=zh-cn"
header = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/84.0.4147.105 Safari/537.36'
icon_path = Path(IMAGE_PATH) / "genshin" / "genshin_icon"
map_path = Path(IMAGE_PATH) / "genshin" / "map"
resource_label_file = Path(TXT_PATH) / "genshin" / "resource_label_file.json"
resource_point_file = Path(TXT_PATH) / "genshin" / "resource_point_file.json"
resource_type_file = Path(TXT_PATH) / "genshin" / "resource_type_file.json"
FILE_PATH = IMAGE_PATH + 'genshin/'
if not os.path.exists(IMAGE_PATH + 'genshin/genshin_icon/'):
os.mkdir(IMAGE_PATH + 'genshin/genshin_icon/')
# 地图中心坐标
CENTER_POINT: Optional[Tuple[int, int]] = None
MAP_PATH = None
MAP_IMAGE = None
MAP_SIZE = None
# resource_point里记录的坐标是相对坐标,是以蒙德城的大雕像为中心的,所以图片合成时需要转换坐标
CENTER = (3505, 1907)
zoom = 0.75
resource_icon_offset = (-int(150 * 0.5 * zoom), -int(150 * zoom))
resource_name_list: List[str] = []
@driver.on_startup
async def init():
global MAP_SIZE, MAP_PATH, MAP_IMAGE
MAP_PATH = os.path.join(IMAGE_PATH, "genshin", "seek_god_eye", "icon", "map_icon.jpg")
MAP_IMAGE = await asyncio.get_event_loop().run_in_executor(None, Image.open, MAP_PATH)
MAP_SIZE = MAP_IMAGE.size
await up_label_and_point_list()
# 查找资源
async def query_resource(resource_name: str) -> str:
planning_route: bool = False
if resource_name and resource_name[-2:] == "路径":
resource_name = resource_name[:-2].strip()
planning_route = True
if not resource_name or resource_name not in resource_name_list:
return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.."
map_ = Map(resource_name, CENTER_POINT, planning_route=planning_route)
count = map_.get_resource_count()
rand = await asyncio.get_event_loop().run_in_executor(None, map_.generate_resource_icon_in_map)
return f"{image(f'genshin_map_{rand}.png', 'temp')}" \
f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki"
data = {
"all_resource_type": {
# 这个字典保存所有资源类型,
# "1": {
# "id": 1,
# "name": "传送点",
# "icon": "",
# "parent_id": 0,
# "depth": 1,
# "node_type": 1,
# "jump_type": 0,
# "jump_target_id": 0,
# "display_priority": 0,
# "children": []
# },
},
"can_query_type_list": {
# 这个字典保存所有可以查询的资源类型名称和ID,这个字典只有名称和ID
# 上边字典里"depth": 2的类型才可以查询,"depth": 1的是1级目录,不能查询
# "七天神像":"2"
# "风神瞳":"5"
},
"all_resource_point_list": [
# 这个列表保存所有资源点的数据
# {
# "id": 2740,
# "label_id": 68,
# "x_pos": -1789,
# "y_pos": 2628,
# "author_name": "✟紫灵心✟",
# "ctime": "2020-10-29 10:41:21",
# "display_state": 1
# },
],
"date": "" # 记录上次更新"all_resource_point_list"的日期
}
def up_icon_image(sublist):
# 检查是否有图标,没有图标下载保存到本地
id = sublist["id"]
icon_url = sublist["icon"]
icon_path = os.path.join(FILE_PATH, "genshin_icon", f"{id}.png")
if not os.path.exists(icon_path):
schedule = request.Request(icon_url)
schedule.add_header('User-Agent', header)
with request.urlopen(schedule) as f:
icon = Image.open(f)
icon = icon.resize((150, 150))
box_alpha = Image.open(os.path.join(FILE_PATH, "genshin_icon", "box_alpha.png")).getchannel("A")
box = Image.open(os.path.join(FILE_PATH, "genshin_icon", "box.png"))
logger.info(f'原神资源更新 --> {sublist}')
try:
icon_alpha = icon.getchannel("A")
icon_alpha = ImageMath.eval("convert(a*b/256, 'L')", a=icon_alpha, b=box_alpha)
except ValueError:
# 米游社的图有时候会没有alpha导致报错,这时候直接使用box_alpha当做alpha就行
icon_alpha = box_alpha
icon2 = Image.new("RGBA", (150, 150), "#00000000")
icon2.paste(icon, (0, -10))
bg = Image.new("RGBA", (150, 150), "#00000000")
bg.paste(icon2, mask=icon_alpha)
bg.paste(box, mask=box)
with open(icon_path, "wb") as icon_file:
bg.save(icon_file)
async def up_label_and_point_list():
# 更新label列表和资源点列表
try:
if os.path.exists(os.path.dirname(__file__) + '/icon/box_alpha.png'):
os.rename(os.path.dirname(__file__) + '/icon/box_alpha.png', IMAGE_PATH + 'genshin/genshin_icon/box_alpha.png')
except:
pass
try:
if os.path.exists(os.path.dirname(__file__) + '/icon/box.png'):
os.rename(os.path.dirname(__file__) + '/icon/box.png', IMAGE_PATH + 'genshin/genshin_icon/box.png')
except:
pass
schedule = request.Request(LABEL_URL)
schedule.add_header('User-Agent', header)
with request.urlopen(schedule, timeout=5) as f:
if f.code != 200: # 检查返回的状态码是否是200
raise ValueError(f"资源标签列表初始化失败,错误代码{f.code}")
label_data = json.loads(f.read().decode('utf-8'))
tasks = []
for label in label_data["data"]["tree"]:
data["all_resource_type"][str(label["id"])] = label
for sublist in label["children"]:
data["all_resource_type"][str(sublist["id"])] = sublist
data["can_query_type_list"][sublist["name"]] = str(sublist["id"])
tasks.append(asyncio.get_event_loop().run_in_executor(None, up_icon_image, sublist))
# logger.info(f'原神资源更新 --> {sublist}')
label["children"] = []
await asyncio.gather(*tasks)
schedule = request.Request(POINT_LIST_URL)
schedule.add_header('User-Agent', header)
with request.urlopen(schedule) as f:
if f.code != 200: # 检查返回的状态码是否是200
raise ValueError(f"资源点列表初始化失败,错误代码{f.code}")
test = json.loads(f.read().decode('utf-8'))
data["all_resource_point_list"] = test["data"]["point_list"]
data["date"] = time.strftime("%d")
# def load_resource_type_id():
# with open(os.path.join(FILE_PATH,'resource_type_id.json'), 'r', encoding='UTF-8') as f:
# json_data = json.load(f)
# for id in json_data.keys():
# data["all_resource_type"][id] = json_data[id]
# if json_data[id]["depth"] != 1:
# data["can_query_type_list"][json_data[id]["name"]] = id
# 初始化
# load_resource_type_id()
class Resource_map(object):
def __init__(self, resource_name):
self.resource_id = str(data["can_query_type_list"][resource_name])
# 地图要要裁切的左上角和右下角坐标
# 这里初始化为地图的大小
self.x_start = MAP_SIZE[0]
self.y_start = MAP_SIZE[1]
self.x_end = 0
self.y_end = 0
self.map_image = MAP_IMAGE.copy()
self.resource_icon = Image.open(self.get_icon_path())
self.resource_icon = self.resource_icon.resize((int(150 * zoom), int(150 * zoom)))
self.resource_xy_list = self.get_resource_point_list()
def get_icon_path(self):
# 检查有没有图标,有返回正确图标,没有返回默认图标
icon_path = os.path.join(FILE_PATH, "genshin_icon", f"{self.resource_id}.png")
if os.path.exists(icon_path):
return icon_path
else:
return os.path.join(FILE_PATH, "genshin_icon", "0.png")
def get_resource_point_list(self):
temp_list = []
for resource_point in data["all_resource_point_list"]:
if str(resource_point["label_id"]) == self.resource_id:
# 获取xy坐标,然后加上中心点的坐标完成坐标转换
x = resource_point["x_pos"] + CENTER[0]
y = resource_point["y_pos"] + CENTER[1]
temp_list.append((int(x), int(y)))
return temp_list
def paste(self):
for x, y in self.resource_xy_list:
# 把资源图片贴到地图上
self.map_image.paste(self.resource_icon, (x + resource_icon_offset[0], y + resource_icon_offset[1]),
self.resource_icon)
# 找出4个方向最远的坐标,用于后边裁切
self.x_start = min(x, self.x_start)
self.y_start = min(y, self.y_start)
self.x_end = max(x, self.x_end)
self.y_end = max(y, self.y_end)
def crop(self):
# 先把4个方向扩展150像素防止把资源图标裁掉
self.x_start -= 150
self.y_start -= 150
self.x_end += 150
self.y_end += 150
# 如果图片裁切的太小会看不出资源的位置在哪,检查图片裁切的长和宽看够不够1000,不到1000的按1000裁切
if (self.x_end - self.x_start) < 1000:
center = int((self.x_end + self.x_start) / 2)
self.x_start = center - 500
self.x_end = center + 500
if (self.y_end - self.y_start) < 1000:
center = int((self.y_end + self.y_start) / 2)
self.y_start = center - 500
self.y_end = center + 500
self.map_image = self.map_image.crop((self.x_start, self.y_start, self.x_end, self.y_end))
def get_cq_cod(self):
if not self.resource_xy_list:
return "没有这个资源的信息"
self.paste()
self.crop()
bio = BytesIO()
self.map_image.save(bio, format='JPEG')
base64_str = 'base64://' + base64.b64encode(bio.getvalue()).decode()
return image(b64=base64_str)
def get_resource_count(self):
return len(self.resource_xy_list)
async def get_resource_map_mes(name):
if data["date"] != time.strftime("%d"):
await up_label_and_point_list()
if not (name in data["can_query_type_list"]):
return f"没有 {name} 这种资源。\n发送 原神资源列表 查看所有资源名称"
map = Resource_map(name)
count = map.get_resource_count()
if not count:
return f"没有找到 {name} 资源的位置,可能米游社wiki还没更新。"
mes = f"资源 {name} 的位置如下\n"
mes += map.get_cq_cod()
mes += f"\n\n※ {name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki"
return mes
def get_resource_list_mes():
# 原神资源列表
def get_resource_type_list():
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
temp = {}
for id in data["all_resource_type"].keys():
# 先找1级目录
if data["all_resource_type"][id]["depth"] == 1:
temp[id] = []
for id in data["all_resource_type"].keys():
# 再找2级目录
if data["all_resource_type"][id]["depth"] == 2:
temp[str(data["all_resource_type"][id]["parent_id"])].append(id)
for id_ in data.keys():
temp[data[id_]["name"]] = []
for x in data[id_]["children"]:
temp[data[id_]["name"]].append(x["name"])
mes = "当前资源列表如下:\n"
for resource_type_id in temp.keys():
if resource_type_id in ["1", "12", "50", "51", "95", "131"]:
# 在游戏里能查到的数据这里就不列举了,不然消息太长了
continue
mes += f"{data['all_resource_type'][resource_type_id]['name']}:"
for resource_id in temp[resource_type_id]:
mes += f"{data['all_resource_type'][resource_id]['name']},"
mes += "\n"
for resource_type in temp.keys():
mes += f"{resource_type}:{','.join(temp[resource_type])}\n"
return mes
@driver.on_startup
async def init(flag: bool = False):
global CENTER_POINT, resource_name_list
semaphore = asyncio.Semaphore(10)
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
await download_map_init(session, semaphore, flag)
await download_resource_data(session, semaphore)
await download_resource_type(session)
if not CENTER_POINT:
CENTER_POINT = json.load(open(resource_label_file, "r", encoding="utf8"))[
"CENTER_POINT"
]
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
for id_ in data:
for x in data[id_]["children"]:
resource_name_list.append(x["name"])
# 图标及位置资源
async def download_resource_data(session: ClientSession, semaphore: Semaphore):
icon_path.mkdir(parents=True, exist_ok=True)
resource_label_file.parent.mkdir(parents=True, exist_ok=True)
try:
async with session.get(POINT_LIST_URL, timeout=5) as response:
if response.status == 200:
data = await response.json()
if data["message"] == "OK":
data = data["data"]
for lst in ["label_list", "point_list"]:
resource_data = {"CENTER_POINT": CENTER_POINT}
tasks = []
file = (
resource_label_file
if lst == "label_list"
else resource_point_file
)
for x in data[lst]:
id_ = x["id"]
if lst == "label_list":
img_url = x["icon"]
tasks.append(
asyncio.ensure_future(
download_image(
img_url,
f"{icon_path}/{id_}.png",
session,
semaphore,
True,
)
)
)
resource_data[id_] = x
await asyncio.gather(*tasks)
with open(file, "w", encoding="utf8") as f:
json.dump(resource_data, f, ensure_ascii=False, indent=4)
else:
logger.warning(f'获取原神资源失败 msg: {data["message"]}')
else:
logger.warning(f"获取原神资源失败 code:{response.status}")
except TimeoutError:
logger.warning("获取原神资源数据超时...已再次尝试...")
await download_resource_data(session, semaphore)
# 下载原神地图并拼图
async def download_map_init(session: ClientSession, semaphore: Semaphore, flag: bool = False):
global CENTER_POINT
map_path.mkdir(exist_ok=True, parents=True)
async with session.get(MAP_URL, timeout=5) as response:
if response.status == 200:
data = await response.json()
if data["message"] == "OK":
data = json.loads(data["data"]["info"]["detail"])
CENTER_POINT = (data["origin"][0], data["origin"][1])
# padding_w, padding_h = data['padding']
data = data["slices"]
idx = 0
for x in data:
idj = 0
for j in x:
await download_image(
j["url"],
f"{map_path}/{idx}_{idj}.png",
session,
semaphore,
force_flag=flag
)
idj += 1
idx += 1
map_width, map_height = CreateImg(
0, 0, background=f"{map_path}/0_0.png"
).size
lens = len([x for x in os.listdir(f"{map_path}") if x.startswith("0")])
background_image = CreateImg(
map_width * lens, map_height * lens, map_width, map_height
)
for i in range(idx):
for j in range(idj):
x = CreateImg(0, 0, background=f"{map_path}/{i}_{j}.png")
background_image.paste(x)
background_image.save(f"{map_path}/map.png")
else:
logger.warning(f'获取原神地图失败 msg: {data["message"]}')
else:
logger.warning(f"获取原神地图失败 code:{response.status}")
# 下载资源类型数据
async def download_resource_type(session: ClientSession):
resource_type_file.parent.mkdir(parents=True, exist_ok=True)
async with session.get(LABEL_URL, timeout=5) as response:
if response.status == 200:
data = await response.json()
if data["message"] == "OK":
data = data["data"]["tree"]
resource_data = {}
for x in data:
id_ = x["id"]
resource_data[id_] = x
with open(resource_type_file, "w", encoding="utf8") as f:
json.dump(resource_data, f, ensure_ascii=False, indent=4)
logger.info(f"更新原神资源类型成功...")
else:
logger.warning(f'获取原神资源类型失败 msg: {data["message"]}')
else:
logger.warning(f"获取原神资源类型失败 code:{response.status}")
# 初始化资源图标
def gen_icon(icon: str):
A = CreateImg(0, 0, background=f"{icon_path}/box.png")
B = CreateImg(0, 0, background=f"{icon_path}/box_alpha.png")
icon_ = icon_path / f"{icon}"
icon_img = CreateImg(115, 115, background=icon_)
icon_img.circle()
B.paste(icon_img, (17, 10), True)
B.paste(A, alpha=True)
B.save(icon)
logger.info(f"生成图片成功 file:{str(icon)}")
# 下载图片
async def download_image(
img_url: str,
path: str,
session: ClientSession,
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:
async with session.get(img_url, timeout=5) as response:
async with aiofiles.open(path, "wb") as f:
await f.write(await response.read())
logger.info(f"下载原神资源图标:{img_url}")
if gen_flag:
gen_icon(path)
except TimeoutError:
logger.warning("下载原神资源图片超时...已再次尝试...")
await download_image(img_url, path, session, semaphore, gen_flag)
except UnidentifiedImageError:
logger.warning(f"原神图片打开错误..已删除,等待下次更新... file: {path}")
if os.path.exists(path):
os.remove(path)
@@ -1,926 +0,0 @@
{
"1": {
"id": 1,
"name": "传送点",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"2": {
"id": 2,
"name": "七天神像",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/c59585d1fabc9c22ad3fcf94e1622aa8_357413506633071859.png",
"parent_id": 1,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"3": {
"id": 3,
"name": "传送锚点",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/0cc42d15134cbb724304050fd0bbcaac_8799482478853097434.png",
"parent_id": 1,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"4": {
"id": 4,
"name": "神瞳",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"5": {
"id": 5,
"name": "风神瞳",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/4b568dcdea1c699456464c611ce87e4f_3484482126589511603.png",
"parent_id": 4,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"6": {
"id": 6,
"name": "岩神瞳",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/f4409292be83f81d0c41c350a91ebac1_355618004292502793.png",
"parent_id": 4,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"7": {
"id": 7,
"name": "地灵龛",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"8": {
"id": 8,
"name": "蒙德地灵龛",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/a9f458cf7ba149ec659aabb581050a0b_3339433578214432669.png",
"parent_id": 7,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"9": {
"id": 9,
"name": "璃月地灵龛",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/a9f458cf7ba149ec659aabb581050a0b_3479171218459475297.png",
"parent_id": 7,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"10": {
"id": 10,
"name": "区域特产",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"29": {
"id": 29,
"name": "落落莓",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/11e1861e2b94d1b1e132d61c0f7c3948_5882174105995719914.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"30": {
"id": 30,
"name": "绝云椒椒",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/3184e356629e8b071a878063d1c0df94_5172487424247849295.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"31": {
"id": 31,
"name": "嘟嘟莲",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/07a2252a60301893294ef377e563f0e7_7014418407781853378.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"32": {
"id": 32,
"name": "清心",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/0de9385a957ef0cb981a5ed6a6984f57_7797138076139828289.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"33": {
"id": 33,
"name": "小灯草",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/348fe1164e9330226b225c011aea4d5a_2068903308538485227.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"34": {
"id": 34,
"name": "琉璃袋",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/77dc4532fe938a24c4cc714d77d48b0d_6612669651078791213.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"35": {
"id": 35,
"name": "塞西莉亚花",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/e55cfc43f5e483362e9ddf433653d326_9031812646608361297.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"36": {
"id": 36,
"name": "霓裳花",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/e22d205c11b39b9b6984a4ec8adefeb2_2210397206297609865.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"37": {
"id": 37,
"name": "蒲公英籽",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/a348a4302f58f499bdf89025d2cb2cdb_2244957478004520779.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"38": {
"id": 38,
"name": "琉璃百合",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/dfe6d92e18060cd724ebadd73ba084c6_7141991283452930467.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"39": {
"id": 39,
"name": "慕风蘑菇",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/d0f4c83add3dc326ffc92b5fedb6f82c_3118392491847470850.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"40": {
"id": 40,
"name": "石珀",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/5789d9dc9c8840f21f9afc2437e9026e_8487232206600716291.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"41": {
"id": 41,
"name": "钩钩果",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/7dedeee543b94525f0812a18eb09b7d7_4938366361261655916.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"42": {
"id": 42,
"name": "夜泊石",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/51adcbda83a2f2b4422db9ad4908245b_7898256673375056193.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"43": {
"id": 43,
"name": "风车菊",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/387684f5c9a891135e05f95192b6dc21_2171784899125537458.png",
"parent_id": 10,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"11": {
"id": 11,
"name": "矿物",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"15": {
"id": 15,
"name": "白铁块",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/4d0e329b0458a918d376bbbabd4415cd_9079005216548585535.png",
"parent_id": 11,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"16": {
"id": 16,
"name": "水晶块",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/ceede1f6fa9a3e53986b5ac63e2aacb9_3251440935681461856.png",
"parent_id": 11,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"12": {
"id": 12,
"name": "怪物(精英)",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"19": {
"id": 19,
"name": "火斧丘丘暴徒",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/cef1444b97c8f49cd8cd8aa10e5448ae_1229715974301029440.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"20": {
"id": 20,
"name": "木盾丘丘暴徒",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/cef1444b97c8f49cd8cd8aa10e5448ae_2049522587981126653.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"21": {
"id": 21,
"name": "岩盾丘丘暴徒",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/cef1444b97c8f49cd8cd8aa10e5448ae_4383986804076887911.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"22": {
"id": 22,
"name": "火深渊法师",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/3c287ea61919d856723ba802fd91677f_2936850964636137610.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"23": {
"id": 23,
"name": "水深渊法师",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/5d59b593551bb62506096c76bd55ab2a_5561999899365928315.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"24": {
"id": 24,
"name": "冰深渊法师",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/4b9b07114f30df8715f41835d3215add_6327856690043584281.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"25": {
"id": 25,
"name": "愚人众 债务处理人",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/359e5697e4609a7f34714bfa65cce97e_7545179401283346969.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"26": {
"id": 26,
"name": "愚人众 雷萤术士",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/a73112218e1329ae4728a096554258d7_4082505538504798279.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"27": {
"id": 27,
"name": "遗迹守卫",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/86ddf140b786c6a2a73b038e341403a7_6217455819326456307.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"28": {
"id": 28,
"name": "遗迹猎者",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/99ce18638304f8169918c85436d0585c_5415189466598569723.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"47": {
"id": 47,
"name": "冰霜骗骗花",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/14/75276545/54904a37ab2165e5b8ad91c7ee805061_2703681786862158841.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"48": {
"id": 48,
"name": "炽热骗骗花",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/14/75276545/1848c68a09d54637721529abb35b22a1_7882961499456527312.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"49": {
"id": 49,
"name": "幼岩龙蜥",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/14/75276545/83d1ef1dbb3b6d489c0b150886597cbc_5647365818975751099.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"53": {
"id": 53,
"name": "丘丘岩盔王",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/a6e1a33b8f4bd4c8a091f69ead200948_2480904266424771100.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"54": {
"id": 54,
"name": "愚人众先遣队",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/8dd741d0f58dc6abef2f9ee6d278a062_7759801496426769012.png",
"parent_id": 12,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"13": {
"id": 13,
"name": "宝箱",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"17": {
"id": 17,
"name": "普通的宝箱",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/35cf41aad7620ce6d5dc516defb967f7_7806440070871726330.png",
"parent_id": 13,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"44": {
"id": 44,
"name": "精致的宝箱",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/14/75276545/35cf41aad7620ce6d5dc516defb967f7_6214340810257945197.png",
"parent_id": 13,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"45": {
"id": 45,
"name": "珍贵的宝箱",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/14/75276545/44a7de58782f36f15bec044c1069da76_7523256410581248233.png",
"parent_id": 13,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"46": {
"id": 46,
"name": "华丽的宝箱",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/14/75276545/35cf41aad7620ce6d5dc516defb967f7_3987566332689612662.png",
"parent_id": 13,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"14": {
"id": 14,
"name": "解谜",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"18": {
"id": 18,
"name": "指引仙灵",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/08/75276545/8de3558f991ac422463712dd095278b3_109842752079072307.png",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"64": {
"id": 64,
"name": "限时挑战",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/21/75795471/a6978cb8965e81de4a25accbf6c236ce_6189233402996409228.png",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"65": {
"id": 65,
"name": "风车机关",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_7547151797455251961.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"66": {
"id": 66,
"name": "漂浮的风史莱姆",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_6780166156178323412.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"67": {
"id": 67,
"name": "压力机关",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_5932273944571249310.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"68": {
"id": 68,
"name": "蓬蓬果",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_7627546850715675857.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"69": {
"id": 69,
"name": "挖掘宝箱",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_200949033774003499.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"70": {
"id": 70,
"name": "元素方碑",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_8520221369291334139.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"71": {
"id": 71,
"name": "火炬机关",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_1061118532437351431.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"72": {
"id": 72,
"name": "巨型碎石",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_6449674692302465374.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"73": {
"id": 73,
"name": "小石堆",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_7798666829547657712.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"74": {
"id": 74,
"name": "拔植物",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_3891992353724563278.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"75": {
"id": 75,
"name": "被束缚的宝箱",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_7069442788377617628.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"76": {
"id": 76,
"name": "岩种子",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_6714446188416963945.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"77": {
"id": 77,
"name": "微解谜",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/10/21/75795471/de87958fa1e78efcc84da49aad61dede_3053004782269703586.jpg",
"parent_id": 14,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"50": {
"id": 50,
"name": "怪物(普通)",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"55": {
"id": 55,
"name": "丘丘人",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/74c2350936386d12f84e4244b8bd9750_8061221501486024583.png",
"parent_id": 50,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"56": {
"id": 56,
"name": "射手丘丘人",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/74c2350936386d12f84e4244b8bd9750_8668908145618002848.png",
"parent_id": 50,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"57": {
"id": 57,
"name": "丘丘萨满",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/fbd2f8a868f6c3a6f587d57d655f40c9_1156685569894627424.png",
"parent_id": 50,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"58": {
"id": 58,
"name": "盗宝团",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/a9ecb7952e877dfd7c1dfae5132c7181_242314377398779361.png",
"parent_id": 50,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"59": {
"id": 59,
"name": "史莱姆",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/de444c63df86b407045c0cca2d9c24b2_761844897909742071.png",
"parent_id": 50,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"51": {
"id": 51,
"name": "世界任务",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"52": {
"id": 52,
"name": "世界任务",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/16/75795471/c7263000d1f1ec150eddd27fca4d8630_2386396225561541114.png",
"parent_id": 51,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"60": {
"id": 60,
"name": "材料",
"icon": "",
"parent_id": 0,
"depth": 1,
"node_type": 1,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"61": {
"id": 61,
"name": "冰雾花花朵",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/cca41572bb14d20c094ce9af77eefda9_2844359998862121652.png",
"parent_id": 60,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"62": {
"id": 62,
"name": "烈焰花花蕊",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/82a7a8327bfa630eb5e52695a2b456e9_4760074611076337816.png",
"parent_id": 60,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
},
"63": {
"id": 63,
"name": "电气水晶",
"icon": "https://uploadstatic.mihoyo.com/ys-obc/2020/09/17/75276545/aab9020763a7bee1fb532b7117b21fd1_5874466862813696108.png",
"parent_id": 60,
"depth": 2,
"node_type": 2,
"jump_type": 0,
"jump_target_id": 0,
"display_priority": 0,
"children": []
}
}
+76 -80
View File
@@ -1,29 +1,32 @@
from nonebot import on_notice, on_request
from configs.path_config import IMAGE_PATH, DATA_PATH
from utils.init_result import image
from utils.message_builder import image
import os
import random
from models.group_member_info import GroupInfoUser
from datetime import datetime
from services.log import logger
from models.group_remind import GroupRemind
from nonebot.adapters.cqhttp import Bot, GroupIncreaseNoticeEvent, GroupDecreaseNoticeEvent, GroupRequestEvent
from nonebot.adapters.cqhttp import (
Bot,
GroupIncreaseNoticeEvent,
GroupDecreaseNoticeEvent,
)
from nonebot.adapters.cqhttp.exception import ActionFailed
from pathlib import Path
from nonebot import require
from models.group_info import GroupInfo
try:
import ujson as json
except ModuleNotFoundError:
import json
__plugin_name__ = '群事件处理 [Hidden]'
__plugin_name__ = "群事件处理 [Hidden]"
__usage__ = '用法:无'
__usage__ = "用法:无"
export = require("admin_bot_manage")
# 群员增加处理
group_increase_handle = on_notice(priority=1, block=False)
# 群员减少处理
@@ -34,98 +37,91 @@ add_group = on_request(priority=1, block=False)
@group_increase_handle.handle()
async def _(bot: Bot, event: GroupIncreaseNoticeEvent, state: dict):
if event.user_id == int(bot.self_id):
await export.update_member_info(event.group_id)
logger.info('被邀请入群,自动更新群成员列表...')
join_time = datetime.now()
user_info = await bot.get_group_member_info(
group_id=event.group_id, user_id=event.user_id
)
if await GroupInfoUser.add_member_info(
user_info["user_id"],
user_info["group_id"],
user_info["nickname"],
join_time,
):
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新成功")
else:
join_time = datetime.now()
user_info = await bot.get_group_member_info(group_id=event.group_id, user_id=event.user_id)
if await GroupInfoUser.insert(
user_info['user_id'],
user_info['group_id'],
user_info['nickname'],
join_time,
):
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新成功")
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新失败")
# 群欢迎消息
if await GroupRemind.get_status(event.group_id, "hy"):
msg = ""
img = ""
at_flag = False
custom_welcome_msg_json = (
Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
)
if custom_welcome_msg_json.exists():
data = json.load(open(custom_welcome_msg_json, "r"))
if data.get(str(event.group_id)):
msg = data[str(event.group_id)]
if msg.find("[at]") != -1:
msg = msg.replace("[at]", "")
at_flag = True
if os.path.exists(DATA_PATH + f"custom_welcome_msg/{event.group_id}.jpg"):
img = image(abspath=DATA_PATH + f"custom_welcome_msg/{event.group_id}.jpg")
if msg or img:
await group_increase_handle.send(
"\n" + msg.strip() + img, at_sender=at_flag
)
else:
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新失败")
if await GroupRemind.get_status(event.group_id, 'hy'):
msg = ''
img = ''
at_flag = False
custom_welcome_msg_json = Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
if custom_welcome_msg_json.exists():
data = json.load(open(custom_welcome_msg_json, 'r'))
if data.get(str(event.group_id)):
msg = data[str(event.group_id)]
if msg.find('[at]') != -1:
msg = msg.replace('[at]', '')
at_flag = True
if os.path.exists(DATA_PATH + f'custom_welcome_msg/{event.group_id}.jpg'):
img = image(abspath=DATA_PATH + f'custom_welcome_msg/{event.group_id}.jpg')
if msg or img:
await group_increase_handle.send("\n" + msg + img, at_sender=at_flag)
else:
await group_increase_handle.send(
'新人快跑啊!!本群现状↓(快使用自定义!)' + image(random.choice(os.listdir(IMAGE_PATH + "qxz/")), "qxz"))
await group_increase_handle.send(
"新人快跑啊!!本群现状↓(快使用自定义!)"
+ image(random.choice(os.listdir(IMAGE_PATH + "qxz/")), "qxz")
)
@group_decrease_handle.handle()
async def _(bot: Bot, event: GroupDecreaseNoticeEvent, state: dict):
# 真寻被踢出群
if event.sub_type == 'kick_me':
if event.sub_type == "kick_me":
group_id = event.group_id
operator_id = event.operator_id
try:
operator_name = (await GroupInfoUser.select_member_info(event.operator_id, event.group_id)).user_name
operator_name = (
await GroupInfoUser.get_member_info(event.operator_id, event.group_id)
).user_name
except AttributeError:
operator_name = 'None'
operator_name = "None"
group = await GroupInfo.get_group_info(group_id)
group_name = group.group_name if group else ""
coffee = int(list(bot.config.superusers)[0])
await bot.send_private_msg(
user_id=coffee,
message=f'报告..\n'
f'我被 {operator_name}({operator_id})\n'
f'踢出了 {group_id}')
message=f"****呜..一份踢出报告****\n"
f"我被 {operator_name}({operator_id})\n"
f"踢出了 {group_name}({group_id})\n"
f"日期:{str(datetime.now()).split('.')[0]}",
)
return
try:
user_name = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
user_name = (
await GroupInfoUser.get_member_info(event.user_id, event.group_id)
).user_name
except AttributeError:
user_name = str(event.user_id)
rst = ''
if event.sub_type == 'leave':
rst = f'{user_name}离开了我们...'
if event.sub_type == 'kick':
try:
operator_name = (await GroupInfoUser.select_member_info(event.operator_id, event.group_id)).user_name
except AttributeError:
operator_name = event.operator_id
rst = f'{user_name} 被 {operator_name} 送走了.'
try:
await group_decrease_handle.send(f"{rst}")
except ActionFailed:
return
rst = ""
if event.sub_type == "leave":
rst = f"{user_name}离开了我们..."
if event.sub_type == "kick":
operator = await bot.get_group_member_info(
user_id=event.operator_id, group_id=event.group_id
)
operator_name = operator["card"] if operator["card"] else operator["nickname"]
rst = f"{user_name} 被 {operator_name} 送走了."
if await GroupInfoUser.delete_member_info(event.user_id, event.group_id):
logger.info(f"用户{user_name}, qq={event.user_id} 所属{event.group_id} 删除成功")
else:
logger.info(f"用户{user_name}, qq={event.user_id} 所属{event.group_id} 删除失败")
@add_group.handle()
async def _(bot: Bot, event: GroupRequestEvent, state: dict):
pass
# user_info = await bot._get_vip_info(user_id=event.user_id)
# if user_info['level'] > 16:
# bot.set
try:
await group_decrease_handle.send(f"{rst}")
except ActionFailed:
return
+54 -36
View File
@@ -9,90 +9,108 @@ from nonebot.permission import SUPERUSER
from pathlib import Path
from configs.config import plugins2info_dict
from nonebot.message import run_preprocessor, IgnoredException
try:
import ujson as json
except ModuleNotFoundError:
import json
__plugin_name__ = '群权限'
__plugin_usage__ = '区分权限功能'
__plugin_name__ = "群权限"
__plugin_usage__ = "区分权限功能"
flmt = FreqLimiter(60)
group_level_data = Path() / 'data'/ 'manager' / 'group_level.json'
group_level_data = Path() / "data" / "manager" / "group_level.json"
group_level_data.parent.mkdir(exist_ok=True, parents=True)
group_data = {}
if group_level_data.exists():
group_data = json.load(open(group_level_data, 'r', encoding='utf8'))
group_data = json.load(open(group_level_data, "r", encoding="utf8"))
@run_preprocessor
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, 9]:
if isinstance(event, GroupMessageEvent):
if not group_data.get(str(event.group_id)):
group_data[str(event.group_id)] = 5
if plugins2info_dict.get(matcher.module):
if plugins2info_dict[matcher.module]['level'] > group_data[str(event.group_id)]:
try:
if flmt.check(event.group_id):
flmt.start_cd(event.group_id)
await bot.send_group_msg(group_id=event.group_id, message='群权限不足...')
except Exception:
pass
raise IgnoredException('群权限不足')
if not check_level_group(matcher.module, event.group_id):
try:
if flmt.check(event.group_id):
flmt.start_cd(event.group_id)
await bot.send_group_msg(
group_id=event.group_id, message="群权限不足..."
)
except AttributeError:
pass
raise IgnoredException("群权限不足")
add_group_level = on_command('修改群权限', priority=1, permission=SUPERUSER, block=True)
my_group_level = on_command('查看群权限', aliases={'群权限'}, priority=5, permission=GROUP, block=True)
what_up_group_level = on_regex('.*?(提高|提升|升高|增加|加上)(.*?)群权限.*?', rule=to_me(), priority=5, permission=GROUP, block=True)
add_group_level = on_command("修改群权限", priority=1, permission=SUPERUSER, block=True)
my_group_level = on_command(
"查看群权限", aliases={"群权限"}, priority=5, permission=GROUP, block=True
)
what_up_group_level = on_regex(
".*?(提高|提升|升高|增加|加上)(.*?)群权限.*?",
rule=to_me(),
priority=5,
permission=GROUP,
block=True,
)
@add_group_level.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
await add_group_level.finish('用法:修改群权限 [group] [level]')
msg = msg.split(' ')
await add_group_level.finish("用法:修改群权限 [group] [level]")
msg = msg.split(" ")
if len(msg) < 2:
await add_group_level.finish('参数不完全..[group] [level]')
await add_group_level.finish("参数不完全..[group] [level]")
if is_number(msg[0]) and is_number(msg[1]):
group_id = msg[0]
level = int(msg[1])
else:
await add_group_level.finish('参数错误...group和level必须是数字..')
await add_group_level.finish("参数错误...group和level必须是数字..")
if not group_data.get(group_id):
group_data[group_id] = 5
await add_group_level.send('修改成功...', at_sender=True)
await bot.send_group_msg(group_id=int(group_id), message=f'管理员修改了此群权限:{group_data[group_id]} -> {level}')
await add_group_level.send("修改成功...", at_sender=True)
await bot.send_group_msg(
group_id=int(group_id), message=f"管理员修改了此群权限:{group_data[group_id]} -> {level}"
)
group_data[group_id] = level
with open(group_level_data, 'w', encoding='utf8') as f:
with open(group_level_data, "w", encoding="utf8") as f:
json.dump(group_data, f, ensure_ascii=False, indent=4)
logger.info(f'{event.user_id} 修改了 {group_id} 的权限:{level}')
logger.info(f"{event.user_id} 修改了 {group_id} 的权限:{level}")
@my_group_level.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if group_data.get(str(event.group_id)):
level = group_data[str(event.group_id)]
tmp = ''
tmp = ""
for plugin in plugins2info_dict:
if plugins2info_dict[plugin]['level'] > level:
plugin_name = plugins2info_dict[plugin]['cmd'][0]
if plugin_name == 'pixiv':
plugin_name = '搜图 p站排行'
tmp += f'{plugin_name}\n'
if plugins2info_dict[plugin]["level"] > level:
plugin_name = plugins2info_dict[plugin]["cmd"][0]
if plugin_name == "pixiv":
plugin_name = "搜图 p站排行"
tmp += f"{plugin_name}\n"
if tmp:
tmp = '\n目前无法使用的功能:\n' + tmp
await my_group_level.finish(f'当前群权限:{level}{tmp}')
tmp = "\n目前无法使用的功能:\n" + tmp
await my_group_level.finish(f"当前群权限:{level}{tmp}")
@what_up_group_level.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
await what_up_group_level.finish(f'[此功能用于防止内鬼,如果引起不便那真是抱歉了]\n'
f'目前提高群权限的方法:\n'
f'\t1.管理员修改权限')
await what_up_group_level.finish(
f"[此功能用于防止内鬼,如果引起不便那真是抱歉了]\n" f"目前提高群权限的方法:\n" f"\t1.管理员修改权限"
)
# 检查权限
def check_level_group(module: str, group_id: int) -> bool:
if plugins2info_dict.get(module):
if plugins2info_dict[module]["level"] > group_data[str(group_id)]:
return False
return True
+18 -22
View File
@@ -3,44 +3,40 @@ from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from nonebot.adapters.cqhttp.permission import GROUP
from configs.path_config import DATA_PATH
from utils.init_result import image
from utils.message_builder import image
import os
from pathlib import Path
try:
import ujson as json
except ModuleNotFoundError:
import json
__plugin_name__ = '查看群欢迎消息'
__plugin_name__ = "查看群欢迎消息"
__plugin_usage__ = '无'
__plugin_usage__ = "无"
view_custom_welcome = on_command('群欢迎消息', aliases={'查看群欢迎消息', '查看当前群欢迎消息'}, permission=GROUP, priority=5, block=True)
view_custom_welcome = on_command(
"群欢迎消息", aliases={"查看群欢迎消息", "查看当前群欢迎消息"}, permission=GROUP, priority=5, block=True
)
@view_custom_welcome.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
img = ''
msg = ''
if os.path.exists(DATA_PATH + f'custom_welcome_msg/{event.group_id}.jpg'):
img = image(abspath=DATA_PATH + f'custom_welcome_msg/{event.group_id}.jpg')
custom_welcome_msg_json = Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
img = ""
msg = ""
if os.path.exists(DATA_PATH + f"custom_welcome_msg/{event.group_id}.jpg"):
img = image(abspath=DATA_PATH + f"custom_welcome_msg/{event.group_id}.jpg")
custom_welcome_msg_json = (
Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
)
if custom_welcome_msg_json.exists():
data = json.load(open(custom_welcome_msg_json, 'r'))
data = json.load(open(custom_welcome_msg_json, "r"))
if data.get(str(event.group_id)):
msg = data[str(event.group_id)]
if msg.find('[at]') != -1:
msg = msg.replace('[at]', '')
if msg.find("[at]") != -1:
msg = msg.replace("[at]", "")
if img or msg:
await view_custom_welcome.finish(msg + img, at_sender=True)
else:
await view_custom_welcome.finish('当前还没有自定义群欢迎消息哦', at_sender=True)
await view_custom_welcome.finish("当前还没有自定义群欢迎消息哦", at_sender=True)
+12 -11
View File
@@ -3,7 +3,7 @@ from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, PrivateMessageEvent
from nonebot.typing import T_State
from nonebot.rule import to_me
from configs.path_config import DATA_PATH
from utils.init_result import image
from utils.message_builder import image
import os
from .data_source import create_help_img, create_group_help_img, get_plugin_help
from nonebot import require
@@ -12,25 +12,27 @@ from utils.utils import get_message_text
export = require("nonebot_plugin_manager")
__plugin_name__ = '帮助'
__plugin_name__ = "帮助"
if not os.path.exists(DATA_PATH + 'group_help/'):
os.mkdir(DATA_PATH + 'group_help/')
if not os.path.exists(DATA_PATH + "group_help/"):
os.mkdir(DATA_PATH + "group_help/")
create_help_img()
for file in os.listdir(DATA_PATH + 'group_help/'):
os.remove(DATA_PATH + 'group_help/' + file)
for file in os.listdir(DATA_PATH + "group_help/"):
os.remove(DATA_PATH + "group_help/" + file)
_help = on_command("功能", rule=to_me(), aliases={'help', '帮助'}, priority=1, block=True)
_help = on_command("功能", rule=to_me(), aliases={"help", "帮助"}, priority=1, block=True)
@_help.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
if not os.path.exists(DATA_PATH + f'group_help/{event.group_id}.png'):
if not os.path.exists(DATA_PATH + f"group_help/{event.group_id}.png"):
create_group_help_img(event.group_id)
await _help.finish(image(abspath=DATA_PATH + f'group_help/{event.group_id}.png'))
await _help.finish(
image(abspath=DATA_PATH + f"group_help/{event.group_id}.png")
)
else:
await _help.finish(get_plugin_help(msg))
@@ -39,7 +41,6 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
await _help.finish(image('help.png'))
await _help.finish(image("help.png"))
else:
await _help.finish(get_plugin_help(msg))
+57 -56
View File
@@ -1,65 +1,66 @@
# 实用
utility_help = {
'update_pic': '一些对图片的操作 --> 指令:操作图片/图片/修改图片(包含 10 种图片操作)',
'search_buff_skin_price': 'BUFF皮肤底价查询 --> 指令:查询皮肤(代理ip不得劲)',
'weather': '天气查询 --> 指令:xx天气',
'yiqing': '实时疫情数据 --> 指令:疫情查询/疫情/查询疫情',
'bt': 'bt(磁力搜索){仅支持私聊,懂的都懂} --> 指令:bt',
'reimu': '老司机必备!{仅支持私聊,懂的都懂}-> 指令:上车',
'what_anime': '靠图识番 --> 指令:识番',
'nonebot_plugin_picsearcher': '以图搜图 --> 指令:识图/这是什么/上一张图是什么',
'search_anime': '找不到想看的动漫吗? --> 指令:搜番',
'songpicker2': '来一首歌听听? --> 指令:点歌',
'epic': 'epic速速白嫖 --> 指令:epic',
'pixiv_r': 'P站排行榜直接冲 --> 指令:p站排行(可含参数)',
'pixiv_s': 'P站的图随便搜搜 --> 指令:搜图(可含参数)',
'pid_search': '通过PID搜索图片 --> 指令:p搜 [pid]',
'translate': '出国旅游助手(狗头) --> 指令:英翻/翻英/日翻/翻日/韩翻/翻韩',
'cover': '快捷的b站封面获取方式 --> 指令:b封面 [连接/av/bv/cv/直播id]'
"update_pic": "一些对图片的操作 --> 指令:操作图片/图片/修改图片(包含 10 种图片操作)",
"search_buff_skin_price": "BUFF皮肤底价查询 --> 指令:查询皮肤(代理ip不得劲)",
"weather": "天气查询 --> 指令:xx天气",
"yiqing": "实时疫情数据 --> 指令:疫情查询/疫情/查询疫情",
"bt": "bt(磁力搜索){仅支持私聊,懂的都懂} --> 指令:bt",
"reimu": "老司机必备!{仅支持私聊,懂的都懂}-> 指令:上车",
"what_anime": "靠图识番 --> 指令:识番",
"nonebot_plugin_picsearcher": "以图搜图 --> 指令:识图/这是什么/上一张图是什么",
"search_anime": "找不到想看的动漫吗? --> 指令:搜番",
"songpicker2": "来一首歌听听? --> 指令:点歌",
"epic": "epic速速白嫖 --> 指令:epic",
"pixiv_r": "P站排行榜直接冲 --> 指令:p站排行(可含参数)",
"pixiv_s": "P站的图随便搜搜 --> 指令:搜图(可含参数)",
"pid_search": "通过PID搜索图片 --> 指令:p搜 [pid]",
"translate": "出国旅游助手(狗头) --> 指令:英翻/翻英/日翻/翻日/韩翻/翻韩",
"cover": "快捷的b站封面获取方式 --> 指令:b封面 [连接/av/bv/cv/直播id]",
}
# 娱乐
entertainment_help = {
'sign_in': '签到(影响色图和开箱) --> 指令:签到/我的签到/好感度排行/好感度总榜/好感度总榜[屏蔽我/显示我]',
'send_img': '发送图片 --> 指令:美图/萝莉/壁纸/(美图/萝莉/壁纸[id])/N张图xx(N<=9)',
'send_setu': '不要小看涩图啊混蛋! --> 指令:色图/色图[id]/n张色图/n张xx色图/查色图/...(请查看 色图 帮助)',
'white2black_img': '黑白草图 --> 指令:黑白图/黑白草图',
'coser': '三次元也不戳 --> 指令:coser',
'jitang': '不喝点什么不舒服 --> 指令:鸡汤/语录',
'send_dinggong_voice': '骂我(傲娇?) --> 指令:骂老子',
'poke': '戳一戳发送语音美图萝莉图不美哉?',
'open_cases': '模拟开箱(戒赌) --> 指令:开箱(N连开箱[N<=30])/我的开箱/群开箱统计/我的金色',
'luxun': '鲁迅说过 --> 指令:鲁迅说',
'fake_msg': '构造一个假消息 --> 指令:假消息',
'shop_handle': '商店系统(初始送100金币) --> 指令:商店/我的金币/购买道具/使用道具',
'draw_card_prts': '换个地方当非酋TvT... --> 指令:方舟一井/方舟N抽(0<N<300)',
'draw_card_genshin': '提瓦特是个好地方! --> 指令:原神一井/原神N抽(0<N<180)/原神武器/角色N抽/重置原神抽卡次数',
'draw_card_pretty': '赛马娘!!!! --> 指令:赛马娘一井/赛马娘N抽/赛马娘卡一井/赛马娘卡N抽(0<N<200)',
'draw_card_guardian': '坎公骑冠剑.... --> 指令:坎公骑冠剑一井/坎公骑冠剑武器一井/坎公骑冠剑N抽/坎公骑冠剑武器N抽(0<N<300)',
'draw_card_pcr': '公主连结(国服)来几发 --> 指令:pcr一井/pcrN抽(0<N<300)',
'draw_card_azur': '我跟方舟坐狱友 --> 指令:碧蓝轻型/重型/特型N抽(0<N<300)',
'draw_card_fgo': '你就是我的马斯塔嘛 --> 指令:fgoN抽(0<N<300)',
'draw_card_onmyoji': '普通的阴阳师召唤 --> 指令:阴阳师N抽(0<N<300)',
'one_friend': '我有一个朋友想问问... --> 指令:我有一个朋友想问问xxx(内容)',
'nickname': '区区昵称! --> 指令:以后叫我xx(昵称)/我是谁/取消昵称',
'almanac': '这是一张正经的黄历 --> 指令:原神黄历',
'material_remind': '看看原神今天要刷什么 --> 指令:今日素材/今日材料/今天素材/今天材料',
'qiu_qiu_translation': '这家伙到底在说什么? --> 指令:丘丘翻译/丘丘一下/丘丘语翻译',
'query_resource_points': '地图资源速速查看 --> 指令:原神资源查询xx/原神资源列表/哪里有xx/xx在哪(xx=资源名称)',
'russian': '紧张刺激的俄罗斯轮盘 --> 指令:俄罗斯轮盘帮助',
'gold_redbag': '运气项目又来啦! --> 指令:塞红包/ 抢红包指令: 开/抢/戳一戳真寻/ 退回:退回未抢完的红包',
'poetry': '突然文艺的真寻是否搞错了什么 --> 指令:念诗/来首诗/念首诗',
'comments_163': '生了个人,我很抱歉 --> 指令:到点了/12点了/网易云热评/网易云评论',
"sign_in": "签到(影响色图和开箱) --> 指令:签到/我的签到/好感度排行/好感度总榜/好感度总榜[屏蔽我/显示我]",
"send_img": "发送图片 --> 指令:美图/萝莉/壁纸/(美图/萝莉/壁纸[id])/N张图xx(N<=9)",
"send_setu": "不要小看涩图啊混蛋! --> 指令:色图/色图[id]/n张色图/n张xx色图/查色图/...(请查看 色图 帮助)",
"white2black_img": "黑白草图 --> 指令:黑白图/黑白草图",
"coser": "三次元也不戳 --> 指令:coser",
"jitang": "不喝点什么不舒服 --> 指令:鸡汤/语录",
"send_dinggong_voice": "骂我(傲娇?) --> 指令:骂老子",
"poke": "戳一戳发送语音美图萝莉图不美哉?",
"open_cases": "模拟开箱(戒赌) --> 指令:开箱(N连开箱[N<=30])/我的开箱/群开箱统计/我的金色",
"luxun": "鲁迅说过 --> 指令:鲁迅说",
"fake_msg": "构造一个假消息 --> 指令:假消息",
"shop_handle": "商店系统(初始送100金币) --> 指令:商店/我的金币/购买道具/使用道具",
"draw_card_prts": "换个地方当非酋TvT... --> 指令:方舟一井/方舟N抽(0<N<300)",
"draw_card_genshin": "提瓦特是个好地方! --> 指令:原神一井/原神N抽(0<N<180)/原神武器/角色N抽/重置原神抽卡次数",
"draw_card_pretty": "赛马娘!!!! --> 指令:赛马娘一井/赛马娘N抽/赛马娘卡一井/赛马娘卡N抽(0<N<200)",
"draw_card_guardian": "坎公骑冠剑.... --> 指令:坎公骑冠剑一井/坎公骑冠剑武器一井/坎公骑冠剑N抽/坎公骑冠剑武器N抽(0<N<300)",
"draw_card_pcr": "公主连结(国服)来几发 --> 指令:pcr一井/pcrN抽(0<N<300)",
"draw_card_azur": "我跟方舟坐狱友 --> 指令:碧蓝轻型/重型/特型N抽(0<N<300)",
"draw_card_fgo": "你就是我的马斯塔嘛 --> 指令:fgoN抽(0<N<300)",
"draw_card_onmyoji": "普通的阴阳师召唤 --> 指令:阴阳师N抽(0<N<300)",
"one_friend": "我有一个朋友想问问... --> 指令:我有一个朋友想问问xxx(内容)",
"nickname": "区区昵称! --> 指令:以后叫我xx(昵称)/我是谁/取消昵称",
"almanac": "这是一张正经的黄历 --> 指令:原神黄历",
"material_remind": "看看原神今天要刷什么 --> 指令:今日素材/今日材料/今天素材/今天材料",
"qiu_qiu_translation": "这家伙到底在说什么? --> 指令:丘丘翻译/丘丘一下/丘丘语翻译",
"query_resource_points": "地图资源速速查看 --> 指令:原神资源查询xx[路径]/原神资源列表/哪里有xx/xx在哪(xx=资源名称)",
"russian": "紧张刺激的俄罗斯轮盘 --> 指令:俄罗斯轮盘帮助",
"gold_redbag": "运气项目又来啦! --> 指令:塞红包/ 抢红包指令: 开/抢/戳一戳真寻/ 退回:退回未抢完的红包",
"poetry": "突然文艺的真寻是否搞错了什么 --> 指令:念诗/来首诗/念首诗",
"comments_163": "生了个人,我很抱歉 --> 指令:到点了/12点了/网易云热评/网易云评论",
"pix_gallery": "偶尔也想看看美图? --> 指令:PIX [关键词/uid/pid:pid] [num]/查看pix图库 [关键词]/显示pix关键词",
}
# 其他
other_help = [
'查看当前的群欢迎消息 --> 指令:群欢迎消息',
'这是一份正经的自我介绍 --> 指令:自我介绍',
'不得看看自己权力多大? --> 指令:我的权限',
'有人记得你是什么时候加入我们的 --> 指令:我的信息',
'让我看看更新了什么 --> 指令:更新信息',
'真寻给我把话收回去! --> 指令:撤回 [id](默认0)',
'群拥有的权限 --> 指令:查看群权限',
'数据统计可视化_1 --> 指令:功能调用统计/日功能调用统计/周功能调用统计/月功能调用统计',
'数据统计可视化_2 --> 指令:周功能调用统计 [功能名称]/月功能调用统计 [功能名称]'
"查看当前的群欢迎消息 --> 指令:群欢迎消息",
"这是一份正经的自我介绍 --> 指令:自我介绍",
"不得看看自己权力多大? --> 指令:我的权限",
"有人记得你是什么时候加入我们的 --> 指令:我的信息",
"让我看看更新了什么 --> 指令:更新信息",
"真寻给我把话收回去! --> 指令:撤回 [id](默认0)",
"群拥有的权限 --> 指令:查看群权限",
"数据统计可视化_1 --> 指令:功能调用统计/日功能调用统计/周功能调用统计/月功能调用统计",
"数据统计可视化_2 --> 指令:周功能调用统计 [功能名称]/月功能调用统计 [功能名称]",
"这里是PIX图库! --> 指令:添加pix关键词 [关键词]/添加pixuid/pid [UID/PID]/我的pix关键词",
]
+99 -68
View File
@@ -1,16 +1,20 @@
from utils.img_utils import CreateImg
from utils.image_utils import CreateImg
from configs.path_config import IMAGE_PATH, DATA_PATH
import ujson as json
import os
from .config import *
from nonebot import require
from configs.config import INITIAL_OPEN_CASE_COUNT, INITIAL_SETU_PROBABILITY, ADMIN_DEFAULT_AUTH
from configs.config import (
INITIAL_OPEN_CASE_COUNT,
INITIAL_SETU_PROBABILITY,
ADMIN_DEFAULT_AUTH,
)
from configs.config import plugins2info_dict
import nonebot
export = require("nonebot_plugin_manager")
width = 1500
width = 1600
e_height = 0
u_height = 950
o_height = 1500
@@ -18,139 +22,166 @@ o_height = 1500
def create_help_img():
if os.path.exists(IMAGE_PATH + 'help.png'):
os.remove(IMAGE_PATH + 'help.png')
h = (100 + len(utility_help) * 24 + len(entertainment_help) * 24 + len(other_help) * 24) * 2
if os.path.exists(IMAGE_PATH + "help.png"):
os.remove(IMAGE_PATH + "help.png")
h = (
100
+ len(utility_help) * 24
+ len(entertainment_help) * 24
+ len(other_help) * 24
) * 2
A = CreateImg(width, h - 200, font_size=24)
e = CreateImg(width, len(entertainment_help) * 42, font_size=24)
rst = ''
rst = ""
i = 0
for cmd in entertainment_help:
rst += f'{i + 1}.{entertainment_help[cmd]}\n'
rst += f"{i + 1}.{entertainment_help[cmd]}\n"
i += 1
e.text((10, 10), '娱乐功能:')
e.text((10, 10), "娱乐功能:")
e.text((40, 40), rst)
u = CreateImg(width, len(utility_help) * 40 + 50, font_size=24, color='black')
rst = ''
u = CreateImg(width, len(utility_help) * 40 + 50, font_size=24, color="black")
rst = ""
i = 0
for cmd in utility_help:
rst += f'{i + 1}.{utility_help[cmd]}\n'
rst += f"{i + 1}.{utility_help[cmd]}\n"
i += 1
u.text((10, 10), '实用功能:', fill=(255, 255, 255))
u.text((10, 10), "实用功能:", fill=(255, 255, 255))
u.text((40, 40), rst, fill=(255, 255, 255))
o = CreateImg(width, len(other_help) * 40, font_size=24)
rst = ''
rst = ""
i = 0
for i in range(len(other_help)):
rst += f'{i + 1}.{other_help[i]}\n'
rst += f"{i + 1}.{other_help[i]}\n"
i += 1
o.text((10, 10), '其他功能:')
o.text((10, 10), "其他功能:")
o.text((40, 40), rst)
A.paste(e, (0, 0))
A.paste(u, (0, u_height))
A.paste(o, (0, o_height))
A.text((10, h * 0.68), '大部分交互功能可以通过输入‘取消’,‘算了’来取消当前交互\n对真寻说 “真寻帮助 指令名” 获取对应详细帮助\n'
'可以通过 “滴滴滴- [消息]” 联系管理员(有趣的想法尽管来吧!<还有Bug和建议>)'
'\n[群管理员请看 管理员帮助(群主与管理员自带 5 级权限)]\n\n'
'\t「如果真寻回复了一些不符合人设的话,那是因为每日白嫖的图灵次数已用完,使用的是备用接口【QAQ】」')
A.text(
(10, h * 0.68),
"大部分交互功能可以通过输入‘取消’,‘算了’来取消当前交互\n对真寻说 “真寻帮助 指令名” 获取对应详细帮助\n"
"可以通过 “滴滴滴- [消息]” 联系管理员(有趣的想法尽管来吧!<还有Bug和建议>)"
"\n[群管理员请看 管理员帮助(群主与管理员自带 5 级权限)]\n\n"
"\t「如果真寻回复了一些不符合人设的话,那是因为每日白嫖的图灵次数已用完,使用的是备用接口【QAQ】」",
)
A.save(IMAGE_PATH + 'help.png')
A.save(IMAGE_PATH + "help.png")
def create_group_help_img(group_id: int):
group_id = str(group_id)
try:
with open(DATA_PATH + 'manager/plugin_list.json', 'r', encoding='utf8') as f:
with open(DATA_PATH + "manager/plugin_list.json", "r", encoding="utf8") as f:
plugin_list = json.load(f)
except (ValueError, FileNotFoundError):
pass
h = (100 + len(utility_help) * 24 + len(entertainment_help) * 24 + len(other_help) * 24) * 2
A = CreateImg(1200, h - 200, font_size=24)
u = CreateImg(1200, len(utility_help) * 40, font_size=24, color='black')
o = CreateImg(1200, len(other_help) * 40, font_size=24)
h = (
100
+ len(utility_help) * 24
+ len(entertainment_help) * 24
+ len(other_help) * 24
) * 2
A = CreateImg(width, h - 200, font_size=24)
u = CreateImg(width, len(utility_help) * 40, font_size=24, color="black")
o = CreateImg(width, len(other_help) * 40, font_size=24)
e = CreateImg(width, len(entertainment_help) * 42, font_size=24)
rst = ''
rst = ""
i = 1
for cmd in entertainment_help.keys():
flag, dfg = parse_cmd(cmd, group_id, plugin_list)
if dfg:
cmd = rcmd(dfg)
rst += f'【{flag}】{i}.{entertainment_help[cmd]}\n'
rst += f"【{flag}】{i}.{entertainment_help[cmd]}\n"
i += 1
e.text((10, 10), '娱乐功能:')
e.text((10, 10), "娱乐功能:")
e.text((40, 40), rst)
rst = ''
rst = ""
i = 1
for cmd in utility_help.keys():
flag, dfg = parse_cmd(cmd, group_id, plugin_list)
rst += f'【{flag}】{i}.{utility_help[cmd]}\n'
rst += f"【{flag}】{i}.{utility_help[cmd]}\n"
i += 1
u.text((10, 10), '实用功能:', fill=(255, 255, 255))
u.text((10, 10), "实用功能:", fill=(255, 255, 255))
u.text((40, 40), rst, fill=(255, 255, 255))
rst = ''
rst = ""
for i in range(len(other_help)):
rst += f'{i + 1}.{other_help[i]}\n'
o.text((10, 10), '其他功能:')
rst += f"{i + 1}.{other_help[i]}\n"
o.text((10, 10), "其他功能:")
o.text((40, 40), rst)
A.paste(e, (0, 0))
A.paste(u, (0, u_height))
A.paste(o, (0, o_height))
# A.text((width, 10), f'总开关【{"√" if data["总开关"] else "×"}】')
A.text((10, h * 0.68), '大部分交互功能可以通过输入‘取消’,‘算了’来取消当前交互\n对真寻说 “真寻帮助 指令名” 获取对应详细帮助\n'
'可以通过 “滴滴滴- [消息]” 联系管理员(有趣的想法尽管来吧!<还有Bug和建议>)'
f'\n[群管理员请看 管理员帮助(群主与管理员自带 {ADMIN_DEFAULT_AUTH} 级权限)]')
A.text((10, h * 0.77), f"【注】「色图概率:好感度 + {int(INITIAL_SETU_PROBABILITY*100)}%\n"
f"\t\t每 3 点好感度 + 1次开箱,初始 {INITIAL_OPEN_CASE_COUNT} 次\n"
f"\t\t开启/关闭功能只需输入‘开启/关闭 指令名’(每个功能的第一个指令)」\n"
f"\t\t示例:开启签到\n"
f"\t\t可以通过管理员开关自动发送消息(早晚安等)\n"
f"\t\t^请查看管理员帮助^\n\n"
f"\t「如果真寻回复了一些不符合人设的话,那是因为每日白嫖的图灵次数已用完,使用的是备用接口【QAQ】」")
A.save(DATA_PATH + f'group_help/{group_id}.png')
A.text(
(10, h * 0.68),
"大部分交互功能可以通过输入‘取消’,‘算了’来取消当前交互\n对真寻说 “真寻帮助 指令名” 获取对应详细帮助\n"
"可以通过 “滴滴滴- [消息]” 联系管理员(有趣的想法尽管来吧!<还有Bug和建议>)"
f"\n[群管理员请看 管理员帮助(群主与管理员自带 {ADMIN_DEFAULT_AUTH} 级权限)]",
)
A.text(
(10, h * 0.77),
f"【注】「色图概率:好感度 + {int(INITIAL_SETU_PROBABILITY*100)}%\n"
f"\t\t每 3 点好感度 + 1次开箱,初始 {INITIAL_OPEN_CASE_COUNT} 次\n"
f"\t\t开启/关闭功能只需输入‘开启/关闭 指令名’(每个功能的第一个指令)」\n"
f"\t\t示例:开启签到\n"
f"\t\t可以通过管理员开关自动发送消息(早晚安等)\n"
f"\t\t^请查看管理员帮助^\n\n"
f"\t「如果真寻回复了一些不符合人设的话,那是因为每日白嫖的图灵次数已用完,使用的是备用接口【QAQ】」",
)
A.save(DATA_PATH + f"group_help/{group_id}.png")
def parse_cmd(cmd, group_id, plugin_list):
flag = '√'
flag = "√"
dfg = None
if cmd.find('draw_card') != -1:
lst = cmd.split('_')
cmd = lst[0] + '_' + lst[1]
if cmd.find("draw_card") != -1:
lst = cmd.split("_")
cmd = lst[0] + "_" + lst[1]
dfg = lst[-1]
elif cmd == 'pixiv_r':
cmd = 'pixiv'
dfg = 'r'
elif cmd == 'pixiv_s':
cmd = 'pixiv'
dfg = 's'
elif cmd == "pixiv_r":
cmd = "pixiv"
dfg = "r"
elif cmd == "pixiv_s":
cmd = "pixiv"
dfg = "s"
if group_id in plugin_list[cmd]:
if not plugin_list[cmd][group_id]:
flag = '×'
if cmd in ['bt', 'reimu', 'nickname']:
flag = '- '
flag = "×"
if cmd in ["bt", "reimu", "nickname"]:
flag = "- "
return flag, dfg
def rcmd(dfg):
if dfg in ['prts', 'genshin', 'pretty', 'guardian', 'pcr', 'azur', 'onmyoji', 'fgo']:
return 'draw_card_' + dfg
if dfg == 'r':
return 'pixiv_r'
if dfg == 's':
return 'pixiv_s'
if dfg in [
"prts",
"genshin",
"pretty",
"guardian",
"pcr",
"azur",
"onmyoji",
"fgo",
]:
return "draw_card_" + dfg
if dfg == "r":
return "pixiv_r"
if dfg == "s":
return "pixiv_s"
def get_plugin_help(msg: str) -> str:
plugin = None
for p in plugins2info_dict.keys():
if msg in plugins2info_dict[p]['cmd']:
if msg in plugins2info_dict[p]["cmd"]:
plugin = nonebot.plugin.get_plugin(p)
break
if plugin:
result = plugin.module.__getattribute__("__plugin_usage__")
return result
else:
return '没有此功能的帮助信息...'
return "没有此功能的帮助信息..."
+74 -83
View File
@@ -1,13 +1,25 @@
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, IgnoredException
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent, PrivateMessageEvent, GroupMessageEvent
from configs.config import BAN_RESULT, admin_plugins_auth, MALICIOUS_BAN_TIME, MALICIOUS_CHECK_TIME, MALICIOUS_BAN_COUNT
from nonebot.adapters.cqhttp import (
Bot,
MessageEvent,
PrivateMessageEvent,
GroupMessageEvent,
)
from configs.config import (
BAN_RESULT,
admin_plugins_auth,
MALICIOUS_BAN_TIME,
MALICIOUS_CHECK_TIME,
MALICIOUS_BAN_COUNT,
)
from models.ban_user import BanUser
from utils.utils import is_number, static_flmt, BanCheckLimiter
from utils.init_result import at
from utils.message_builder import at
from services.log import logger
from models.level_user import LevelUser
try:
import ujson as json
except ModuleNotFoundError:
@@ -19,32 +31,39 @@ except ModuleNotFoundError:
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if not isinstance(event, MessageEvent):
return
if matcher.type == 'message' and matcher.priority not in [1, 9]:
if await BanUser.isban(event.user_id) and str(event.user_id) not in bot.config.superusers:
if matcher.type == "message" and matcher.priority not in [1, 9]:
if (
await BanUser.is_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers
):
time = await BanUser.check_ban_time(event.user_id)
if is_number(time):
time = abs(int(time))
if time < 60:
time = str(time) + ' 秒'
time = str(time) + " 秒"
else:
time = str(int(time / 60)) + ' 分'
time = str(int(time / 60)) + " 分"
else:
time = str(time) + ' 分'
if event.message_type == 'group':
time = str(time) + " 分"
if event.message_type == "group":
if not static_flmt.check(event.user_id):
raise IgnoredException('用户处于黑名单中')
raise IgnoredException("用户处于黑名单中")
static_flmt.start_cd(event.user_id)
if matcher.priority != 9:
await bot.send_group_msg(group_id=event.group_id,
message=at(event.user_id) + BAN_RESULT + f' 在..在 {time}后才会理你喔')
await bot.send_group_msg(
group_id=event.group_id,
message=at(event.user_id) + BAN_RESULT + f" 在..在 {time}后才会理你喔",
)
else:
if not static_flmt.check(event.user_id):
raise IgnoredException('用户处于黑名单中')
raise IgnoredException("用户处于黑名单中")
static_flmt.start_cd(event.user_id)
if matcher.priority != 9:
await bot.send_private_msg(user_id=event.user_id,
message=at(event.user_id) + BAN_RESULT + f' 在..在 {time}后才会理你喔')
raise IgnoredException('用户处于黑名单中')
await bot.send_private_msg(
user_id=event.user_id,
message=at(event.user_id) + BAN_RESULT + f" 在..在 {time}后才会理你喔",
)
raise IgnoredException("用户处于黑名单中")
_blmt = BanCheckLimiter(MALICIOUS_CHECK_TIME, MALICIOUS_BAN_COUNT)
@@ -55,104 +74,76 @@ _blmt = BanCheckLimiter(MALICIOUS_CHECK_TIME, MALICIOUS_BAN_COUNT)
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, 9]:
if state["_prefix"]["raw_command"]:
# print(state["_prefix"]["raw_command"])
if _blmt.check(f'{event.user_id}{state["_prefix"]["raw_command"]}'):
if await BanUser.ban(event.user_id, 9, MALICIOUS_BAN_TIME * 60):
logger.info(f'USER {event.user_id} 触发了恶意触发检测')
logger.info(f"USER {event.user_id} 触发了恶意触发检测")
# await update_img.finish('检测到恶意触发命令,您将被封禁 30 分钟', at_sender=True)
if event.message_type == 'group':
if event.message_type == "group":
if not static_flmt.check(event.user_id):
return
static_flmt.start_cd(event.user_id)
await bot.send_group_msg(group_id=event.group_id,
message=at(event.user_id) + '检测到恶意触发命令,您将被封禁 30 分钟')
await bot.send_group_msg(
group_id=event.group_id,
message=at(event.user_id) + "检测到恶意触发命令,您将被封禁 30 分钟",
)
else:
if not static_flmt.check(event.user_id):
return
static_flmt.start_cd(event.user_id)
await bot.send_private_msg(user_id=event.user_id,
message=at(event.user_id) + '检测到恶意触发命令,您将被封禁 30 分钟')
raise IgnoredException('检测到恶意触发命令')
await bot.send_private_msg(
user_id=event.user_id,
message=at(event.user_id) + "检测到恶意触发命令,您将被封禁 30 分钟",
)
raise IgnoredException("检测到恶意触发命令")
_blmt.add(f'{event.user_id}{state["_prefix"]["raw_command"]}')
# 权限检测
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if not isinstance(event, MessageEvent):
return
if await BanUser.isban(event.user_id):
if not isinstance(event, MessageEvent) or await BanUser.is_ban(event.user_id):
return
if matcher.module in admin_plugins_auth.keys() and matcher.priority not in [1, 9]:
if event.message_type == 'group':
if not await LevelUser.check_level(event.user_id, event.group_id, admin_plugins_auth[matcher.module]):
await bot.send_group_msg(group_id=event.group_id,
message=f'{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:'
f'{admin_plugins_auth[matcher.module]}')
raise IgnoredException('权限不足')
if event.message_type == "group":
if not await LevelUser.check_level(
event.user_id, event.group_id, admin_plugins_auth[matcher.module]
):
await bot.send_group_msg(
group_id=event.group_id,
message=f"{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:"
f"{admin_plugins_auth[matcher.module]}",
)
raise IgnoredException("权限不足")
else:
if not await LevelUser.check_level(event.user_id, 0, admin_plugins_auth[matcher.module]):
await bot.send_private_msg(user_id=event.user_id,
message=f'你的权限不足喔,该功能需要的权限等级:{admin_plugins_auth[matcher.module]}')
raise IgnoredException('权限不足')
if not await LevelUser.check_level(
event.user_id, 0, admin_plugins_auth[matcher.module]
):
await bot.send_private_msg(
user_id=event.user_id,
message=f"你的权限不足喔,该功能需要的权限等级:{admin_plugins_auth[matcher.module]}",
)
raise IgnoredException("权限不足")
# 为什么AI会自己和自己聊天
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: PrivateMessageEvent, state: T_State):
if not isinstance(event, MessageEvent):
return
if event.user_id == int(bot.self_id):
raise IgnoredException('为什么AI会自己和自己聊天')
raise IgnoredException("为什么AI会自己和自己聊天")
# 有命令就别说话了
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
if matcher.type == 'message':
if state["_prefix"]["raw_command"] and matcher.module == 'ai':
raise IgnoredException('有命令就别说话了')
# _ulmt = UserExistLimiter()
#
#
# # 是否有命令正在处理
# @run_preprocessor
# async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
# if matcher.module == 'admin_bot_manage':
# return
# if event.user_id == bot.self_id:
# raise IgnoredException('自己和自己聊天?')
# print(state["_prefix"]["raw_command"])
# print(matcher.type)
# if (event.is_tome() and (state["_prefix"]["raw_command"] and matcher.type == 'message')
# and matcher.module == 'ai') or not static_group_dict[event.group_id]['总开关']:
# raise IgnoredException('Ai给爷爬?')
# # if matcher.module in ['ai']:
# # raise IgnoredException('Ai给爷爬?')
# if matcher.type == 'message' and matcher.priority not in [1, 8, 9]:
# if _ulmt.check(event.user_id):
# if event.message_type == 'group':
# await bot.send_group_msg(group_id=event.group_id, message=at(event.user_id) + '您有命令正在处理,等一哈!')
# else:
# await bot.send_private_msg(user_id=event.user_id, message='您有命令正在处理,等一哈!')
# raise IgnoredException('有命令正在处理')
# _ulmt.set_True(event.user_id)
#
#
# # 结束正在处理的命令
# @run_postprocessor
# async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
# _ulmt.set_False(event.user_id)
#
#
# # 结束正在处理的命令
# @event_preprocessor
# async def _(bot: Bot, event: Event, state: T_State):
# try:
# _ulmt.set_False(event.user_id)
# except AttributeError:
# pass
if not isinstance(event, MessageEvent):
return
if matcher.type == "message":
if state["_prefix"]["raw_command"] and matcher.module == "ai":
raise IgnoredException("有命令就别说话了")
+11 -19
View File
@@ -1,17 +1,13 @@
from nonebot import on_command
from utils.user_agent import get_user_agent
from services.log import logger
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
import aiohttp
from asyncio.exceptions import TimeoutError
try:
import ujson as json
except ModuleNotFoundError:
import json
__plugin_name__ = '鸡汤'
__plugin_usage__ = '用法: 发送’鸡汤‘,真寻亲自为你喝鸡汤'
__plugin_name__ = "鸡汤"
__plugin_usage__ = "用法: 发送’鸡汤‘,真寻亲自为你喝鸡汤"
url = "https://v2.alapi.cn/api/soul"
@@ -21,24 +17,20 @@ jitang = on_command("鸡汤", aliases={"毒鸡汤"}, priority=5, block=True)
@jitang.handle()
async def _(bot: Bot, event: Event, state: T_State):
params = {
"format": "json",
"token": "h0KuF6qNniMHGUtA"
}
async def _(bot: Bot, event: MessageEvent, state: T_State):
params = {"format": "json", "token": "h0KuF6qNniMHGUtA"}
try:
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, timeout=7, params=params) as response:
if response.status == 200:
data = await response.json()
await jitang.send(data['data']['content'])
await jitang.send(data["data"]["content"])
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 发送鸡汤:" + data['data']['content'])
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送鸡汤:" + data["data"]["content"]
)
else:
await jitang.send('鸡汤煮坏掉了...')
await jitang.send("鸡汤煮坏掉了...")
except TimeoutError:
await jitang.send("鸡汤煮超时了##", at_sender=True)
# except Exception as e:
# await jitang.send("出错啦!再试一次吧!", at_sender=True)
# logger.info(f'鸡汤error e:{e}')
+11 -31
View File
@@ -7,9 +7,9 @@ from .data_source import cancel_all_notice, save_data, get_data, set_data_value
from services.log import logger
__plugin_name__ = '查看群最后聊天时间 [Hidden]'
__plugin_name__ = "查看群最后聊天时间 [Hidden]"
__plugin_usage__ = '用法:无'
__plugin_usage__ = "用法:无"
last_chat = on_message(priority=1, block=False, permission=GROUP)
@@ -19,37 +19,17 @@ last_chat = on_message(priority=1, block=False, permission=GROUP)
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
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'])
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 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())
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()
+14 -17
View File
@@ -4,6 +4,7 @@ from models.group_remind import GroupRemind
from datetime import datetime
import time
from services.log import logger
try:
import ujson as json
except ModuleNotFoundError:
@@ -17,34 +18,36 @@ async def init():
global time_data
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
data = read_data('group_last_chat_time.json')
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'] = []
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:
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:
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]}')
logger.info(
f'自动存储 group_last_chat_time.json 时间:{str(datetime.now()).split(".")[0]}'
)
command_list = ['zwa', 'hy', 'kxcz', 'blpar', 'epic', 'pa']
command_list = ["zwa", "hy", "kxcz", "blpar", "epic", "pa", "gb"]
# 取消全部通知
@@ -53,7 +56,7 @@ async def cancel_all_notice(group_id):
for command in command_list:
if await GroupRemind.get_status(group_id, command):
await GroupRemind.set_status(group_id, command, False)
logger.info(f'关闭了 {group_id} 群的全部通知')
logger.info(f"关闭了 {group_id} 群的全部通知")
async def get_data():
@@ -66,9 +69,3 @@ async def get_data():
def set_data_value(key, value):
global time_data
time_data[key] = value
+13 -13
View File
@@ -3,15 +3,15 @@ import textwrap
from configs.path_config import IMAGE_PATH, TTF_PATH
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent
from utils.init_result import image
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from utils.message_builder import image
from services.log import logger
from utils.utils import UserExistLimiter, get_message_text
from utils.img_utils import pic2b64
from utils.image_utils import pic2b64
__plugin_name__ = '鲁迅说'
__plugin_name__ = "鲁迅说"
__plugin_usage__ = '用法:鲁迅说 [消息]'
__plugin_usage__ = "用法:鲁迅说 [消息]"
_ulmt = UserExistLimiter()
@@ -22,17 +22,17 @@ luxun = on_command("鲁迅说过", aliases={"鲁迅说"}, priority=5, block=True
@luxun.handle()
async def handle(bot: Bot, event: MessageEvent, state: T_State):
if _ulmt.check(event.user_id):
await luxun.finish('你的鲁迅正在说,等会', at_sender=True)
await luxun.finish("你的鲁迅正在说,等会", at_sender=True)
args = get_message_text(event.json())
if args:
state["content"] = args if args else '烦了,不说了'
state["content"] = args if args else "烦了,不说了"
@luxun.got("content", prompt="你让鲁迅说点啥?")
async def handle_event(bot: Bot, event: MessageEvent, state: T_State):
filename = str(event.user_id) + "_.jpg"
content = state["content"].strip()
if content.startswith(',') or content.startswith(','):
if content.startswith(",") or content.startswith(","):
content = content[1:]
_ulmt.set_True(event.user_id)
if len(content) > 20:
@@ -40,10 +40,12 @@ async def handle_event(bot: Bot, event: MessageEvent, state: T_State):
await luxun.finish("太长了, 鲁迅说不完!", at_sender=True)
else:
if len(content) >= 12:
content = content[:12] + '\n' + content[12:]
content = content[:12] + "\n" + content[12:]
img = image(b64=process_pic(content, filename))
logger.info(f"USER {event.user_id} GROUP "
f"{event.group_id if event.message_type != 'private' else 'private'} 鲁迅说过 {content}")
logger.info(
f"USER {event.user_id} GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'} 鲁迅说过 {content}"
)
await luxun.send(img)
_ulmt.set_False(event.user_id)
@@ -64,5 +66,3 @@ def process_pic(content, filename) -> str:
current_h += h + pad
draw.text((320, 400), "——鲁迅", font=font2, fill=(255, 255, 255))
return pic2b64(bk_img)
+40 -31
View File
@@ -3,30 +3,32 @@ from services.log import logger
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from configs.config import IMAGE_DIR_LIST
from utils.utils import is_number, cn2py
from configs.path_config import IMAGE_PATH
__plugin_name__ = '移动图片'
__plugin_usage__ = '移动图片帮助:\n\t' \
'1.查看列表 --> 指令: 移动图片 列表/目录\n\t' \
'2.移动图片 源 目的 id\n\t\t示例: 移动图片 色图 美图 1234'
__plugin_name__ = "移动图片"
__plugin_usage__ = (
"移动图片帮助:\n\t"
"1.查看列表 --> 指令: 移动图片 列表/目录\n\t"
"2.移动图片 源 目的 id\n\t\t示例: 移动图片 色图 美图 1234"
)
move_img = on_command('移动图片', priority=5, rule=to_me(), block=True)
move_img = on_command("移动图片", priority=5, rule=to_me(), block=True)
@move_img.args_parser
async def parse(bot: Bot, event: MessageEvent, state: T_State):
if str(event.get_message()) in ['取消', '算了']:
if str(event.get_message()) in ["取消", "算了"]:
await move_img.finish("已取消操作..", at_sender=True)
if state["_current_key"] in ['source_path', 'destination_path']:
if state["_current_key"] in ["source_path", "destination_path"]:
if str(event.get_message()) not in IMAGE_DIR_LIST:
await move_img.reject("此目录不正确,请重新输入目录!")
state[state["_current_key"]] = str(event.get_message())
if state["_current_key"] == 'id':
if state["_current_key"] == "id":
if not is_number(str(event.get_message())):
await move_img.reject("id不正确!请重新输入数字...")
state[state["_current_key"]] = str(event.get_message())
@@ -37,12 +39,17 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
raw_arg = str(event.get_message()).strip()
if raw_arg:
args = raw_arg.split(" ")
if args[0] in ['帮助']:
if args[0] in ["帮助"]:
await move_img.finish(__plugin_usage__)
if len(args) >= 3 and args[0] in IMAGE_DIR_LIST and args[1] in IMAGE_DIR_LIST and is_number(args[2]):
state['source_path'] = args[0]
state['destination_path'] = args[1]
state['id'] = args[2]
if (
len(args) >= 3
and args[0] in IMAGE_DIR_LIST
and args[1] in IMAGE_DIR_LIST
and is_number(args[2])
):
state["source_path"] = args[0]
state["destination_path"] = args[1]
state["id"] = args[2]
else:
await move_img.finish("参数错误,请重试", at_sender=True)
@@ -51,34 +58,36 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
@move_img.got("destination_path", prompt="要移动到哪个图库?")
@move_img.got("id", prompt="要移动的图片id是?")
async def _(bot: Bot, event: MessageEvent, state: T_State):
img_id = state['id']
source_path = IMAGE_PATH + cn2py(state['source_path'])
destination_path = IMAGE_PATH + cn2py(state['destination_path'])
img_id = state["id"]
source_path = IMAGE_PATH + cn2py(state["source_path"])
destination_path = IMAGE_PATH + cn2py(state["destination_path"])
max_id = len(os.listdir(source_path)) - 1
des_max_id = len(os.listdir(destination_path))
if int(img_id) > max_id or int(img_id) < 0:
await move_img.finish(f"Id超过上下限,上限:{max_id}", at_sender=True)
try:
os.rename(source_path + img_id + ".jpg", destination_path + str(des_max_id) + ".jpg")
logger.info(f"移动 {source_path}{img_id}.jpg ---> {destination_path}{des_max_id} 移动成功")
os.rename(
source_path + img_id + ".jpg", destination_path + str(des_max_id) + ".jpg"
)
logger.info(
f"移动 {source_path}{img_id}.jpg ---> {destination_path}{des_max_id} 移动成功"
)
except Exception as e:
logger.warning(f"移动 {source_path}{img_id}.jpg ---> {destination_path}{des_max_id} 移动失败 e:{e}")
logger.warning(
f"移动 {source_path}{img_id}.jpg ---> {destination_path}{des_max_id} 移动失败 e:{e}"
)
await move_img.finish(f"移动图片id:{img_id} 失败了...", at_sender=True)
if max_id > 0:
try:
os.rename(source_path + str(max_id) + ".jpg", source_path + img_id + ".jpg")
logger.info(f"{source_path}{max_id}.jpg 替换 {source_path}{img_id}.jpg 成功")
except Exception as e:
logger.warning(f"{source_path}{max_id}.jpg 替换 {source_path}{img_id}.jpg 失败 e:{e}")
logger.warning(
f"{source_path}{max_id}.jpg 替换 {source_path}{img_id}.jpg 失败 e:{e}"
)
await move_img.finish(f"替换图片id:{max_id} -> {img_id} 失败了...", at_sender=True)
logger.info(f"USER {event.user_id} GROUP {event.group_id if event.message_type != 'private' else 'private'} ->"
f" {source_path} --> {destination_path} (id:{img_id}) 移动图片成功")
logger.info(
f"USER {event.user_id} GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'} ->"
f" {source_path} --> {destination_path} (id:{img_id}) 移动图片成功"
)
await move_img.finish(f"移动图片 id:{img_id} --> id:{des_max_id}成功", at_sender=True)
+67 -56
View File
@@ -6,28 +6,34 @@ from nonebot.typing import T_State
import time
from nonebot.adapters.cqhttp.exception import ActionFailed
from configs.path_config import DATA_PATH, IMAGE_PATH
from utils.img_utils import get_img_hash
from utils.image_utils import get_img_hash
from services.log import logger
import aiohttp
import aiofiles
from configs.config import MUTE_DEFAULT_COUNT, MUTE_DEFAULT_TIME, MUTE_DEFAULT_DURATION
try:
import ujson as json
except ModuleNotFoundError:
import json
__plugin_name__ = '刷屏禁言'
__plugin_name__ = "刷屏禁言"
__plugin_usage__ = '刷屏禁言检测'
__plugin_usage__ = "刷屏禁言检测"
mute = on_message(priority=1, block=False)
mute_setting = on_command('mute_setting', aliases={'设置检测时间', '设置检测次数', '设置禁言时长', '刷屏检测设置'}, permission=GROUP, block=True)
mute_setting = on_command(
"mute_setting",
aliases={"设置检测时间", "设置检测次数", "设置禁言时长", "刷屏检测设置"},
permission=GROUP,
block=True,
)
def get_data():
try:
with open(DATA_PATH + 'group_mute_data.json', 'r', encoding='utf8') as f:
with open(DATA_PATH + "group_mute_data.json", "r", encoding="utf8") as f:
data = json.load(f)
except (ValueError, FileNotFoundError):
data = {}
@@ -36,16 +42,18 @@ def get_data():
def save_data():
global mute_data
with open(DATA_PATH + 'group_mute_data.json', 'w', encoding='utf8') as f:
with open(DATA_PATH + "group_mute_data.json", "w", encoding="utf8") as f:
json.dump(mute_data, f, indent=4)
async def download_img_and_hash(url, group_id):
async with aiohttp.ClientSession() as session:
async with session.get(url, proxy=get_local_proxy(), timeout=10) as response:
async with aiofiles.open(IMAGE_PATH + f'temp/mute_{group_id}_img.jpg', 'wb') as f:
async with aiofiles.open(
IMAGE_PATH + f"temp/mute_{group_id}_img.jpg", "wb"
) as f:
await f.write(await response.read())
return str(get_img_hash(IMAGE_PATH + f'temp/mute_{group_id}_img.jpg'))
return str(get_img_hash(IMAGE_PATH + f"temp/mute_{group_id}_img.jpg"))
mute_dict = {}
@@ -57,44 +65,48 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
group_id = str(event.group_id)
msg = get_message_text(event.json())
imgs = get_message_imgs(event.json())
img_hash = ''
img_hash = ""
for img in imgs:
img_hash += await download_img_and_hash(img, event.group_id)
msg += img_hash
if not mute_data.get(group_id):
mute_data[group_id] = {
'count': MUTE_DEFAULT_COUNT,
'time': MUTE_DEFAULT_TIME,
'duration': MUTE_DEFAULT_DURATION
"count": MUTE_DEFAULT_COUNT,
"time": MUTE_DEFAULT_TIME,
"duration": MUTE_DEFAULT_DURATION,
}
if not mute_dict.get(event.user_id):
mute_dict[event.user_id] = {
'time': time.time(),
'count': 1,
'msg': msg
}
mute_dict[event.user_id] = {"time": time.time(), "count": 1, "msg": msg}
else:
if state["_prefix"]["raw_command"] or not msg:
return
if msg and msg.find(mute_dict[event.user_id]['msg']) != -1:
mute_dict[event.user_id]['count'] += 1
if msg and msg.find(mute_dict[event.user_id]["msg"]) != -1:
mute_dict[event.user_id]["count"] += 1
else:
mute_dict[event.user_id]['time'] = time.time()
mute_dict[event.user_id]['count'] = 1
mute_dict[event.user_id]['msg'] = msg
if time.time() - mute_dict[event.user_id]['time'] > mute_data[group_id]['time']:
mute_dict[event.user_id]['time'] = time.time()
mute_dict[event.user_id]['count'] = 1
if mute_dict[event.user_id]['count'] > mute_data[group_id]['count'] and\
time.time() - mute_dict[event.user_id]['time'] < mute_data[group_id]['time']:
mute_dict[event.user_id]["time"] = time.time()
mute_dict[event.user_id]["count"] = 1
mute_dict[event.user_id]["msg"] = msg
if time.time() - mute_dict[event.user_id]["time"] > mute_data[group_id]["time"]:
mute_dict[event.user_id]["time"] = time.time()
mute_dict[event.user_id]["count"] = 1
if (
mute_dict[event.user_id]["count"] > mute_data[group_id]["count"]
and time.time() - mute_dict[event.user_id]["time"]
< mute_data[group_id]["time"]
):
try:
if mute_data[group_id]['duration'] != 0:
await bot.set_group_ban(group_id=event.group_id, user_id=event.user_id,
duration=mute_data[group_id]['duration'])
await mute.send('检测到恶意刷屏,真寻要把你关进小黑屋!', at_sender=True)
mute_dict[event.user_id]['count'] = 0
logger.info(f'USER {event.user_id} GROUP {event.group_id} '
f'检测刷屏 被禁言 {mute_data[group_id]["duration"] / 60} 分钟')
if mute_data[group_id]["duration"] != 0:
await bot.set_group_ban(
group_id=event.group_id,
user_id=event.user_id,
duration=mute_data[group_id]["duration"],
)
await mute.send("检测到恶意刷屏,真寻要把你关进小黑屋!", at_sender=True)
mute_dict[event.user_id]["count"] = 0
logger.info(
f"USER {event.user_id} GROUP {event.group_id} "
f'检测刷屏 被禁言 {mute_data[group_id]["duration"] / 60} 分钟'
)
except ActionFailed:
pass
@@ -103,29 +115,28 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
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": 10, "time": 7, "duration": 0}
msg = get_message_text(event.json())
if state["_prefix"]["raw_command"] == '刷屏检测设置':
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'【在规定时间内发送相同消息超过最大次数则禁言\n当禁言时长为0时关闭此功能】')
if state["_prefix"]["raw_command"] == "刷屏检测设置":
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"【在规定时间内发送相同消息超过最大次数则禁言\n当禁言时长为0时关闭此功能】"
)
if not is_number(msg):
await mute.finish('设置的参数必须是数字啊!', at_sender=True)
if state["_prefix"]["raw_command"] == '设置检测时间':
mute_data[group_id]['time'] = int(msg)
msg += '秒'
if state["_prefix"]["raw_command"] == '设置检测次数':
mute_data[group_id]['count'] = int(msg)
msg += ' 次'
if state["_prefix"]["raw_command"] == '设置禁言时长':
mute_data[group_id]['duration'] = int(msg) * 60
msg += ' 分钟'
await mute.finish("设置的参数必须是数字啊!", at_sender=True)
if state["_prefix"]["raw_command"] == "设置检测时间":
mute_data[group_id]["time"] = int(msg)
msg += "秒"
if state["_prefix"]["raw_command"] == "设置检测次数":
mute_data[group_id]["count"] = int(msg)
msg += " 次"
if state["_prefix"]["raw_command"] == "设置禁言时长":
mute_data[group_id]["duration"] = int(msg) * 60
msg += " 分钟"
await mute_setting.send(f'刷屏检测:{state["_prefix"]["raw_command"]}为 {msg}')
logger.info(f'USER {event.user_id} GROUP {group_id} {state["_prefix"]["raw_command"]}:{msg}')
logger.info(
f'USER {event.user_id} GROUP {group_id} {state["_prefix"]["raw_command"]}:{msg}'
)
save_data()
+6 -9
View File
@@ -6,15 +6,12 @@ from models.group_member_info import GroupInfoUser
from datetime import timedelta
from models.level_user import LevelUser
__plugin_name__ = '更新群组成员列表 [Hidden]'
__plugin_usage__ = (
'用法:\n'
'更新群员的信息'
)
__plugin_name__ = "更新群组成员列表 [Hidden]"
__plugin_usage__ = "用法:\n" "更新群员的信息"
get_my_group_info = on_command("我的信息", permission=GROUP, priority=1, block=True)
my_level = on_command('我的权限', permission=GROUP, priority=5, block=True)
my_level = on_command("我的权限", permission=GROUP, priority=5, block=True)
@get_my_group_info.handle()
@@ -24,7 +21,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
async def get_member_info(user_qq: int, group_id: int) -> str:
user = await GroupInfoUser.select_member_info(user_qq, group_id)
user = await GroupInfoUser.get_member_info(user_qq, group_id)
if user is None:
return "该群员不在列表中,请更新群成员信息"
result = ""
@@ -36,5 +33,5 @@ async def get_member_info(user_qq: int, group_id: int) -> str:
@my_level.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if (level := await LevelUser.get_user_level(event.user_id, event.group_id)) == -1:
await my_level.finish('您目前没有任何权限了,硬要说的话就是0吧~', at_sender=True)
await my_level.finish(f'您目前的权限等级:{level}', at_sender=True)
await my_level.finish("您目前没有任何权限了,硬要说的话就是0吧~", at_sender=True)
await my_level.finish(f"您目前的权限等级:{level}", at_sender=True)
+122 -113
View File
@@ -10,166 +10,175 @@ from models.ban_user import BanUser
from services.log import logger
__plugin_name__ = '昵称系统'
__plugin_name__ = "昵称系统"
__plugin_usage__ = '用法:\n' \
'以后叫我 [名称]\n' \
'真寻我是谁'
__plugin_usage__ = "用法:\n" "以后叫我 [名称]\n" "真寻我是谁"
nickname = on_command('nickname',
aliases={'以后叫我', '以后请叫我', '称呼我', '以后请称呼我', '以后称呼我', '叫我', '请叫我'},
rule=to_me(), priority=5, block=True)
nickname = on_command(
"nickname",
aliases={"以后叫我", "以后请叫我", "称呼我", "以后请称呼我", "以后称呼我", "叫我", "请叫我"},
rule=to_me(),
priority=5,
block=True,
)
my_nickname = on_command('my_name', aliases={'我叫什么', '我是谁', '我的名字'}, rule=to_me(), priority=5, block=True)
my_nickname = on_command(
"my_name", aliases={"我叫什么", "我是谁", "我的名字"}, rule=to_me(), priority=5, block=True
)
cancel_nickname = on_command('取消昵称', rule=to_me(), priority=5, block=True)
cancel_nickname = on_command("取消昵称", rule=to_me(), priority=5, block=True)
@nickname.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
await nickname.finish('叫你空白?叫你虚空?叫你无名??', at_sender=True)
await nickname.finish("叫你空白?叫你虚空?叫你无名??", at_sender=True)
if len(msg) > 10:
await nickname.finish('昵称可不能超过10个字!', at_sender=True)
if await GroupInfoUser.set_group_member_nickname(event.user_id, event.group_id, msg):
await nickname.finish("昵称可不能超过10个字!", at_sender=True)
if await GroupInfoUser.set_group_member_nickname(
event.user_id, event.group_id, msg
):
if len(msg) < 5:
if random.random() < 0.5:
msg = "~".join(msg)
await nickname.send(random.choice([
'好啦好啦,我知道啦,{},以后就这么叫你吧',
'嗯嗯,小真寻记住你的昵称了哦,{}',
'好突然,突然要叫你昵称什么的...{}..',
'小真寻会好好记住的{}的,放心吧',
'好..好.,那窝以后就叫你{}了.'
]).format(msg))
logger.info(f'USER {event.user_id} GROUP {event.group_id} 设置群昵称 {msg}')
await nickname.send(
random.choice(
[
"好啦好啦,我知道啦,{},以后就这么叫你吧",
"嗯嗯,小真寻记住你的昵称了哦,{}",
"好突然,突然要叫你昵称什么的...{}..",
"小真寻会好好记住的{}的,放心吧",
"好..好.,那窝以后就叫你{}了.",
]
).format(msg)
)
logger.info(f"USER {event.user_id} GROUP {event.group_id} 设置群昵称 {msg}")
else:
await nickname.send('设置昵称失败,请更新群组成员信息!', at_sender=True)
logger.warning(f'USER {event.user_id} GROUP {event.group_id} 设置群昵称 {msg} 失败')
await nickname.send("设置昵称失败,请更新群组成员信息!", at_sender=True)
logger.warning(f"USER {event.user_id} GROUP {event.group_id} 设置群昵称 {msg} 失败")
@nickname.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
await nickname.finish('叫你空白?叫你虚空?叫你无名??', at_sender=True)
await nickname.finish("叫你空白?叫你虚空?叫你无名??", at_sender=True)
if len(msg) > 10:
await nickname.finish('不要超过10个字!', at_sender=True)
await nickname.finish("不要超过10个字!", at_sender=True)
if await FriendUser.set_friend_nickname(event.user_id, msg):
await nickname.send(random.choice([
'好啦好啦,我知道啦,{},以后就这么叫你吧',
'嗯嗯,小真寻记住你的昵称了哦,{}',
'好突然,突然要叫你昵称什么的...{}..',
'小真寻会好好记住的{}的,放心吧',
'好..好.,那窝以后就叫你{}了.'
]).format(msg))
logger.info(f'USER {event.user_id} 设置昵称 {msg}')
await nickname.send(
random.choice(
[
"好啦好啦,我知道啦,{},以后就这么叫你吧",
"嗯嗯,小真寻记住你的昵称了哦,{}",
"好突然,突然要叫你昵称什么的...{}..",
"小真寻会好好记住的{}的,放心吧",
"好..好.,那窝以后就叫你{}了.",
]
).format(msg)
)
logger.info(f"USER {event.user_id} 设置昵称 {msg}")
else:
await nickname.send('设置昵称失败了,明天再来试一试!或联系管理员更新好友!', at_sender=True)
logger.warning(f'USER {event.user_id} 设置昵称 {msg} 失败')
await nickname.send("设置昵称失败了,明天再来试一试!或联系管理员更新好友!", at_sender=True)
logger.warning(f"USER {event.user_id} 设置昵称 {msg} 失败")
@my_nickname.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
try:
nickname = await GroupInfoUser.get_group_member_nickname(event.user_id, event.group_id)
nickname_ = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
except AttributeError:
nickname = ''
if nickname:
await my_nickname.send(random.choice([
'我肯定记得你啊,你是{}啊',
'我不会忘记你的,你也不要忘记我!{}',
'哼哼,真寻记忆力可是很好的,{}',
'嗯?你是失忆了嘛...{}..',
'不要小看真寻的记忆力啊!笨蛋{}!QAQ',
'哎?{}..怎么了吗..突然这样问..'
]).format(nickname))
nickname_ = ""
if nickname_:
await my_nickname.send(
random.choice(
[
"我肯定记得你啊,你是{}啊",
"我不会忘记你的,你也不要忘记我!{}",
"哼哼,真寻记忆力可是很好的,{}",
"嗯?你是失忆了嘛...{}..",
"不要小看真寻的记忆力啊!笨蛋{}!QAQ",
"哎?{}..怎么了吗..突然这样问..",
]
).format(nickname_)
)
else:
try:
nickname = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
except AttributeError:
nickname = event.user_id
await my_nickname.finish(random.choice([
'对不起,我只记得一串神秘代码..{}\n【群管理快更新群组成员信息!】'
]).format(nickname))
await my_nickname.send(random.choice([
'没..没有昵称嘛,{}',
'啊,你是{}啊,我想叫你的昵称!',
'是{}啊,有什么事吗?',
'你是{}?'
]).format(nickname))
nickname_ = event.sender.card if event.sender.card else event.sender.nickname
await my_nickname.send(
random.choice(
["没..没有昵称嘛,{}", "啊,你是{}啊,我想叫你的昵称!", "是{}啊,有什么事吗?", "你是{}?"]
).format(nickname_)
)
@my_nickname.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
nickname = await FriendUser.get_friend_nickname(event.user_id)
if nickname:
await my_nickname.send(random.choice([
'我肯定记得你啊,你是{}啊',
'我不会忘记你的,你也不要忘记我!{}',
'哼哼,真寻记忆力可是很好的,{}',
'嗯?你是失忆了嘛...{}..',
'不要小看真寻的记忆力啊!笨蛋{}!QAQ',
'哎?{}..怎么了吗..突然这样问..'
]).format(nickname))
nickname_ = await FriendUser.get_friend_nickname(event.user_id)
if nickname_:
await my_nickname.send(
random.choice(
[
"我肯定记得你啊,你是{}啊",
"我不会忘记你的,你也不要忘记我!{}",
"哼哼,真寻记忆力可是很好的,{}",
"嗯?你是失忆了嘛...{}..",
"不要小看真寻的记忆力啊!笨蛋{}!QAQ",
"哎?{}..怎么了吗..突然这样问..",
]
).format(nickname_)
)
else:
nickname = await FriendUser.get_user_name(event.user_id)
if nickname:
await my_nickname.send(random.choice([
'没..没有昵称嘛,{}',
'啊,你是{}啊,我想叫你的昵称!',
'是{}啊,有什么事吗?',
'你是{}?'
]).format(nickname))
else:
nickname = event.user_id
await my_nickname.finish(random.choice([
'对不起,我只记得一串神秘代码..{}\n【火速联系管理员更新好友列表!】'
]).format(nickname))
nickname_ = (await bot.get_stranger_info(user_id=event.user_id))["nickname"]
await my_nickname.send(
random.choice(
["没..没有昵称嘛,{}", "啊,你是{}啊,我想叫你的昵称!", "是{}啊,有什么事吗?", "你是{}?"]
).format(nickname_)
)
@cancel_nickname.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
nickname = await GroupInfoUser.get_group_member_nickname(event.user_id, event.group_id)
if nickname:
await cancel_nickname.send(random.choice([
'呜..真寻睡一觉就会忘记的..和梦一样..{}',
'窝知道了..{}..',
'是真寻哪里做的不好嘛..好吧..晚安{}',
'呃,{},下次我绝对绝对绝对不会再忘记你!',
'可..可恶!{}!太可恶了!呜'
]).format(nickname))
await GroupInfoUser.set_group_member_nickname(event.user_id, event.group_id, '')
nickname_ = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
if nickname_:
await cancel_nickname.send(
random.choice(
[
"呜..真寻睡一觉就会忘记的..和梦一样..{}",
"窝知道了..{}..",
"是真寻哪里做的不好嘛..好吧..晚安{}",
"呃,{},下次我绝对绝对绝对不会再忘记你!",
"可..可恶!{}!太可恶了!呜",
]
).format(nickname_)
)
await GroupInfoUser.set_group_member_nickname(event.user_id, event.group_id, "")
await BanUser.ban(event.user_id, 9, 60)
else:
await cancel_nickname.send('你在做梦吗?你没有昵称啊', at_sender=True)
await cancel_nickname.send("你在做梦吗?你没有昵称啊", at_sender=True)
@cancel_nickname.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
nickname = await FriendUser.get_user_name(event.user_id)
if nickname:
await cancel_nickname.send(random.choice([
'呜..真寻睡一觉就会忘记的..和梦一样..{}',
'窝知道了..{}..',
'是真寻哪里做的不好嘛..好吧..晚安{}',
'呃,{},下次我绝对绝对绝对不会再忘记你!',
'可..可恶!{}!太可恶了!呜'
]).format(nickname))
nickname_ = await FriendUser.get_friend_nickname(event.user_id)
if nickname_:
await cancel_nickname.send(
random.choice(
[
"呜..真寻睡一觉就会忘记的..和梦一样..{}",
"窝知道了..{}..",
"是真寻哪里做的不好嘛..好吧..晚安 {}",
"呃,{},下次我绝对绝对绝对不会再忘记你!",
"可..可恶!{}!太可恶了!呜",
]
).format(nickname_)
)
await FriendUser.get_user_name(event.user_id)
await BanUser.ban(event.user_id, 9, 60)
else:
await cancel_nickname.send('你在做梦吗?你没有昵称啊', at_sender=True)
await cancel_nickname.send("你在做梦吗?你没有昵称啊", at_sender=True)
+26 -25
View File
@@ -3,7 +3,13 @@ from nonebot.matcher import Matcher
from nonebot.typing import T_State
from nonebot.exception import IgnoredException
from nonebot.message import run_preprocessor
from nonebot.adapters.cqhttp import Event, Bot, GroupMessageEvent, PrivateMessageEvent, MessageEvent
from nonebot.adapters.cqhttp import (
Event,
Bot,
GroupMessageEvent,
PrivateMessageEvent,
MessageEvent,
)
from configs.config import plugins2info_dict
from utils.utils import FreqLimiter
from models.ban_user import BanUser
@@ -19,7 +25,6 @@ from .parser import npm_parser
export = export()
export.block_plugin = block_plugin
export.unblock_plugin = unblock_plugin
export.unblock_plugin = unblock_plugin
export.get_group_plugin_list = get_group_plugin_list
# 注册 shell_like 事件响应器
@@ -39,37 +44,35 @@ async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
plugin_list = auto_update_plugin_list(loaded_plugin_list)
# 无视本插件的 Matcher
if plugin not in plugins2info_dict or matcher.priority in [1, 9] or await BanUser.isban(event.user_id):
if (
plugin not in plugins2info_dict
or matcher.priority in [1, 9]
or await BanUser.is_ban(event.user_id)
):
return
if isinstance(event, PrivateMessageEvent) and plugin_list[plugin]["default"]:
return
try:
if isinstance(event, PrivateMessageEvent) and plugin_list[plugin]["default"]:
return
except:
pass
# print(matcher.module)
# print(f'plugin_list[plugin]["default"] = {plugin_list[plugin]["default"]}')
# print(f'{matcher.module} -> this is hook')
if not plugin_list[plugin]["default"]:
if event.message_type == 'group':
if str(event.user_id) in bot.config.superusers:
return
if isinstance(event, GroupMessageEvent):
if flmt.check(event.group_id):
flmt.start_cd(event.group_id)
await bot.send_group_msg(group_id=event.group_id, message='此功能正在维护...')
await bot.send_group_msg(group_id=event.group_id, message="此功能正在维护...")
else:
if flmt.check(event.user_id):
flmt.start_cd(event.user_id)
await bot.send_private_msg(user_id=event.user_id, message='此功能正在维护...')
await bot.send_private_msg(user_id=event.user_id, message="此功能正在维护...")
raise IgnoredException(f"Nonebot Plugin Manager has blocked {plugin} !")
# print(plugin_list[plugin])
# print(group_id)
# print(plugin_list[plugin][group_id])
# print(not plugin_list[plugin][group_id])
if group_id in plugin_list[plugin]:
if not plugin_list[plugin][group_id]:
if plugin != 'ai' and matcher.type == 'message':
if plugin != "ai" and matcher.type == "message":
if flmt.check(event.group_id):
flmt.start_cd(event.group_id)
await bot.send_group_msg(group_id=event.group_id, message='该群未开启此功能..')
await bot.send_group_msg(
group_id=event.group_id, message="该群未开启此功能.."
)
raise IgnoredException(f"Nonebot Plugin Manager has blocked {plugin} !")
@@ -80,7 +83,7 @@ async def _(bot: Bot, event: Event, state: T_State):
is_admin = _is_admin(event)
is_superuser = _is_superuser(bot, event)
if group_id == 0:
group_id = 'default'
group_id = "default"
if hasattr(args, "handle"):
await plugin_manager.finish(args.handle(args, group_id, is_admin, is_superuser))
@@ -116,6 +119,4 @@ def _is_superuser(bot: Bot, event: Event) -> bool:
return str(event.user_id) in bot.config.superusers
plugins_dict = {
}
plugins_dict = {}
+10 -10
View File
@@ -19,12 +19,9 @@ from .trace import get_des as get_des_trace
from .yandex import get_des as get_des_yandex
__plugin_name__ = '识图'
__plugin_name__ = "识图"
__plugin_usage__ = '用法:识图 [参数](默认nao) [图片]\n' \
'参数列表:\n' \
'\t1.nao\n' \
'\t2.asc'
__plugin_usage__ = "用法:识图 [参数](默认nao) [图片]\n" "参数列表:\n" "\t1.nao\n" "\t2.asc"
async def get_des(url: str, mode: str, user_id: int):
@@ -60,8 +57,8 @@ setu = on_command("识图", aliases={"search"}, block=True, priority=5)
async def handle_first_receive(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
imgs = get_message_imgs(event.json())
if msg in ['帮助']:
await setu.finish('示例:\n\t识图 (图片)\n\t识图asc (图片)')
if msg in ["帮助"]:
await setu.finish("示例:\n\t识图 (图片)\n\t识图asc (图片)")
if imgs:
state["setu"] = imgs[0]
if msg:
@@ -73,6 +70,7 @@ async def handle_first_receive(bot: Bot, event: MessageEvent, state: T_State):
# async def get_func(bot: Bot, event: MessageEvent, state: dict):
# pass
@setu.args_parser
async def get_setu(bot: Bot, event: MessageEvent, state: T_State):
imgs = get_message_imgs(event.json())
@@ -80,7 +78,7 @@ async def get_setu(bot: Bot, event: MessageEvent, state: T_State):
if not imgs:
await setu.reject()
if msg:
state['mod'] = msg
state["mod"] = msg
state["setu"] = imgs[0]
@@ -100,8 +98,10 @@ async def get_setu(bot: Bot, event: MessageEvent, state: T_State):
if idx == MAX_FIND_IMG_COUNT:
break
idx += 1
logger.info(f"(USER {event.user_id}, GROUP "
f"{event.group_id if event.message_type != 'private' else 'private'}) 识图:{url}")
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if event.message_type != 'private' else 'private'}) 识图:{url}"
)
# image_data: List[Tuple] = await get_pic_from_url(url)
# await setu.finish("hso")
except IndexError:
@@ -6,7 +6,7 @@ from utils.utils import get_local_proxy
from utils.user_agent import get_user_agent
from configs.path_config import IMAGE_PATH
from asyncio.exceptions import TimeoutError
from utils.init_result import image
from utils.message_builder import image
from lxml.html import fromstring
import aiohttp
@@ -6,7 +6,7 @@ from utils.utils import get_local_proxy
from utils.user_agent import get_user_agent
from configs.path_config import IMAGE_PATH
from asyncio.exceptions import TimeoutError
from utils.init_result import image
from utils.message_builder import image
import aiohttp
from lxml.html import fromstring
+23 -21
View File
@@ -5,6 +5,7 @@ from nonebot.rule import to_me
from nonebot.typing import T_State, T_CalledAPIHook
from .config import Config
global_config = get_driver().config
withdraw_config = Config(**global_config.dict())
@@ -12,33 +13,34 @@ msg_ids = {}
max_size = withdraw_config.withdraw_max_size
__plugin_name__ = '撤回'
__plugin_name__ = "撤回"
__plugin_usage__ = '用法:撤回 [消息位置](默认0)\n' \
'示例:\n' \
'\t撤回0 -> 撤回倒数第一条消息(即最新发送的消息)' \
'\t撤回1 -> 撤回倒数第2条消息'
__plugin_usage__ = (
"用法:撤回 [消息位置](默认0)\n" "示例:\n" "\t撤回0 -> 撤回倒数第一条消息(即最新发送的消息)" "\t撤回1 -> 撤回倒数第2条消息"
)
def get_key(msg_type, id):
return f'{msg_type}_{id}'
return f"{msg_type}_{id}"
async def save_msg_id(bot: Bot, e: Exception, api: str, data: Dict[str, Any], result: Any) -> T_CalledAPIHook:
async def save_msg_id(
bot: Bot, e: Exception, api: str, data: Dict[str, Any], result: Any
) -> T_CalledAPIHook:
try:
if api == 'send_msg':
msg_type = data['message_type']
id = data['group_id'] if msg_type == 'group' else data['user_id']
elif api == 'send_private_msg':
msg_type = 'private'
id = data['user_id']
elif api == 'send_group_msg':
msg_type = 'group'
id = data['group_id']
if api == "send_msg":
msg_type = data["message_type"]
id = data["group_id"] if msg_type == "group" else data["user_id"]
elif api == "send_private_msg":
msg_type = "private"
id = data["user_id"]
elif api == "send_group_msg":
msg_type = "group"
id = data["group_id"]
else:
return
key = get_key(msg_type, id)
msg_id = result['message_id']
msg_id = result["message_id"]
if key not in msg_ids:
msg_ids[key] = []
@@ -52,16 +54,16 @@ async def save_msg_id(bot: Bot, e: Exception, api: str, data: Dict[str, Any], re
Bot._called_api_hook.add(save_msg_id)
withdraw = on_command('withdraw', aliases={'撤回'}, rule=to_me(), priority=1, block=True)
withdraw = on_command("withdraw", aliases={"撤回"}, rule=to_me(), priority=1, block=True)
@withdraw.handle()
async def _(bot: Bot, event: Event, state: T_State):
if isinstance(event, GroupMessageEvent):
msg_type = 'group'
msg_type = "group"
id = event.group_id
elif isinstance(event, PrivateMessageEvent):
msg_type = 'private'
msg_type = "private"
id = event.user_id
else:
return
@@ -80,4 +82,4 @@ async def _(bot: Bot, event: Event, state: T_State):
await bot.delete_msg(message_id=msg_ids[key][idx])
msg_ids[key].pop(idx)
except:
await withdraw.finish('撤回失败,可能已超时')
await withdraw.finish("撤回失败,可能已超时")
+25 -19
View File
@@ -1,4 +1,3 @@
import aiohttp
from utils.user_agent import get_user_agent
from io import BytesIO
@@ -7,20 +6,23 @@ from nonebot import on_regex
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from utils.utils import get_message_text, get_local_proxy, get_message_at
from utils.init_result import image
from utils.message_builder import image
import re
from utils.img_utils import CreateImg
from utils.image_utils import CreateImg
__plugin_name__ = '我有一个朋友'
__plugin_name__ = "我有一个朋友"
__plugin_usage__ = '用法:我有一个朋友说/问 [消息] [at](不艾特则群员随机)'
__plugin_usage__ = "用法:我有一个朋友说/问 [消息] [at](不艾特则群员随机)"
one_friend = on_regex('^我.*?朋友.*?(想问问|说|让我问问|想问|让我问|想知道|让我帮他问问|让我'
'帮他问|让我帮忙问|让我帮忙问问|问).*', priority=5, block=True)
one_friend = on_regex(
"^我.*?朋友.*?(想问问|说|让我问问|想问|让我问|想知道|让我帮他问问|让我" "帮他问|让我帮忙问|让我帮忙问问|问).*",
priority=5,
block=True,
)
async def get_pic(qq):
url = f'http://q1.qlogo.cn/g?b=qq&nk={qq}&s=100'
url = f"http://q1.qlogo.cn/g?b=qq&nk={qq}&s=100"
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, proxy=get_local_proxy(), timeout=5) as response:
return await response.read()
@@ -31,27 +33,31 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
msg = get_message_text(event.json())
qq = get_message_at(event.json())
if not qq:
qq = choice([x['user_id'] for x in
await bot.get_group_member_list(self_id=event.self_id, group_id=event.group_id)])
qq = choice(
[
x["user_id"]
for x in await bot.get_group_member_list(
self_id=event.self_id, group_id=event.group_id
)
]
)
else:
qq = qq[0]
msg = re.search(r'^我.*?朋友.*?'
r'(想问问|说|让我问问|想问|让我问|想知道|让我帮他问问|让我帮他问|让我帮忙问|让我帮忙问问|问)(.*)',
msg)
msg = re.search(
r"^我.*?朋友.*?" r"(想问问|说|让我问问|想问|让我问|想知道|让我帮他问问|让我帮他问|让我帮忙问|让我帮忙问问|问)(.*)", msg
)
msg = msg.group(2)
if not msg:
msg = '都不知道问什么'
msg = msg.replace('他', '我').replace('她', '我').replace('它', '我')
msg = "都不知道问什么"
msg = msg.replace("他", "我").replace("她", "我").replace("它", "我")
ava = CreateImg(100, 100, background=BytesIO(await get_pic(qq)))
ava.circle()
text = CreateImg(60, 30, font_size=30)
text.text((0, 0), '朋友')
text.text((0, 0), "朋友")
# text.show()
A = CreateImg(700, 150, font_size=25, color='white')
A = CreateImg(700, 150, font_size=25, color="white")
A.paste(ava, (30, 25), True)
A.paste(text, (150, 40))
A.text((150, 85), msg, (125, 125, 125))
await one_friend.send(image(b64=A.pic2bs4()))
+73 -70
View File
@@ -7,28 +7,34 @@ from nonebot.permission import SUPERUSER
import random
from nonebot.plugin import MatcherGroup
import re
from .open_cases_c import open_case, total_open_statistics, group_statistics, my_knifes_name, open_shilian_case
from .open_cases_c import (
open_case,
total_open_statistics,
group_statistics,
my_knifes_name,
open_shilian_case,
)
from .utils import util_get_buff_price, util_get_buff_img, update_count_daily
__plugin_name__ = '开箱'
__plugin_name__ = "开箱"
__plugin_usage__ = (
'用法:\n'
'看看你的人品罢了\n'
'目前只支持\n\t'
'1.狂牙大行动武器箱\n\t'
'2.突围大行动武器箱\n\t'
'3.命悬一线武器箱\n\t'
'4.裂空武器箱\n\t'
'5.光谱武器箱\n'
'示例:小真寻开箱 突围大行动(不输入指定武器箱则随机)\n'
'示例:我的开箱(开箱统计)\n'
'示例:群开箱统计\n'
'示例:我的金色'
"用法:\n"
"看看你的人品罢了\n"
"目前只支持\n\t"
"1.狂牙大行动武器箱\n\t"
"2.突围大行动武器箱\n\t"
"3.命悬一线武器箱\n\t"
"4.裂空武器箱\n\t"
"5.光谱武器箱\n"
"示例:小真寻开箱 突围大行动(不输入指定武器箱则随机)\n"
"示例:我的开箱(开箱统计)\n"
"示例:群开箱统计\n"
"示例:我的金色"
)
_flmt = FreqLimiter(3)
cases_name = ['狂牙大行动', '突围大行动', '命悬一线', '裂空', '光谱']
cases_name = ["狂牙大行动", "突围大行动", "命悬一线", "裂空", "光谱"]
cases_matcher_group = MatcherGroup(priority=5, permission=GROUP, block=True)
@@ -38,20 +44,24 @@ k_open_case = cases_matcher_group.on_command("开箱")
@k_open_case.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if str(event.get_message()).strip() in ['帮助']:
if str(event.get_message()).strip() in ["帮助"]:
await k_open_case.finish(__plugin_usage__)
if not _flmt.check(event.user_id):
await k_open_case.finish('着什么急啊,慢慢来!', at_sender=True)
await k_open_case.finish("着什么急啊,慢慢来!", at_sender=True)
_flmt.start_cd(event.user_id)
case_name = get_message_text(event.json())
if case_name:
result = await open_case(event.user_id, event.group_id, case_name)
else:
result = await open_case(event.user_id, event.group_id, random.choice(cases_name))
result = await open_case(
event.user_id, event.group_id, random.choice(cases_name)
)
await k_open_case.finish(result, at_sender=True)
total_case_data = cases_matcher_group.on_command("我的开箱", aliases={'开箱统计', '开箱查询', '查询开箱'})
total_case_data = cases_matcher_group.on_command(
"我的开箱", aliases={"开箱统计", "开箱查询", "查询开箱"}
)
@total_case_data.handle()
@@ -75,7 +85,9 @@ my_kinfes = on_command("我的金色", priority=1, permission=GROUP, block=True)
@my_kinfes.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
await my_kinfes.finish(await my_knifes_name(event.user_id, event.group_id), at_sender=True)
await my_kinfes.finish(
await my_knifes_name(event.user_id, event.group_id), at_sender=True
)
open_shilian = cases_matcher_group.on_regex(".*连开箱")
@@ -87,7 +99,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
# await k_open_case.finish('着什么急啊,慢慢来!', at_sender=True)
_flmt.start_cd(event.user_id)
msg = get_message_text(event.json())
rs = re.search(r'(.*)连开箱(.*)', msg)
rs = re.search(r"(.*)连开箱(.*)", msg)
if rs:
num = rs.group(1).strip()
if is_number(num) or num_dict.get(num):
@@ -96,61 +108,53 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
except KeyError:
num = int(num)
if num > 30:
await open_shilian.finish('开箱次数不要超过30啊笨蛋!', at_sender=True)
await open_shilian.finish("开箱次数不要超过30啊笨蛋!", at_sender=True)
else:
await open_shilian.finish('必须要是数字切不要超过30啊笨蛋!中文也可!', at_sender=True)
await open_shilian.finish("必须要是数字切不要超过30啊笨蛋!中文也可!", at_sender=True)
case_name = rs.group(2).strip()
if case_name.find('武器箱') != -1:
case_name = case_name.replace('武器箱', '').strip()
if case_name.find("武器箱") != -1:
case_name = case_name.replace("武器箱", "").strip()
if not case_name:
case_name = random.choice(cases_name)
elif case_name not in cases_name:
await open_shilian.finish('武器箱未收录!', at_sender=True)
await open_shilian.finish(await open_shilian_case(event.user_id, event.group_id, case_name, num), at_sender=True)
# await open_shilian.send("嘟嘟嘟...开箱中...")
# num = 10
# if str(state["_prefix"]["raw_command"]).find('十') != -1:
# num = 10
# elif str(state["_prefix"]["raw_command"]).find('五') != -1:
# num = 5
# if case_name:
# await open_shilian.finish(await open_shilian_case(event.user_id, event.group_id, case_name, num), at_sender=True)
# else:
# await open_shilian.finish(await open_shilian_case(event.user_id, event.group_id, random.choice(cases_name), num),
# at_sender=True)
await open_shilian.finish("武器箱未收录!", at_sender=True)
await open_shilian.finish(
await open_shilian_case(event.user_id, event.group_id, case_name, num),
at_sender=True,
)
num_dict = {
'一': 1,
'二': 2,
'三': 3,
'四': 4,
'五': 5,
'六': 6,
'七': 7,
'八': 8,
'九': 9,
'十': 10,
'十一': 11,
'十二': 12,
'十三': 13,
'十四': 14,
'十五': 15,
'十六': 16,
'十七': 17,
'十八': 18,
'十九': 19,
'二十': 20,
'二十一': 21,
'二十二': 22,
'二十三': 23,
'二十四': 24,
'二十五': 25,
'二十六': 26,
'二十七': 27,
'二十八': 28,
'二十九': 29,
'三十': 30
"一": 1,
"二": 2,
"三": 3,
"四": 4,
"五": 5,
"六": 6,
"七": 7,
"八": 8,
"九": 9,
"十": 10,
"十一": 11,
"十二": 12,
"十三": 13,
"十四": 14,
"十五": 15,
"十六": 16,
"十七": 17,
"十八": 18,
"十九": 19,
"二十": 20,
"二十一": 21,
"二十二": 22,
"二十三": 23,
"二十四": 24,
"二十五": 25,
"二十六": 26,
"二十七": 27,
"二十八": 28,
"二十九": 29,
"三十": 30,
}
@@ -172,10 +176,9 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
# 重置开箱
@scheduler.scheduled_job(
'cron',
"cron",
hour=0,
minute=1,
)
async def _():
await update_count_daily()
+4 -4
View File
@@ -4,13 +4,13 @@ from services.log import logger
from services.db_context import db
from models.open_cases_user import OpenCasesUser
from models.sigin_group_user import SignGroupUser
from utils.init_result import image
from utils.message_builder import image
import pypinyin
import random
from .utils import get_price
from models.buff_price import BuffPrice
from PIL import Image
from utils.img_utils import alphabg2white_PIL, CreateImg
from utils.image_utils import alpha2white_PIL, CreateImg
from configs.path_config import IMAGE_PATH
import asyncio
from utils.utils import cn2py
@@ -221,7 +221,7 @@ async def open_shilian_case(user_qq: int, group: int, case_name: str, num: int =
skin_name += ''.join(i)
# img = image(skin_name, "cases/" + case, "png")
wImg = CreateImg(200, 270, 200, 200)
wImg.paste(alphabg2white_PIL(Image.open(IMAGE_PATH + f'cases/{case}/{skin_name}.png').resize((200, 200), Image.ANTIALIAS)), (0, 0))
wImg.paste(alpha2white_PIL(Image.open(IMAGE_PATH + f'cases/{case}/{skin_name}.png').resize((200, 200), Image.ANTIALIAS)), (0, 0))
wImg.text((5, 200), skin)
wImg.text((5, 220), f'磨损:{str(mosun)[:9]}')
wImg.text((5, 240), f'价格:{price_result}')
@@ -370,7 +370,7 @@ def _pst_my_knife(w, h, knifes_list):
style=pypinyin.NORMAL):
skin_name += ''.join(i)
knife_img = CreateImg(470, 600, 470, 470, font_size=20)
knife_img.paste(alphabg2white_PIL(
knife_img.paste(alpha2white_PIL(
Image.open(IMAGE_PATH + f'cases/{case}/{skin_name}.png').resize((470, 470), Image.ANTIALIAS)), (0, 0))
knife_img.text((5, 500), f'\t{name}({itype})')
knife_img.text((5, 530), f'\t磨损:{mosun}')
+4 -4
View File
@@ -12,9 +12,9 @@ from utils.utils import get_bot
from models.group_remind import GroupRemind
from utils.utils import get_cookie_text
from asyncio.exceptions import TimeoutError
from .config import *
import pypinyin
from nonebot.adapters.cqhttp.exception import ActionFailed
from configs.config import buff_proxy
from configs.config import BUFF_PROXY
url = "https://buff.163.com/api/market/goods"
# proxies = 'http://49.75.59.242:3128'
@@ -60,7 +60,7 @@ async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
"search": skin
}
try:
async with session.get(url, proxy=buff_proxy, params=parameter, timeout=20) as response:
async with session.get(url, proxy=BUFF_PROXY, params=parameter, timeout=20) as response:
if response.status == 200:
data = (await response.json())["data"]
total_page = data["total_page"]
@@ -168,7 +168,7 @@ async def util_get_buff_img(case_name: str = "狂牙大行动") -> str:
print(skin)
skin_name = ''
# try:
async with session.get(url, proxy=buff_proxy, params=parameter, timeout=20) as response:
async with session.get(url, proxy=BUFF_PROXY, params=parameter, timeout=20) as response:
if response.status == 200:
data = (await response.json())["data"]
total_page = data["total_page"]
+30 -38
View File
@@ -1,4 +1,4 @@
from nonebot import on_message
from nonebot import on_message, on_command
from services.log import logger
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
from nonebot.typing import T_State
@@ -7,63 +7,55 @@ import json
from utils.user_agent import get_user_agent
from nonebot.adapters.cqhttp.permission import GROUP
from bilibili_api import video
from utils.init_result import image
from utils.message_builder import image
from models.group_remind import GroupRemind
from nonebot.adapters.cqhttp.exception import ActionFailed
import time
import aiohttp
from bilibili_api import settings
if get_local_proxy():
settings.proxy = get_local_proxy()
parse_bilibili_json = on_message(priority=1, permission=GROUP, block=False)
@parse_bilibili_json.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if await GroupRemind.get_status(event.group_id, 'blpar') and get_message_json(event.json()):
data = json.loads(get_message_json(event.json())['data'])
if await GroupRemind.get_status(event.group_id, "blpar") and get_message_json(
event.json()
):
data = json.loads(get_message_json(event.json())[0]["data"])
if data:
if data.get('desc') == '哔哩哔哩':
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:
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]
bvid = url.split("/")[-1]
vd_info = await video.Video(bvid=bvid).get_info()
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'] # 投币
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']))
date = time.strftime("%Y-%m-%d", time.localtime(vd_info["ctime"]))
try:
await parse_bilibili_json.send(
image(vd_info["pic"]) +
f'\nav{aid}\n标题:{title}\n'
f'UP:{author}\n'
f'上传日期:{date}\n'
f'回复:{reply},收藏:{favorite},投币:{coin}\n'
f'{url}'
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解析失败')
logger.info(f'USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}')
logger.warning(f"{event.group_id} 发送bilibili解析失败")
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 解析bilibili转发 {url}"
)
+44 -36
View File
@@ -2,13 +2,12 @@ from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, MessageEvent, Message, GroupMessageEvent
from nonebot.typing import T_State
from utils.utils import get_message_text, is_number
from utils.init_result import image
from utils.message_builder import image
import aiohttp
from services.log import logger
from asyncio.exceptions import TimeoutError
import asyncio
import aiofiles
from io import BytesIO
from configs.path_config import IMAGE_PATH
try:
@@ -16,38 +15,38 @@ try:
except ModuleNotFoundError:
import json
__plugin_name__ = 'p搜'
__plugin_usage__ = '用法: 通过pid在Pixiv上搜索图片\n格式:p搜 [pid]\n\t示例:p搜 79520120'
__plugin_name__ = "p搜"
__plugin_usage__ = "用法: 通过pid在Pixiv上搜索图片\n格式:p搜 [pid]\n\t示例:p搜 79520120"
pid_search = on_command("p搜", aliases={'pixiv搜', 'P搜'}, priority=5, block=True)
pid_search = on_command("p搜", aliases={"pixiv搜", "P搜"}, priority=5, block=True)
url = 'https://api.fantasyzone.cc/tu/search.php'
url = "https://api.fantasyzone.cc/tu/search.php"
@pid_search.args_parser
async def _(bot: Bot, event: MessageEvent, state: T_State):
pid = get_message_text(event.json())
if pid:
if pid in ['取消', '算了']:
await pid_search.finish('已取消操作...')
if pid in ["取消", "算了"]:
await pid_search.finish("已取消操作...")
if not is_number(pid):
await pid_search.reject('笨蛋,重新输入数!字!', at_sender=True)
state['pid'] = pid
await pid_search.reject("笨蛋,重新输入数!字!", at_sender=True)
state["pid"] = pid
@pid_search.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
pid = get_message_text(event.json())
if pid:
state['pid'] = pid
state["pid"] = pid
@pid_search.got('pid', prompt='需要查询的图片PID是?')
@pid_search.got("pid", prompt="需要查询的图片PID是?")
async def _(bot: Bot, event: MessageEvent, state: T_State):
pid = state['pid']
pid = state["pid"]
params = {
'id': pid,
'p': 1,
"id": pid,
"p": 1,
}
async with aiohttp.ClientSession() as session:
for _ in range(10):
@@ -57,13 +56,13 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
except TimeoutError:
pass
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 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"]
for _ in range(5):
try:
await download_pic(img_url, event.user_id)
@@ -72,29 +71,38 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
else:
break
else:
await pid_search.finish('图片下载失败了....', at_sender=True)
tmp = ''
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}'))
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}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 查询图片 PID:{pid}")
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询图片 PID:{pid}"
)
if isinstance(event, GroupMessageEvent):
await asyncio.sleep(30)
await bot.delete_msg(message_id=msg_id['message_id'], self_id=int(bot.self_id))
await bot.delete_msg(
message_id=msg_id["message_id"], self_id=int(bot.self_id)
)
break
else:
await pid_search.finish('图片下载失败了....', at_sender=True)
await pid_search.finish("图片下载失败了....", at_sender=True)
async def download_pic(img_url: str, user_id: int):
async with aiohttp.ClientSession() as session:
async with session.get(img_url, timeout=2) as res:
async with aiofiles.open(f'{IMAGE_PATH}/temp/pid_search_{user_id}.png', 'wb') as f:
async with aiofiles.open(
f"{IMAGE_PATH}/temp/pid_search_{user_id}.png", "wb"
) as f:
await f.write(await res.read())
+14
View File
@@ -0,0 +1,14 @@
+353
View File
@@ -0,0 +1,353 @@
from aiohttp.client_exceptions import (
ClientOSError,
ServerDisconnectedError,
ClientConnectorError,
)
from asyncpg.exceptions import UniqueViolationError
from asyncio.locks import Semaphore
from aiohttp import ClientPayloadError
from aiohttp.client import ClientSession
from asyncio.exceptions import TimeoutError
from models.pixiv import Pixiv
from typing import List
from utils.utils import get_local_proxy
from utils.image_utils import CreateImg
from services.log import logger
from configs.config import HIBIAPI_BOOKMARKS, HIBIAPI
from configs.path_config import TEMP_PATH
import platform
import aiohttp
import asyncio
import aiofiles
import math
try:
import ujson as json
except ModuleNotFoundError:
import json
if str(platform.system()).lower() == "windows":
policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)
search_url = f"{HIBIAPI}/api/pixiv/search"
member_illust_url = f"{HIBIAPI}/api/pixiv/member_illust"
illust_url = f"{HIBIAPI}/api/pixiv/illust"
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",
}
# 开始更新
async def start_update_image_url(current_keyword: List[str], black_pid: List[str]):
pid_count = 0
pic_count = 0
tasks = []
semaphore = asyncio.Semaphore(10)
async with aiohttp.ClientSession(headers=headers) as session:
for keyword in current_keyword:
for page in range(1, 110):
if keyword.startswith("uid:"):
url = member_illust_url
params = {"id": keyword[4:], "page": page}
if page == 30:
break
elif keyword.startswith("pid:"):
url = illust_url
params = {"id": keyword[4:]}
else:
url = search_url
params = {"word": keyword, "page": page}
tasks.append(
asyncio.ensure_future(
search_image(
url, keyword, params, semaphore, session, page, black_pid
)
)
)
if keyword.startswith("pid:"):
break
result = await asyncio.gather(*tasks)
for x in result:
pid_count += x[0]
pic_count += x[1]
return pid_count, pic_count
async def search_image(
url: str,
keyword: str,
params: dict,
semaphore: Semaphore,
session: ClientSession,
page: int = 1,
black: List[str] = None,
):
tmp_pid = []
pic_count = 0
pid_count = 0
async with semaphore:
try:
async with session.get(
url,
params=params,
proxy=get_local_proxy(),
) as response:
data = await response.json()
if (
not data
or data.get("error")
or (not data.get("illusts") and not data.get("illust"))
):
return 0, 0
if url != illust_url:
logger.info(f'{keyword}: 获取数据成功...数据总量:{len(data["illusts"])}')
data = data["illusts"]
else:
logger.info(f'获取数据成功...PID:{params.get("id")}')
data = [data["illust"]]
img_data = {}
for x in data:
pid = x["id"]
title = x["title"]
width = x["width"]
height = x["height"]
view = x["total_view"]
bookmarks = x["total_bookmarks"]
uid = x["user"]["id"]
author = x["user"]["name"]
tags = []
for tag in x["tags"]:
for i in tag:
if tag[i]:
tags.append(tag[i])
img_urls = []
if x["page_count"] == 1:
img_urls.append(x["meta_single_page"]["original_image_url"])
else:
for urls in x["meta_pages"]:
img_urls.append(urls["image_urls"]["original"])
if (
(
bookmarks >= HIBIAPI_BOOKMARKS
or (url == member_illust_url and bookmarks >= 1500)
or (url == illust_url)
)
and len(img_urls) < 10
and _check_black(img_urls, black)
):
img_data[pid] = {
"pid": pid,
"title": title,
"width": width,
"height": height,
"view": view,
"bookmarks": bookmarks,
"img_urls": img_urls,
"uid": uid,
"author": author,
"tags": tags,
}
else:
continue
for x in img_data.keys():
data = img_data[x]
for img_url in data["img_urls"]:
img_p = img_url[img_url.rfind("_") + 1 : img_url.rfind(".")]
try:
if await Pixiv.add_image_data(
data["pid"],
data["title"],
data["width"],
data["height"],
data["view"],
data["bookmarks"],
img_url,
img_p,
data["uid"],
data["author"],
",".join(data["tags"]),
):
if data["pid"] not in tmp_pid:
pid_count += 1
tmp_pid.append(data["pid"])
pic_count += 1
logger.info(f'存储图片PID:{data["pid"]} IMG_P:{img_p}')
# await download_image(img_url, session)
except UniqueViolationError:
logger.warning(f'{data["pid"]} | {img_url} 已存在...')
# 下载图片
# if not os.path.exists(f'{image_path}/
# {img_url[img_url.rfind("/") + 1:]}'):
# await download_image(img_url, session)
except (ServerDisconnectedError, ClientConnectorError, ClientOSError):
logger.warning("搜索图片服务被关闭,再次调用....")
await search_image(url, keyword, params, semaphore, session, page, black)
return pid_count, pic_count
# 下载图片
async def download_image(img_url: str, session: ClientSession, _count: int = 1):
try:
async with session.get(img_url, proxy=get_local_proxy()) as response:
logger.info(f"下载图片 --> {img_url}")
async with aiofiles.open(f'tmp/{img_url.split("/")[-1]}', "wb") as f:
await f.write(await response.read())
# async with semaphore:
# await asyncio.get_event_loop().run_in_executor(None,
# upload_image, img_url[img_url.rfind("/")+1:])
except ServerDisconnectedError:
logger.warning(f"下载图片服务被关闭,第 {_count} 次调用....")
await download_image(img_url, session, _count + 1)
except ClientOSError:
logger.warning(f"远程连接被关闭,第 {_count} 次调用....")
await download_image(
img_url.replace("i.pximg.net", "i.pixiv.cat"), session, _count + 1
)
except TimeoutError:
logger.warning(f"下载或写入超时,第 {_count} 次调用....")
await download_image(img_url, session, _count + 1)
except ClientPayloadError:
pass
async def get_image(img_url: str, user_id: int) -> str:
try:
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(
img_url,
proxy=get_local_proxy(),
) as response:
async with aiofiles.open(
f"{TEMP_PATH}/pix_{user_id}_{img_url[-10:-4]}.jpg", "wb"
) as f:
await f.write(await response.read())
return f"pix_{user_id}_{img_url[-10:-4]}.jpg"
except (ClientConnectorError, TimeoutError):
return await get_image(img_url, user_id)
# 检测UID或PID是否有效
async def uid_pid_exists(id_: str) -> bool:
if id_.startswith("uid:"):
url = f"{HIBIAPI}/api/pixiv/member"
elif id_.startswith("pid:"):
url = illust_url
else:
return False
params = {"id": int(id_[4:])}
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url, params=params, proxy=get_local_proxy()) as response:
data = await response.json()
if data.get("error"):
return False
return True
async def get_keyword_num(keyword: str) -> "int , int":
return await Pixiv.get_keyword_num(keyword.split())
async def remove_image(pid: int, img_p: str) -> bool:
if img_p:
if "p" not in img_p:
img_p = f"p{img_p}"
return await Pixiv.remove_image_data(pid, img_p)
def gen_keyword_pic(
_pass_keyword: List[str], not_pass_keyword: List[str], is_superuser: bool
):
_keyword = [
x
for x in _pass_keyword
if not x.startswith("uid:")
and not x.startswith("pid:")
and not x.startswith("black:")
]
_uid = [x for x in _pass_keyword if x.startswith("uid:")]
_pid = [x for x in _pass_keyword if x.startswith("pid:")]
_n_keyword = [
x
for x in not_pass_keyword
if not x.startswith("uid:")
and not x.startswith("pid:")
and not x.startswith("black:")
]
_n_uid = [
x
for x in not_pass_keyword
if x.startswith("uid:") and not x.startswith("black:")
]
_n_pid = [
x
for x in not_pass_keyword
if x.startswith("pid:") and not x.startswith("black:")
]
img_width = 0
img_data = {
"_keyword": {"width": 0, "data": _keyword},
"_uid": {"width": 0, "data": _uid},
"_pid": {"width": 0, "data": _pid},
"_n_keyword": {"width": 0, "data": _n_keyword},
"_n_uid": {"width": 0, "data": _n_uid},
"_n_pid": {"width": 0, "data": _n_pid},
}
for x in list(img_data.keys()):
img_data[x]["width"] = math.ceil(len(img_data[x]["data"]) / 40)
img_width += img_data[x]["width"] * 200
if not is_superuser:
img_width = (
img_width
- (
img_data["_n_keyword"]["width"]
+ img_data["_n_uid"]["width"]
+ img_data["_n_pid"]["width"]
)
* 200
)
del img_data["_n_keyword"]
del img_data["_n_pid"]
del img_data["_n_uid"]
current_width = 0
A = CreateImg(img_width, 1100)
for x in list(img_data.keys()):
if img_data[x]["data"]:
img = CreateImg(img_data[x]["width"] * 200, 1100, 200, 1100, font_size=40)
start_index = 0
end_index = 40
total_index = img_data[x]["width"] * 40
for _ in range(img_data[x]["width"]):
tmp = CreateImg(198, 1100, font_size=20)
text_img = CreateImg(198, 100, font_size=50)
key_str = "\n".join(
[key for key in img_data[x]["data"][start_index:end_index]]
)
tmp.text((10, 100), key_str)
if x.find("_n") == -1:
text_img.text((24, 24), "已收录")
else:
text_img.text((24, 24), "待收录")
tmp.paste(text_img, (0, 0))
start_index += 40
end_index = (
end_index + 40 if end_index + 40 <= total_index else total_index
)
background_img = CreateImg(200, 1100, color="#FFE4C4")
background_img.paste(tmp, (1, 1))
img.paste(background_img)
A.paste(img, (current_width, 0))
current_width += img_data[x]["width"] * 200
return A.pic2bs4()
def _check_black(img_urls: List[str], black: List[str]):
for b in black:
for img_url in img_urls:
# img_url = img_url[img_url.rfind('/')+1: img_url.rfind('.')]
if b in img_url:
return False
return True
+63
View File
@@ -0,0 +1,63 @@
from nonebot import on_command
from nonebot.adapters.cqhttp.event import GroupMessageEvent
from nonebot.adapters.cqhttp.message import Message
from utils.utils import get_message_text, is_number
from utils.message_builder import image
from services.log import logger
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.typing import T_State
from .data_source import get_image
from models.pixiv import Pixiv
import random
pix = on_command("pix", aliases={'PIX'}, priority=5, block=True)
@pix.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
num = 1
keyword = get_message_text(event.json())
if is_number(keyword):
all_image = await Pixiv.query_images(uid=int(keyword))
elif keyword.lower().startswith("pid"):
pid = keyword.replace("pid", "").replace(":", "")
if not is_number(pid):
await pix.finish("PID必须是数字...", at_sender=True)
all_image = await Pixiv.query_images(pid=int(pid))
else:
x = keyword.split()
if len(x) > 1:
if is_number(x[-1]):
num = int(x[-1])
if num > 11:
num = random.randint(1, 10)
await pix.send(f"太贪心了,就给你发 {num}张 好了")
x = x[:-1]
keyword = " ".join(x)
all_image = await Pixiv.query_images(x)
if not all_image:
await pix.finish(f"未在图库中找到与 {keyword} 相关Tag/UID/PID的图片...", at_sender=True)
for _ in range(num):
if not all_image:
await pix.finish("坏了...发完了,没图了...")
img = random.choice(all_image)
all_image.remove(img)
img_url = img.img_url
pid = img.pid
title = img.title
author = img.author
uid = img.uid
# tags = img.tags
await pix.send(
Message(
f"title:{title}\n"
f"author:{author}\n"
f"PID:{pid}\nUID:{uid}\n"
f"{image(await get_image(img_url, event.user_id), 'temp')}"
)
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看PIX图库PID: {pid}"
)
+115
View File
@@ -0,0 +1,115 @@
from nonebot import on_command
from utils.utils import get_message_text, is_number
from services.log import logger
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from .data_source import uid_pid_exists
from models.pixiv_keyword_user import PixivKeywordUser
from models.pixiv import Pixiv
from nonebot.permission import SUPERUSER
__plugin_name__ = "添加PIX关键词/UID/PID | 添加PIX黑名单"
__plugin_usage__ = """
关键词:添加搜图的关键词(效果拉胯)
UID:搜集该画师的图片,可指定收藏数
PID:收录单张图片
PIX黑名单:可以是当个pid,也可以是pid_p0等
"""
add_keyword = on_command("添加pix关键词", aliases={"添加pix关键字"}, priority=1, block=True)
add_black_pid = on_command("添加pix黑名单", permission=SUPERUSER, priority=1, block=True)
# 超级用户可以通过字符 -f 来强制收录不检查是否存在
add_uid_pid = on_command(
"添加pixuid",
aliases={
"添加pixpid",
},
priority=1,
block=True,
)
@add_keyword.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
group_id = -1
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
if msg:
if await PixivKeywordUser.add_keyword(
event.user_id, group_id, msg, bot.config.superusers
):
await add_keyword.send(
f"已成功添加pixiv搜图关键词:{msg},请等待管理员通过该关键词!", at_sender=True
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 添加了pixiv搜图关键词:" + msg
)
else:
await add_keyword.finish(f"该关键词 {msg} 已存在...")
else:
await add_keyword.finish(f"虚空关键词?.?.?.?")
@add_uid_pid.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
exists_flag = True
if msg.find("-f") != -1 and str(event.user_id) in bot.config.superusers:
exists_flag = False
msg = msg.replace("-f", "").strip()
if msg:
for msg in msg.split():
if not is_number(msg):
await add_uid_pid.finish("UID只能是数字的说...", at_sender=True)
if state["_prefix"]["raw_command"].lower().endswith("uid"):
msg = f"uid:{msg}"
else:
msg = f"pid:{msg}"
if await Pixiv.check_exists(int(msg[4:]), "p0"):
await add_uid_pid.finish(f"该PID:{msg[4:]}已存在...", at_sender=True)
if not await uid_pid_exists(msg) and exists_flag:
await add_uid_pid.finish("画师或作品不存在或搜索正在CD,请稍等...", at_sender=True)
group_id = -1
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
if await PixivKeywordUser.add_keyword(
event.user_id, group_id, msg, bot.config.superusers
):
await add_uid_pid.send(
f"已成功添加pixiv搜图UID/PID:{msg[4:]},请等待管理员通过!", at_sender=True
)
else:
await add_uid_pid.finish(f"该UID/PID:{msg[4:]} 已存在...")
else:
await add_uid_pid.finish("湮灭吧!虚空的UID!")
@add_black_pid.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
pid = get_message_text(event.json())
img_p = ""
if "p" in pid:
img_p = pid.split("p")[-1]
pid = pid.replace("_", "")
pid = pid[: pid.find("p")]
if not is_number(pid):
await add_black_pid.finish("PID必须全部是数字!", at_sender=True)
if await PixivKeywordUser.add_keyword(
114514,
114514,
f"black:{pid}{f'_p{img_p}' if img_p else ''}",
bot.config.superusers,
):
await add_black_pid.send(f"已添加PID:{pid} 至黑名单中...")
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 添加了pixiv搜图黑名单 PID:{pid}"
)
else:
await add_black_pid.send(f"PID:{pid} 已添加黑名单中,添加失败...")
+167
View File
@@ -0,0 +1,167 @@
from nonebot import on_command
from nonebot.adapters.cqhttp.message import Message
from utils.utils import get_message_text, is_number
from utils.message_builder import at
from services.log import logger
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.permission import SUPERUSER
from nonebot.typing import T_State
from .data_source import remove_image
from models.pixiv_keyword_user import PixivKeywordUser
from models.pixiv import Pixiv
__plugin_name__ = "通过/取消/删除pix关键词 | 删除pix图片"
__plugin_usage__ = """
通过/取消/删除pix关键词 [关键词/pid/uid] 示例:通过pix关键词萝莉,通过pix关键词uid:123456,通过pix关键词pid:123456
删除pix图片 *[pid] 示例:删除pix图片4223442
"""
pass_keyword = on_command(
"通过pix关键词",
aliases={"通过pix关键字", "取消pix关键词", "取消pix关键字"},
permission=SUPERUSER,
priority=1,
block=True,
)
del_keyword = on_command(
"删除pix关键词", aliases={"删除pix关键字"}, permission=SUPERUSER, priority=1, block=True
)
del_pic = on_command(
"删除pix图片", permission=SUPERUSER, priority=1, block=True
)
@del_keyword.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
await del_keyword.finish("好好输入要删除什么关键字啊笨蛋!")
if is_number(msg):
msg = f"uid:{msg}"
if msg.lower().startswith("pid"):
msg = "pid:" + msg.replace("pid", "").replace(":", "")
if await PixivKeywordUser.delete_keyword(msg):
await del_keyword.send(f"删除搜图关键词/UID:{msg} 成功...")
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 删除了pixiv搜图关键词:" + msg
)
else:
await del_keyword.send(f"未查询到搜索关键词/UID/PID:{msg},删除失败!")
@del_pic.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
pid_arr = get_message_text(event.json())
if pid_arr:
msg = ""
black_pid = ""
flag = False
pid_arr = pid_arr.split()
if pid_arr[-1] in ["-black", "-b"]:
flag = True
pid_arr = pid_arr[:-1]
for pid in pid_arr:
img_p = None
if "p" in pid or "ugoira" in pid:
if "p" in pid:
img_p = pid.split("p")[-1]
pid = pid.replace("_", "")
pid = pid[: pid.find("p")]
elif "ugoira" in pid:
img_p = pid.split("ugoira")[-1]
pid = pid.replace("_", "")
pid = pid[: pid.find("ugoira")]
if is_number(pid):
if await Pixiv.query_images(pid=int(pid), r18=2):
if await remove_image(int(pid), img_p):
msg += f'{pid}{f"_p{img_p}" if img_p else ""},'
if flag:
if await PixivKeywordUser.add_keyword(
114514,
114514,
f"black:{pid}{f'_p{img_p}' if img_p else ''}",
bot.config.superusers,
):
black_pid += f'{pid}{f"_p{img_p}" if img_p else ""},'
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 删除了PIX图片 PID:{pid}{f'_p{img_p}' if img_p else ''}"
)
else:
await del_pic.send(
f"PIX:删除pid:{pid}{f'_p{img_p}' if img_p else ''} 失败.."
)
else:
await del_pic.send(
f"PIX:图片pix:{pid}{f'_p{img_p}' if img_p else ''} 不存在...无法删除.."
)
else:
await del_pic.send(f"PID必须为数字!pid:{pid}", at_sender=True)
await del_pic.send(f"PIX:成功删除图片:{msg[:-1]}")
if flag:
await del_pic.send(f"成功图片PID加入黑名单:{black_pid[:-1]}")
else:
await del_pic.send("虚空删除?")
@pass_keyword.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
tmp = {"group": {}, "private": {}}
msg = get_message_text(event.json())
if not msg:
await pass_keyword.finish("通过虚空的关键词/UID?离谱...")
msg = msg.split()
flag = True if state["_prefix"]["raw_command"][:2] == "通过" else False
for x in msg:
if x.lower().startswith("uid"):
x = x.replace("uid", "").replace(":", "")
x = f"uid:{x}"
elif x.lower().startswith("pid"):
x = x.replace("pid", "").replace(":", "")
x = f"pid:{x}"
if x.lower().find("pid") != -1 or x.lower().find("uid") != -1:
if not is_number(x[4:]):
await pass_keyword.send(f"UID/PID:{x} 非全数字,跳过该关键词...")
continue
user_id, group_id = await PixivKeywordUser.set_keyword_pass(x, flag)
if not user_id:
await pass_keyword.send(f"未找到关键词/UID:{x},请检查关键词/UID是否存在...")
continue
if flag:
if group_id == -1:
if not tmp["private"].get(user_id):
tmp["private"][user_id] = {"keyword": [x]}
else:
tmp["private"][user_id]["keyword"].append(x)
else:
if not tmp["group"].get(group_id):
tmp["group"][group_id] = {}
if not tmp["group"][group_id].get(user_id):
tmp["group"][group_id][user_id] = {"keyword": [x]}
else:
tmp["group"][group_id][user_id]["keyword"].append(x)
msg = " ".join(msg)
await pass_keyword.send(f'已成功{state["_prefix"]["raw_command"][:2]}搜图关键词:{msg}....')
for user in tmp["private"]:
x = ",".join(tmp["private"][user]["keyword"])
await bot.send_private_msg(
user_id=user, message=f"你的关键词/UID/PID {x} 已被管理员通过,将在下一次进行更新..."
)
for group in tmp["group"]:
for user in tmp["group"][group]:
x = ",".join(tmp["group"][group][user]["keyword"])
await bot.send_group_msg(
group_id=group,
message=Message(f"{at(user)}你的关键词/UID/PID {x} 已被管理员通过,将在下一次进行更新..."),
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 通过了pixiv搜图关键词/UID:" + msg
)
+65
View File
@@ -0,0 +1,65 @@
from nonebot import on_command
from utils.utils import get_message_text
from utils.message_builder import image
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.typing import T_State
from .data_source import gen_keyword_pic, get_keyword_num
from models.pixiv_keyword_user import PixivKeywordUser
import asyncio
__plugin_name__ = "查看pix图库"
__plugin_usage__ = """
查看pix图库 [keyword]:当keyword为空时检查所有图片
"""
my_keyword = on_command("我的pix关键词", aliases={"我的pix关键字"}, priority=1, block=True)
show_keyword = on_command("显示pix关键词", aliases={"显示pix关键字"}, priority=1, block=True)
show_pix = on_command("查看pix图库", priority=1, block=True)
@my_keyword.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
data = await PixivKeywordUser.get_all_user_dict()
if data.get(event.user_id) is None or not data[event.user_id]["keyword"]:
await my_keyword.finish("您目前没有提供任何Pixiv搜图关键字...", at_sender=True)
await my_keyword.send(
f"您目前提供的如下关键字:\n\t" + ",".join(data[event.user_id]["keyword"])
)
@show_keyword.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
_pass_keyword, not_pass_keyword = await PixivKeywordUser.get_current_keyword()
if _pass_keyword or not_pass_keyword:
await show_keyword.send(
image(
b64=await asyncio.get_event_loop().run_in_executor(
None,
gen_keyword_pic,
_pass_keyword,
not_pass_keyword,
str(event.user_id) in bot.config.superusers,
)
)
)
else:
if str(event.user_id) in bot.config.superusers:
await show_keyword.finish(f"目前没有已收录或待收录的搜索关键词...")
else:
await show_keyword.finish(f"目前没有已收录的搜索关键词...")
@show_pix.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
keyword = get_message_text(event.json())
count, r18_count = await get_keyword_num(keyword)
await show_pix.send(
f"PIX图库:{keyword}\n"
f"总数:{count + r18_count}\n"
f"美图:{count}\n"
f"r18:{r18_count}"
)
+126
View File
@@ -0,0 +1,126 @@
from nonebot import on_command
from utils.utils import get_message_text, is_number
from nonebot.permission import SUPERUSER
from nonebot.typing import T_State
from .data_source import start_update_image_url
from models.pixiv_keyword_user import PixivKeywordUser
from models.pixiv import Pixiv
from nonebot.adapters.cqhttp import Bot, MessageEvent
import time
__plugin_name__ = "更新pix关键字 | pix检查更新"
__plugin_usage__ = """
更新pix收录的所有或指定数量的关键词/uid/pid
更新pix关键词 [keyword/uid/pid] [num]=all 示例:更新pix关键词uid 5
pix检测更新:检测从未更新过的uid和pid
"""
start_update = on_command(
"更新pix关键词", aliases={"更新pix关键字"}, permission=SUPERUSER, priority=1, block=True
)
check_not_update_uid_pid = on_command(
"pix检测更新",
aliases={"pix检查更新"},
permission=SUPERUSER,
priority=1,
block=True,
)
@start_update.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg_sp = get_message_text(event.json()).split()
_pass_keyword, _ = await PixivKeywordUser.get_current_keyword()
_pass_keyword.reverse()
black_pid = await PixivKeywordUser.get_black_pid()
_keyword = [
x
for x in _pass_keyword
if not x.startswith("uid:")
and not x.startswith("pid:")
and not x.startswith("black:")
]
_uid = [x for x in _pass_keyword if x.startswith("uid:")]
_pid = [x for x in _pass_keyword if x.startswith("pid:")]
num = 9999
msg = msg_sp[0] if len(msg_sp) else ""
if len(msg_sp) == 2:
if is_number(msg_sp[1]):
num = int(msg_sp[1])
else:
await start_update.finish("参数错误...第二参数必须为数字")
if num < 10000:
keyword_str = ",".join(
_keyword[: num if num < len(_keyword) else len(_keyword)]
)
uid_str = ",".join(_uid[: num if num < len(_uid) else len(_uid)])
pid_str = ",".join(_pid[: num if num < len(_pid) else len(_pid)])
if msg.lower() == "pid":
update_lst = _pid
info = f"开始更新Pixiv搜图PID:\n{pid_str}"
elif msg.lower() == "uid":
update_lst = _uid
info = f"开始更新Pixiv搜图UID:\n{uid_str}"
elif msg.lower() == "keyword":
update_lst = _keyword
info = f"开始更新Pixiv搜图关键词:\n{keyword_str}"
else:
update_lst = _pass_keyword
info = f"开始更新Pixiv搜图关键词:\n{keyword_str}\n更新UID:{uid_str}\n更新PID:{pid_str}"
num = num if num < len(update_lst) else len(update_lst)
else:
if msg.lower() == "pid":
update_lst = [f"pid:{num}"]
info = f"开始更新Pixiv搜图UID:\npid:{num}"
else:
update_lst = [f"uid:{num}"]
info = f"开始更新Pixiv搜图UID:\nuid:{num}"
await start_update.send(info)
start_time = time.time()
pid_count, pic_count = await start_update_image_url(update_lst[:num], black_pid)
await start_update.send(
f"Pixiv搜图关键词搜图更新完成...\n"
f"累计更新PID {pid_count} 个\n"
f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time))
)
@check_not_update_uid_pid.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
flag = False
if msg == "update":
flag = True
_pass_keyword, _ = await PixivKeywordUser.get_current_keyword()
x_uid = []
x_pid = []
_uid = [int(x[4:]) for x in _pass_keyword if x.startswith("uid:")]
_pid = [int(x[4:]) for x in _pass_keyword if x.startswith("pid:")]
all_images = await Pixiv.query_images(r18=2)
for img in all_images:
if img.pid not in x_pid:
x_pid.append(img.pid)
if img.uid not in x_uid:
x_uid.append(img.uid)
await check_not_update_uid_pid.send(
"从未更新过的UID:"
+ ",".join([f"uid:{x}" for x in _uid if x not in x_uid])
+ "\n"
+ "从未更新过的PID:"
+ ",".join([f"pid:{x}" for x in _pid if x not in x_pid])
)
if flag:
await check_not_update_uid_pid.send("开始自动自动更新PID....")
update_lst = [f"pid:{x}" for x in _uid if x not in x_uid]
black_pid = await PixivKeywordUser.get_black_pid()
start_time = time.time()
pid_count, pic_count = await start_update_image_url(update_lst, black_pid)
await check_not_update_uid_pid.send(
f"Pixiv搜图关键词搜图更新完成...\n"
f"累计更新PID {pid_count} 个\n"
f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time))
)
+97 -87
View File
@@ -1,18 +1,22 @@
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.adapters.cqhttp import Bot, MessageEvent, Event, GroupMessageEvent, Message
from nonebot.matcher import Matcher
from nonebot import on_command
from utils.utils import get_message_text, UserExistLimiter, is_number
from .data_source import get_pixiv_urls, download_pixiv_imgs, search_pixiv_urls
import time
from utils.message_builder import at
from services.log import logger
from nonebot.adapters.cqhttp.exception import NetworkError
from asyncio.exceptions import TimeoutError
from aiohttp.client_exceptions import ClientConnectorError
from nonebot.exception import IgnoredException
from nonebot.message import run_preprocessor, run_postprocessor
from typing import Optional
import time
__plugin_name__ = "P站"
__plugin_name__ = 'P站'
__plugin_usage__ = '''P站排行榜帮助:
__plugin_usage__ = """P站排行榜帮助:
可选参数:
类型:
1. 日排行
@@ -45,132 +49,155 @@ p站排行榜 [参数] [数量](可选) [日期](可选)
搜图 樱岛麻衣 5 2 r18
【默认为 热度排序】
【注意空格!!】【在线搜索会较慢】【数量可能不符】
'''
"""
rank_dict = {
'1': 'day',
'2': 'week',
'3': 'month',
'4': 'week_original',
'5': 'week_rookie',
'6': 'day_r18',
'7': 'week_r18',
'8': 'day_male_r18',
'9': 'week_r18g'
"1": "day",
"2": "week",
"3": "month",
"4": "week_original",
"5": "week_rookie",
"6": "day_r18",
"7": "week_r18",
"8": "day_male_r18",
"9": "week_r18g",
}
_ulmt = UserExistLimiter()
pixiv_rank = on_command('p站排行', aliases={'P站排行榜', 'p站排行榜', 'P站排行榜'}, priority=5, block=True)
pixiv_keyword = on_command('搜图', priority=5, block=True)
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State):
if isinstance(event, MessageEvent):
if matcher.module == "pixiv":
if _ulmt.check(event.user_id):
if isinstance(event, GroupMessageEvent):
await bot.send_group_msg(
group_id=event.group_id,
message=Message(f"{at(event.user_id)}P站排行榜或搜图正在搜索噢,不要重复触发命令呀"),
)
else:
await bot.send_private_msg(
user_id=event.user_id, message=f"P站排行榜或搜图正在搜索噢,不要重复触发命令呀"
)
raise IgnoredException("pixiv插件正在访问!")
_ulmt.set_True(event.user_id)
@run_postprocessor
async def do_something(
matcher: Matcher,
exception: Optional[Exception],
bot: Bot,
event: Event,
state: T_State,
):
if isinstance(event, MessageEvent):
if matcher.module == "pixiv":
_ulmt.set_False(event.user_id)
pixiv_rank = on_command(
"p站排行", aliases={"P站排行榜", "p站排行榜", "P站排行榜"}, priority=5, block=True
)
pixiv_keyword = on_command("搜图", priority=5, block=True)
@pixiv_rank.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json()).strip()
msg = msg.split(' ')
msg = msg.split(" ")
msg = [m for m in msg if m]
if not msg:
msg = ['1']
if msg[0] in ['6', '7', '8', '9']:
if event.message_type == 'group':
await pixiv_rank.finish('羞羞脸!私聊里自己看!', at_sender=True)
# print(msg)
if _ulmt.check(event.user_id):
await pixiv_rank.finish("P站排行榜正在搜索噢,不要重复触发命令呀")
_ulmt.set_True(event.user_id)
if len(msg) == 0 or msg[0] == '':
text_list, urls, code = await get_pixiv_urls(rank_dict.get('1'))
msg = ["1"]
if msg[0] in ["6", "7", "8", "9"]:
if event.message_type == "group":
await pixiv_rank.finish("羞羞脸!私聊里自己看!", at_sender=True)
if len(msg) == 0 or msg[0] == "":
text_list, urls, code = await get_pixiv_urls(rank_dict.get("1"))
elif len(msg) == 1:
if msg[0] not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
_ulmt.set_False(event.user_id)
if msg[0] not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
await pixiv_rank.finish("要好好输入要看什么类型的排行榜呀!", at_sender=True)
text_list, urls, code = await get_pixiv_urls(rank_dict.get(msg[0]))
elif len(msg) == 2:
text_list, urls, code = await get_pixiv_urls(rank_dict.get(msg[0]), int(msg[1]))
elif len(msg) == 3:
if not check_date(msg[2]):
_ulmt.set_False(event.user_id)
await pixiv_rank.finish('日期格式错误了', at_sender=True)
text_list, urls, code = await get_pixiv_urls(rank_dict.get(msg[0]), int(msg[1]), msg[2])
await pixiv_rank.finish("日期格式错误了", at_sender=True)
text_list, urls, code = await get_pixiv_urls(
rank_dict.get(msg[0]), int(msg[1]), msg[2]
)
else:
_ulmt.set_False(event.user_id)
await pixiv_rank.finish('格式错了噢,看看帮助?', at_sender=True)
await pixiv_rank.finish("格式错了噢,看看帮助?", at_sender=True)
if code != 200:
_ulmt.set_False(event.user_id)
await pixiv_keyword.finish(text_list[0])
else:
if not text_list or not urls:
_ulmt.set_False(event.user_id)
await pixiv_rank.finish('没有找到啊,等等再试试吧~V', at_sender=True)
await pixiv_rank.finish("没有找到啊,等等再试试吧~V", at_sender=True)
for i in range(len(text_list)):
try:
await pixiv_rank.send(text_list[i] + await download_pixiv_imgs(urls[i], event.user_id))
await pixiv_rank.send(
text_list[i] + await download_pixiv_imgs(urls[i], event.user_id)
)
except (NetworkError, TimeoutError, ClientConnectorError):
await pixiv_keyword.send('这张图网络炸了!', at_sender=True)
await pixiv_keyword.send("这张图网络炸了!", at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 查看了P站排行榜 code:{msg[0]}")
_ulmt.set_False(event.user_id)
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看了P站排行榜 code:{msg[0]}"
)
@pixiv_keyword.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json()).strip()
if event.message_type == 'group':
if msg.find('r18') != -1:
await pixiv_keyword.finish('(脸红#) 你不会害羞的 八嘎!', at_sender=True)
if msg.find('r18') == -1:
if event.message_type == "group":
if msg.find("r18") != -1:
await pixiv_keyword.finish("(脸红#) 你不会害羞的 八嘎!", at_sender=True)
if msg.find("r18") == -1:
r18 = 1
else:
r18 = 2
msg = msg.replace('r18', '').strip()
if _ulmt.check(event.user_id):
await pixiv_rank.finish("P站关键词正在搜索噢,不要重复触发命令呀")
_ulmt.set_True(event.user_id)
msg = msg.split(' ')
msg = msg.replace("r18", "").strip()
msg = msg.split(" ")
msg = [m for m in msg if m]
if len(msg) == 1:
keyword = msg[0].strip()
num = 5
order = 'popular'
order = "popular"
elif len(msg) == 2:
keyword = msg[0].strip()
if not is_number(msg[1].strip()):
_ulmt.set_False(event.user_id)
await pixiv_keyword.finish('图片数量必须是数字!', at_sender=True)
await pixiv_keyword.finish("图片数量必须是数字!", at_sender=True)
num = int(msg[1].strip())
order = 'popular'
order = "popular"
elif len(msg) == 3:
keyword = msg[0].strip()
if not is_number(msg[1].strip()):
_ulmt.set_False(event.user_id)
await pixiv_keyword.finish('图片数量必须是数字!', at_sender=True)
await pixiv_keyword.finish("图片数量必须是数字!", at_sender=True)
num = int(msg[1].strip())
if not is_number(msg[2].strip()):
_ulmt.set_False(event.user_id)
await pixiv_keyword.finish('排序方式必须是数字!', at_sender=True)
if msg[2].strip() == '1':
order = 'popular'
await pixiv_keyword.finish("排序方式必须是数字!", at_sender=True)
if msg[2].strip() == "1":
order = "popular"
else:
order = 'xxx'
order = "xxx"
else:
_ulmt.set_False(event.user_id)
await pixiv_keyword.finish('参数不正确,一定要好好看看帮助啊!', at_sender=True)
await pixiv_keyword.finish("参数不正确,一定要好好看看帮助啊!", at_sender=True)
text_list, urls, code = await search_pixiv_urls(keyword, num, order, r18)
if code != 200:
_ulmt.set_False(event.user_id)
await pixiv_keyword.finish(text_list[0])
else:
for i in range(len(text_list)):
try:
await pixiv_keyword.send(text_list[i] + await download_pixiv_imgs(urls[i], event.user_id))
await pixiv_keyword.send(
text_list[i] + await download_pixiv_imgs(urls[i], event.user_id)
)
except (NetworkError, TimeoutError, ClientConnectorError):
await pixiv_keyword.send('这张图网络炸了!', at_sender=True)
await pixiv_keyword.send("这张图网络炸了!", at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 查看了搜索 {keyword} R18:{r18}")
_ulmt.set_False(event.user_id)
f" 查看了搜索 {keyword} R18:{r18}"
)
def check_date(date):
@@ -179,20 +206,3 @@ def check_date(date):
return True
except:
return False
+34 -24
View File
@@ -5,20 +5,22 @@ from utils.utils import get_local_proxy
from utils.user_agent import get_user_agent
from bs4 import BeautifulSoup
import feedparser
from utils.init_result import image
from utils.message_builder import image
from asyncio.exceptions import TimeoutError
from configs.config import RSSHUBAPP
from aiohttp.client_exceptions import ClientConnectorError
import platform
if platform.system() == 'Windows':
if platform.system() == "Windows":
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def get_pixiv_urls(mode: str, num: int = 5, date: str = '') -> 'list, list, int':
url = f'{RSSHUBAPP}pixiv/ranking/{mode}'
async def get_pixiv_urls(mode: str, num: int = 5, date: str = "") -> "list, list, int":
url = f"{RSSHUBAPP}/pixiv/ranking/{mode}"
if date:
url += f'/{date}'
url += f"/{date}"
try:
return await parser_data(url, num)
except ClientConnectorError:
@@ -26,62 +28,70 @@ async def get_pixiv_urls(mode: str, num: int = 5, date: str = '') -> 'list, list
async def download_pixiv_imgs(urls: list, user_id: int) -> str:
result = ''
result = ""
index = 0
for img in urls:
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
for _ in range(3):
async with session.get(img, proxy=get_local_proxy(), timeout=2) as response:
async with aiofiles.open(IMAGE_PATH + f'temp/{user_id}_{index}_pixiv.jpg', 'wb') as f:
async with session.get(
img, proxy=get_local_proxy(), timeout=2
) as response:
async with aiofiles.open(
IMAGE_PATH + f"temp/{user_id}_{index}_pixiv.jpg", "wb"
) as f:
try:
await f.write(await response.read())
result += image(f'{user_id}_{index}_pixiv.jpg', 'temp')
result += image(f"{user_id}_{index}_pixiv.jpg", "temp")
index += 1
break
except TimeoutError:
# result += '\n这张图下载失败了..\n'
pass
else:
result += '\n这张图下载失败了..\n'
result += "\n这张图下载失败了..\n"
return result
async def search_pixiv_urls(keyword: str, num: int, order: str, r18: int) -> 'list, list':
url = f'{RSSHUBAPP}pixiv/search/{keyword}/{order}/{r18}'
async def search_pixiv_urls(
keyword: str, num: int, order: str, r18: int
) -> "list, list":
url = f"{RSSHUBAPP}/pixiv/search/{keyword}/{order}/{r18}"
return await parser_data(url, num)
async def parser_data(url: str, num: int) -> 'list, list, int':
async def parser_data(url: str, num: int) -> "list, list, int":
text_list = []
urls = []
async with aiohttp.ClientSession() as session:
for _ in range(3):
try:
async with session.get(url, proxy=get_local_proxy(), timeout=2) as response:
data = feedparser.parse(await response.text())['entries']
async with session.get(
url, proxy=get_local_proxy(), timeout=2
) as response:
data = feedparser.parse(await response.text())["entries"]
break
except TimeoutError:
pass
else:
return ['网络不太好,也许过一会就好了'], [], 998
return ["网络不太好,也许过一会就好了"], [], 998
try:
if len(data) == 0:
return ['没有搜索到喔'], [], 997
return ["没有搜索到喔"], [], 997
if num > len(data):
num = len(data)
data = data[:num]
for data in data:
soup = BeautifulSoup(data['summary'], 'lxml')
title = "标题:" + data['title']
pl = soup.find_all('p')
author = pl[0].text.split('-')[0].strip()
soup = BeautifulSoup(data["summary"], "lxml")
title = "标题:" + data["title"]
pl = soup.find_all("p")
author = pl[0].text.split("-")[0].strip()
imgs = []
text_list.append(f'{title}\n{author}\n')
text_list.append(f"{title}\n{author}\n")
for p in pl[1:]:
imgs.append(p.find('img').get('src'))
imgs.append(p.find("img").get("src"))
urls.append(imgs)
except ValueError:
return ['是网站坏了啊,也许过一会就好了'], [], 999
return ["是网站坏了啊,也许过一会就好了"], [], 999
return text_list, urls, 200
+30 -16
View File
@@ -3,21 +3,34 @@ from nonebot.adapters.cqhttp import Bot, PokeNotifyEvent
from nonebot.typing import T_State
from configs.path_config import VOICE_PATH, IMAGE_PATH
import os
from utils.init_result import record, image, poke
from utils.message_builder import record, image, poke
from services.log import logger
import random
from utils.utils import CountLimiter
from models.ban_user import BanUser
__plugin_name__ = '戳一戳 [Hidden]'
__plugin_name__ = "戳一戳 [Hidden]"
__plugin_usage__ = '用法:无'
__plugin_usage__ = "用法:无"
poke__reply = [
"lsp你再戳?", "连个可爱美少女都要戳的肥宅真恶心啊。",
"你再戳!", "?再戳试试?", "别戳了别戳了再戳就坏了555", "我爪巴爪巴,球球别再戳了", "你戳你🐎呢?!",
"那...那里...那里不能戳...绝对...", "(。´・ω・)ん?", "有事恁叫我,别天天一个劲戳戳戳!", "欸很烦欸!你戳🔨呢",
"?", "再戳一下试试?", "???", "正在关闭对您的所有服务...关闭成功", "啊呜,太舒服刚刚竟然睡着了。什么事?", "正在定位您的真实地址。。。\r\n定位成功。轰炸机已起飞"
"lsp你再戳?",
"连个可爱美少女都要戳的肥宅真恶心啊。",
"你再戳!",
"?再戳试试?",
"别戳了别戳了再戳就坏了555",
"我爪巴爪巴,球球别再戳了",
"你戳你🐎呢?!",
"那...那里...那里不能戳...绝对...",
"(。´・ω・)ん?",
"有事恁叫我,别天天一个劲戳戳戳!",
"欸很烦欸!你戳🔨呢",
"?",
"再戳一下试试?",
"???",
"正在关闭对您的所有服务...关闭成功",
"啊呜,太舒服刚刚竟然睡着了。什么事?",
"正在定位您的真实地址...定位成功。轰炸机已起飞",
]
@@ -31,24 +44,25 @@ async def _poke_(bot: Bot, event: PokeNotifyEvent, state: T_State):
if event.self_id == event.target_id:
_clmt.add(event.user_id)
if _clmt.check(event.user_id) or random.random() < 0.3:
rst = ''
rst = ""
if random.random() < 0.15:
await BanUser.ban(event.user_id, 1, 60)
rst = '气死我了!'
rst = "气死我了!"
await poke_.finish(rst + random.choice(poke__reply), at_sender=True)
rand = random.random()
if rand <= 0.3:
path = random.choice(['luoli/', 'meitu/'])
path = random.choice(["luoli/", "meitu/"])
index = random.randint(0, len(os.listdir(IMAGE_PATH + path)))
result = f'id:{index}' + image(f'{index}.jpg', path)
result = f"id:{index}" + image(f"{index}.jpg", path)
await poke_.send(result)
logger.info(f'USER {event.user_id} 戳了戳我 回复: {result} \n {result}')
logger.info(f"USER {event.user_id} 戳了戳我 回复: {result} \n {result}")
elif 0.3 < rand < 0.6:
voice = random.choice(os.listdir(VOICE_PATH + 'dinggong/'))
voice = random.choice(os.listdir(VOICE_PATH + "dinggong/"))
result = record(voice, "dinggong")
await poke_.send(result)
await poke_.send(voice.split('_')[1])
logger.info(f'USER {event.user_id} 戳了戳我 回复: {result} \n {voice.split("_")[1]}')
await poke_.send(voice.split("_")[1])
logger.info(
f'USER {event.user_id} 戳了戳我 回复: {result} \n {voice.split("_")[1]}'
)
else:
await poke_.send(poke(event.user_id))
+8 -8
View File
@@ -1,18 +1,18 @@
from nonebot import on_command
from services.log import logger
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
import aiohttp
from utils.utils import get_local_proxy
__plugin_name__ = '语录'
__plugin_usage__ = '用法: 二次元语录给你力量'
__plugin_name__ = "语录"
__plugin_usage__ = "用法: 二次元语录给你力量"
quotations = on_command("语录", aliases={'二次元', '二次元语录'}, priority=5, block=True)
quotations = on_command("语录", aliases={"二次元", "二次元语录"}, priority=5, block=True)
url = 'https://international.v1.hitokoto.cn/?c=a'
url = "https://international.v1.hitokoto.cn/?c=a"
@quotations.handle()
@@ -23,6 +23,6 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
result = f'{data["hitokoto"]}\t——{data["from"]}'
await quotations.send(result)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'}) 发送语录:"
+ result)
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 发送语录:"
+ result
)
+25 -37
View File
@@ -2,13 +2,13 @@ from nonebot import on_command
from nonebot.adapters.cqhttp.permission import PRIVATE
from .data_source import from_reimu_get_info
from services.log import logger
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp import Bot, Event, PrivateMessageEvent
from nonebot.typing import T_State
from utils.utils import is_number, get_message_text, UserExistLimiter, scheduler
from models.count_user import UserCount
from configs.config import COUNT_PER_DAY_REIMU
__plugin_name__ = '上车'
__plugin_name__ = "上车"
__plugin_usage__ = r"""
* 请各位使用后不要转发 *
* 大部分解压密码是⑨ *
@@ -22,49 +22,48 @@ ps: 请尽量提供具体的目的地名称
_ulmt = UserExistLimiter()
reimu = on_command('上车', permission=PRIVATE, block=True, priority=1)
reimu = on_command("上车", permission=PRIVATE, block=True, priority=1)
@reimu.args_parser
async def _(bot: Bot, event: Event, state: T_State):
if get_message_text(event.json()) in ['取消', '算了']:
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
if get_message_text(event.json()) in ["取消", "算了"]:
await reimu.finish("已取消操作..", at_sender=True)
if not get_message_text(event.json()):
await reimu.reject('没时间等了!快说你要去哪里?', at_sender=True)
state['keyword'] = get_message_text(event.json())
state['page'] = 1
await reimu.reject("没时间等了!快说你要去哪里?", at_sender=True)
state["keyword"] = get_message_text(event.json())
state["page"] = 1
@reimu.handle()
async def _(bot: Bot, event: Event, state: T_State):
if str(event.get_message()) in ['帮助']:
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
if str(event.get_message()) in ["帮助"]:
await reimu.finish(__plugin_usage__)
if await UserCount.check_count(event.user_id, 'reimu', COUNT_PER_DAY_REIMU):
await reimu.finish('今天已经没车了,请明天再来...', at_sender=True)
if await UserCount.check_count(event.user_id, "reimu", COUNT_PER_DAY_REIMU):
await reimu.finish("今天已经没车了,请明天再来...", at_sender=True)
if _ulmt.check(event.user_id):
await reimu.finish('您还没下车呢,请稍等...', at_sender=True)
await reimu.finish("您还没下车呢,请稍等...", at_sender=True)
_ulmt.set_True(event.user_id)
msg = get_message_text(event.json())
args = msg.split(" ")
if msg in ['!', '!', '?', '?', ',', ',', '.', '。']:
if msg in ["!", "!", "?", "?", ",", ",", ".", "。"]:
await reimu.finish(__plugin_usage__)
if msg:
if len(args) > 1 and is_number(args[0]):
state['keyword'] = args[1]
state['page'] = args[0]
state["keyword"] = args[1]
state["page"] = args[0]
else:
state['keyword'] = msg
state['page'] = 1
state["keyword"] = msg
state["page"] = 1
@reimu.got('keyword', '你的目的地是哪?')
async def _(bot: Bot, event: Event, state: T_State):
@reimu.got("keyword", "你的目的地是哪?")
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
try:
keyword = state['keyword']
page = state['page']
print(keyword, page)
await UserCount.add_count(event.user_id, 'reimu')
await reimu.send('已经帮你关好车门了,请等待发车(不加真寻好友的话是欣赏不到旅途的风景的)', at_sender=True)
keyword = state["keyword"]
page = state["page"]
await UserCount.add_count(event.user_id, "reimu")
await reimu.send("已经帮你关好车门了,请等待发车(不加真寻好友的话是欣赏不到旅途的风景的)", at_sender=True)
reimu_report = await from_reimu_get_info(keyword, page)
if reimu_report:
await reimu.send(reimu_report)
@@ -77,20 +76,9 @@ async def _(bot: Bot, event: Event, state: T_State):
@scheduler.scheduled_job(
'cron',
# year=None,
# month=None,
# day=None,
# week=None,
# day_of_week="mon,tue,wed,thu,fri",
"cron",
hour=0,
minute=1,
# second=None,
# start_date=None,
# end_date=None,
# timezone=None,
)
async def _():
await UserCount.reset_count()
+91 -95
View File
@@ -11,106 +11,102 @@ from asyncio.exceptions import TimeoutError
async def from_reimu_get_info(key_word: str, page: int) -> str:
if "miku" in key_word.lower():
logger.warning("Taboo words are being triggered")
return None
return ''
repass = ""
url = 'https://blog.reimu.net/search/' + key_word + '/page/' + str(page)
url_s = 'https://blog.reimu.net/'
try:
if key_word == "最近的存档":
logger.debug("Now starting get the {}".format(url_s))
repass = await get_repass(url_s)
else:
logger.debug("Now starting get the {}".format(url))
repass = await get_repass(url)
except TimeoutError as e:
logger.error("Timeout! {}".format(e))
return repass
url = f"https://blog.reimu.net/search/{key_word}/page/{page}"
url_s = "https://blog.reimu.net/"
# try:
# if key_word == "最近的存档":
# logger.debug("Now starting get the {}".format(url_s))
# repass = await get_repass(url_s)
# else:
# logger.debug("Now starting get the {}".format(url))
# repass = await get_repass(url)
# except TimeoutError as e:
# logger.error("Timeout! {}".format(e))
#
# return repass
async def get_repass(url: str) -> str:
repass = ""
info = "[Note]注意大部分资源解压密码为⑨\n"
fund = None
print(url)
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, proxy=get_local_proxy(), timeout=15) as response:
html = etree.HTML(await response.text())
fund_l = html.xpath('//h1[@class="page-title"]/text()')
if fund_l:
fund = fund_l[0]
if fund == "未找到":
return "老司机也找不到路了……"
else:
pass
headers = html.xpath('//article/header/h2/a/text()')
urls = html.xpath('//article/header/h2/a/@href')
logger.debug("Now get {} post from search page".format(len(headers)))
headers_d = []
urls_d = []
for i, header in enumerate(headers):
if check_need_list(header):
headers_d.append(headers[i])
urls_d.append(urls[i])
else:
logger.debug("This title {} does not meet the requirements".format(header))
header_len = len(headers_d)
logger.debug("Get {} post after processing".format(header_len))
if header_len > MAXINFO_REIMU:
headers_d = headers_d[:MAXINFO_REIMU]
urls_d = urls_d[:MAXINFO_REIMU]
for h_s, url_s in zip(headers_d, urls_d):
if h_s != "审核结果存档":
time.sleep(1.5)
putline = await get_son_html_info(h_s, url_s)
if putline:
if repass:
repass = "\n\n- - - - - - - - \n".join([repass, putline])
else:
repass = putline
else:
logger.info("审核归档页面已跳过")
if repass:
repass = info + repass
return repass
# async def get_repass(url: str) -> str:
# repass = ""
# info = "[Note]注意大部分资源解压密码为⑨\n"
# fund = None
# print(url)
# async with aiohttp.ClientSession(headers=get_user_agent()) as session:
# async with session.get(url, proxy=get_local_proxy(), timeout=15) as response:
# html = etree.HTML(await response.text())
#
# fund_l = html.xpath('//h1[@class="page-title"]/text()')
# if fund_l:
# fund = fund_l[0]
# if fund == "未找到":
# return "老司机也找不到路了……"
# else:
# pass
#
# headers = html.xpath("//article/header/h2/a/text()")
# urls = html.xpath("//article/header/h2/a/@href")
# logger.debug("Now get {} post from search page".format(len(headers)))
#
# headers_d = []
# urls_d = []
# for i, header in enumerate(headers):
# if check_need_list(header):
# headers_d.append(headers[i])
# urls_d.append(urls[i])
# else:
# logger.debug(
# "This title {} does not meet the requirements".format(header)
# )
#
# header_len = len(headers_d)
# logger.debug("Get {} post after processing".format(header_len))
# if header_len > MAXINFO_REIMU:
# headers_d = headers_d[:MAXINFO_REIMU]
# urls_d = urls_d[:MAXINFO_REIMU]
#
# for h_s, url_s in zip(headers_d, urls_d):
# if h_s != "审核结果存档":
# time.sleep(1.5)
# putline = await get_son_html_info(h_s, url_s)
# if putline:
# if repass:
# repass = "\n\n- - - - - - - - \n".join([repass, putline])
# else:
# repass = putline
# else:
# logger.info("审核归档页面已跳过")
#
# if repass:
# repass = info + repass
# return repass
#
#
# async def get_son_html_info(h_s, url_s) -> str:
# repass = ""
# logger.debug("Now starting get the {}".format(url_s))
# async with aiohttp.ClientSession(headers=get_user_agent()) as session:
# async with session.get(url_s, proxy=get_local_proxy(), timeout=15) as response:
# html = etree.HTML(await response.text())
# pres = html.xpath('//div[@class="entry-content"]/pre/text()')
# a_texts = html.xpath('//div[@class="entry-content"]/pre//a/text()')
# a_hrefs = html.xpath('//div[@class="entry-content"]/pre//a/@href')
#
# if pres and a_texts and a_hrefs:
# while "" in pres:
# pres.remove("")
#
# repass = "【资源名称】 {}\n\n{}".format(h_s, pres[0].strip())
# for i, (a_t_s, a_h_s) in enumerate(zip(a_texts, a_hrefs)):
# a = "\n {} {} {} ".format(a_t_s, a_h_s, pres[i + 1].strip())
# repass += a
# else:
# logger.warning("Not get putline from {}".format(url_s))
#
# return repass
async def get_son_html_info(h_s, url_s) -> str:
repass = ""
logger.debug("Now starting get the {}".format(url_s))
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url_s, proxy=get_local_proxy(), timeout=15) as response:
html = etree.HTML(await response.text())
pres = html.xpath('//div[@class="entry-content"]/pre/text()')
a_texts = html.xpath('//div[@class="entry-content"]/pre//a/text()')
a_hrefs = html.xpath('//div[@class="entry-content"]/pre//a/@href')
if pres and a_texts and a_hrefs:
while "" in pres:
pres.remove("")
repass = "【资源名称】 {}\n\n{}".format(h_s, pres[0].strip())
for i, (a_t_s, a_h_s) in enumerate(zip(a_texts, a_hrefs)):
a = "\n {} {} {} ".format(a_t_s, a_h_s, pres[i + 1].strip())
repass += a
else:
logger.warning("Not get putline from {}".format(url_s))
return repass
def check_need_list(header: str) -> bool:
not_need = ['音乐', '御所动态']
for nd in not_need:
if nd in header:
return False
return True
# print(asyncio.get_event_loop().run_until_complete(from_reimu_get_info('萝莉')))
+29 -27
View File
@@ -1,4 +1,4 @@
from utils.init_result import image
from utils.message_builder import image
from utils.utils import scheduler, get_bot
from services.log import logger
from models.group_remind import GroupRemind
@@ -11,7 +11,7 @@ __name__ = "早晚安 [Hidden]"
# 早上好
@scheduler.scheduled_job(
'cron',
"cron",
# year=None,
# month=None,
# day=None,
@@ -28,22 +28,21 @@ async def _():
try:
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
gl = [g["group_id"] for g in gl]
for g in gl:
if await GroupRemind.get_status(g, 'zwa'):
if await GroupRemind.get_status(g, "zwa"):
result = image("zao.jpg", "zhenxun")
try:
await bot.send_group_msg(group_id=g,
message="早上好" + result)
await bot.send_group_msg(group_id=g, message="早上好" + result)
except ActionFailed:
logger.warning(f'{g} 群被禁言中,无法发送早安')
logger.warning(f"{g} 群被禁言中,无法发送早安")
except Exception as e:
logger.error(f'早晚安错误 e:{e}')
logger.error(f"早晚安错误 e:{e}")
# 睡觉了
@scheduler.scheduled_job(
'cron',
"cron",
hour=23,
minute=59,
)
@@ -51,22 +50,23 @@ async def _():
try:
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
gl = [g["group_id"] for g in gl]
for g in gl:
if await GroupRemind.get_status(g, 'zwa'):
if await GroupRemind.get_status(g, "zwa"):
result = image("sleep.jpg", "zhenxun")
try:
await bot.send_group_msg(group_id=g,
message="小真寻要睡觉了,你们也要早点睡呀" + result)
await bot.send_group_msg(
group_id=g, message="小真寻要睡觉了,你们也要早点睡呀" + result
)
except ActionFailed:
logger.warning(f'{g} 群被禁言中,无法发送晚安')
logger.warning(f"{g} 群被禁言中,无法发送晚安")
except Exception as e:
logger.error(f'早晚安错误 e:{e}')
logger.error(f"早晚安错误 e:{e}")
# 自动更新群组信息
@scheduler.scheduled_job(
'cron',
"cron",
hour=3,
minute=1,
)
@@ -74,19 +74,23 @@ async def _():
try:
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g['group_id'] for g in gl]
gl = [g["group_id"] for g in gl]
for g in gl:
group_info = await bot.get_group_info(group_id=g)
await GroupInfo.add_group_info(group_info['group_id'], group_info['group_name'],
group_info['max_member_count'], group_info['member_count'])
logger.info(f'自动更新群组 {g} 信息成功')
await GroupInfo.add_group_info(
group_info["group_id"],
group_info["group_name"],
group_info["max_member_count"],
group_info["member_count"],
)
logger.info(f"自动更新群组 {g} 信息成功")
except Exception as e:
logger.error(f'自动更新群组信息错误 e:{e}')
logger.error(f"自动更新群组信息错误 e:{e}")
# 自动更新好友信息
@scheduler.scheduled_job(
'cron',
"cron",
hour=3,
minute=1,
)
@@ -95,12 +99,13 @@ async def _():
bot = get_bot()
fl = await bot.get_friend_list(self_id=bot.self_id)
for f in fl:
if await FriendUser.add_friend_info(f['user_id'], f['nickname']):
if await FriendUser.add_friend_info(f["user_id"], f["nickname"]):
logger.info(f'自动更新好友 {f["user_id"]} 信息成功')
else:
logger.warning(f'自动更新好友 {f["user_id"]} 信息失败')
except Exception as e:
logger.error(f'自动更新群组信息错误 e:{e}')
logger.error(f"自动更新群组信息错误 e:{e}")
# 一次性任务
# 固定时间触发,仅触发一次:
@@ -189,6 +194,3 @@ async def _():
# misfire_grace_time=60, # 允许的误差时间,建议不要省略
# # jobstore='default', # 任务储存库,在下一小节中说明
# )
+8 -5
View File
@@ -5,7 +5,7 @@ from nonebot.adapters.cqhttp import GROUP, Bot, GroupMessageEvent, Message
from nonebot.typing import T_State
from utils.utils import get_message_text, is_number, get_message_at
from models.group_member_info import GroupInfoUser
from utils.init_result import at
from utils.message_builder import at
from models.russian_user import RussianUser
from models.bag_user import BagUser
from services.log import logger
@@ -93,7 +93,7 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if rs_player[event.group_id]['at'] != 0 and event.user_id != rs_player[event.group_id]['at']:
await accept.finish('又不是找你决斗,你拒绝什么啊!气!', at_sender=True)
if rs_player[event.group_id]['at'] == event.user_id:
at_player_name = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
at_player_name = (await GroupInfoUser.get_member_info(event.user_id, event.group_id)).user_name
await accept.send(Message(f'{at(rs_player[event.group_id][1])}\n'
f'{at_player_name}拒绝了你的对决!'))
rs_player[event.group_id] = {}
@@ -191,7 +191,10 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if at_:
at_ = at_[0]
at_player_name = event.sender.card if event.sender.card else event.sender.nickname
try:
at_player_name = (await GroupInfoUser.get_member_info(at_, event.group_id)).user_name
except AttributeError:
at_player_name = at(at_)
msg = f'{player1_name} 向 {at(at_)} 发起了决斗!请 {at_player_name} 在30秒内回复‘接受对决’ or ‘拒绝对决’,超时此次决斗作废!'
else:
at_ = 0
@@ -242,10 +245,10 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
await shot.finish(random.choice([
f'不要打扰 {player1_name} 和 {player2_name} 的决斗啊!',
'给我好好做好一个观众!不然小真寻就要生气了',
f'不要捣乱啊baka{(await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name}!'
f'不要捣乱啊baka{(await GroupInfoUser.get_member_info(event.user_id, event.group_id)).user_name}!'
]), at_sender=True)
await shot.finish(f'你的左轮不是连发的!该 '
f'{(await GroupInfoUser.select_member_info(int(rs_player[event.group_id]["next"]), event.group_id)).user_name} 开枪了')
f'{(await GroupInfoUser.get_member_info(int(rs_player[event.group_id]["next"]), event.group_id)).user_name} 开枪了')
if rs_player[event.group_id]['bullet'][rs_player[event.group_id]['index']] != 1:
await shot.send(Message(random.choice([
'呼呼,没有爆裂的声响,你活了下来',
+8 -7
View File
@@ -3,22 +3,23 @@ from utils.data_utils import init_rank
async def rank(group_id: int, itype) -> str:
users = await RussianUser.all_user(group_id)
all_users = await RussianUser.get_all_user(group_id)
all_user_id = [user.user_qq for user in all_users]
if itype == 'win_rank':
rank_name = '\t胜场排行榜\n'
all_user_data = [user.win_count for user in users]
all_user_data = [user.win_count for user in all_users]
elif itype == 'lose_rank':
rank_name = '\t败场排行榜\n'
all_user_data = [user.fail_count for user in users]
all_user_data = [user.fail_count for user in all_users]
elif itype == 'make_money':
rank_name = '\t赢取金币排行榜\n'
all_user_data = [user.make_money for user in users]
all_user_data = [user.make_money for user in all_users]
else:
rank_name = '\t输掉金币排行榜\n'
all_user_data = [user.lose_money for user in users]
all_user_data = [user.lose_money for user in all_users]
rst = ''
if users:
rst = await init_rank(users, all_user_data, group_id)
if all_users:
rst = await init_rank(all_user_id, all_user_data, group_id)
return rank_name + rst
+24 -20
View File
@@ -1,13 +1,13 @@
from nonebot import on_command
from .data_source import from_anime_get_info
from services.log import logger
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from configs.config import MAXINFO_GROUP_ANIME, MAXINFO_PRIVATE_ANIME
from utils.utils import get_message_text, get_message_type, UserExistLimiter
from utils.utils import get_message_text, UserExistLimiter
__plugin_name__ = '搜番'
__plugin_name__ = "搜番"
__plugin_usage__ = r"""
在群内使用此功能只返还5个结果,私聊返还 20 个结果(绝不能打扰老色批们看色图!)
搜索动漫资源
@@ -16,39 +16,43 @@ __plugin_usage__ = r"""
""".strip()
_ulmt = UserExistLimiter()
search_anime = on_command('搜番', aliases={'搜动漫'}, priority=5, block=True)
search_anime = on_command("搜番", aliases={"搜动漫"}, priority=5, block=True)
@search_anime.args_parser
async def _(bot: Bot, event: Event, state: T_State):
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if not msg:
await search_anime.reject('番名番名番名呢?', at_sender=True)
state['anime'] = msg
await search_anime.reject("番名番名番名呢?", at_sender=True)
state["anime"] = msg
@search_anime.handle()
async def _(bot: Bot, event: Event, state: T_State):
async def _(bot: Bot, event: MessageEvent, state: T_State):
if _ulmt.check(event.user_id):
await search_anime.finish('您有动漫正在搜索,请稍等...', at_sender=True)
await search_anime.finish("您有动漫正在搜索,请稍等...", at_sender=True)
_ulmt.set_True(event.user_id)
if get_message_text(event.json()):
state['anime'] = get_message_text(event.json())
state["anime"] = get_message_text(event.json())
@search_anime.got('anime', prompt='是不是少了番名?')
async def _(bot: Bot, event: Event, state: T_State):
key_word = state['anime']
await search_anime.send(f'开始搜番 {key_word}', at_sender=True)
anime_report = await from_anime_get_info(key_word, MAXINFO_GROUP_ANIME if get_message_type(event.json()) in ['group', 'discuss'] else MAXINFO_PRIVATE_ANIME)
@search_anime.got("anime", prompt="是不是少了番名?")
async def _(bot: Bot, event: MessageEvent, state: T_State):
key_word = state["anime"]
await search_anime.send(f"开始搜番 {key_word}", at_sender=True)
anime_report = await from_anime_get_info(
key_word,
MAXINFO_GROUP_ANIME
if isinstance(event, GroupMessageEvent)
else MAXINFO_PRIVATE_ANIME,
)
if anime_report:
await search_anime.send(anime_report)
logger.info(f"USER {event.user_id} GROUP"
f" {event.group_id if event.message_type != 'private' else 'private'} 搜索番剧 {key_word} 成功")
logger.info(
f"USER {event.user_id} GROUP"
f" {event.group_id if isinstance(event, GroupMessageEvent) else 'private'} 搜索番剧 {key_word} 成功"
)
else:
logger.warning(f"未找到番剧 {key_word}")
await search_anime.send(f"未找到番剧 {key_word}(也有可能是超时,再尝试一下?)")
_ulmt.set_False(event.user_id)
+28 -14
View File
@@ -7,41 +7,55 @@ import time
from utils.utils import get_local_proxy
async def from_anime_get_info(key_word: str, max: int) -> str:
async def from_anime_get_info(key_word: str, max_: int) -> str:
s_time = time.time()
repass = ""
url = 'https://share.dmhy.org/topics/rss/rss.xml?keyword=' + parse.quote(key_word)
url = "https://share.dmhy.org/topics/rss/rss.xml?keyword=" + parse.quote(key_word)
try:
logger.debug("Now starting get the {}".format(url))
repass = await get_repass(url, max)
repass = await get_repass(url, max_)
except Exception as e:
logger.error("Timeout! {}".format(e))
return f"搜索 {key_word} 结果(耗时 {int(time.time() - s_time)} 秒):\n" + repass
async def get_repass(url: str, max: int) -> str:
async def get_repass(url: str, max_: int) -> str:
putline = []
async with aiohttp.ClientSession() as session:
async with session.get(url, proxy=get_local_proxy(), timeout=20) as response:
d = feedparser.parse(await response.text())
url_list = [e.link for e in d.entries][:max]
url_list = [e.link for e in d.entries][:max_]
for u in url_list:
print(u)
try:
async with session.get(u, proxy=get_local_proxy(), timeout=20) as res:
async with session.get(
u, proxy=get_local_proxy(), timeout=20
) as res:
html = etree.HTML(await res.text())
magent = html.xpath('.//a[@id="a_magnet"]/text()')[0]
title = html.xpath('.//h3/text()')[0]
item = html.xpath('//div[@class="info resource-info right"]/ul/li')
class_a = item[0].xpath('string(.)')[5:].strip().replace("\xa0", "").replace("\t", "")
size = item[3].xpath('string(.)')[5:].strip()
title = html.xpath(".//h3/text()")[0]
item = html.xpath(
'//div[@class="info resource-info right"]/ul/li'
)
class_a = (
item[0]
.xpath("string(.)")[5:]
.strip()
.replace("\xa0", "")
.replace("\t", "")
)
size = item[3].xpath("string(.)")[5:].strip()
putline.append("【{}】| {}\n【{}】| {}".format(class_a, title, size, magent))
putline.append(
"【{}】| {}\n【{}】| {}".format(class_a, title, size, magent)
)
except Exception as e:
logger.warning(f'搜番超时 e:{e}')
logger.warning(f"搜番超时 e:{e}")
repass = '\n\n'.join(putline)
repass = "\n\n".join(putline)
return repass
# print(asyncio.get_event_loop().run_until_complete(from_anime_get_info('进击的巨人', 1234556)))
# print(asyncio.get_event_loop().run_until_complete(from_anime_get_info('进击的巨人', 1234556)))
+34 -25
View File
@@ -2,52 +2,51 @@ from nonebot import on_command
from .data_source import get_price, update_buff_cookie
from services.log import logger
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.rule import to_me
from nonebot.permission import SUPERUSER
from utils.utils import UserExistLimiter, get_message_text
__plugin_name__ = '查询皮肤'
__plugin_usage__ = '查询皮肤帮助:\n\t' \
'查询皮肤 [枪械名] [皮肤]\n\t' \
'示例: 查询皮肤 awp 二西莫夫'
__plugin_name__ = "查询皮肤"
__plugin_usage__ = "查询皮肤帮助:\n\t" "查询皮肤 [枪械名] [皮肤]\n\t" "示例: 查询皮肤 awp 二西莫夫"
_ulmt = UserExistLimiter()
search_skin = on_command('查询皮肤', aliases={'皮肤查询'}, priority=5, block=True)
search_skin = on_command("查询皮肤", aliases={"皮肤查询"}, priority=5, block=True)
@search_skin.args_parser
async def parse(bot: Bot, event: Event, state: T_State):
if get_message_text(event.json()) in ['取消', '算了']:
async def parse(bot: Bot, event: MessageEvent, state: T_State):
if get_message_text(event.json()) in ["取消", "算了"]:
await search_skin.finish("已取消操作..", at_sender=True)
state[state["_current_key"]] = str(event.get_message())
@search_skin.handle()
async def _(bot: Bot, event: Event, state: T_State):
if str(event.get_message()) in ['帮助']:
async def _(bot: Bot, event: MessageEvent, state: T_State):
if str(event.get_message()) in ["帮助"]:
await search_skin.finish(__plugin_usage__)
raw_arg = get_message_text(event.json())
if _ulmt.check(event.user_id):
await search_skin.finish('您有皮肤正在搜索,请稍等...', at_sender=True)
await search_skin.finish("您有皮肤正在搜索,请稍等...", at_sender=True)
if raw_arg:
args = raw_arg.split(" ")
if len(args) >= 2:
state['name'] = args[0]
state['skin'] = args[1]
state["name"] = args[0]
state["skin"] = args[1]
@search_skin.got('name', prompt="要查询什么武器呢?")
@search_skin.got('skin', prompt="要查询该武器的什么皮肤呢?")
async def arg_handle(bot: Bot, event: Event, state: T_State):
@search_skin.got("name", prompt="要查询什么武器呢?")
@search_skin.got("skin", prompt="要查询该武器的什么皮肤呢?")
async def arg_handle(bot: Bot, event: MessageEvent, state: T_State):
result = ""
_ulmt.set_True(event.user_id)
if state['name'] in ['ak', 'ak47']:
state['name'] = 'ak-47'
name = state['name'] + " | " + state['skin']
if state["name"] in ["ak", "ak47"]:
state["name"] = "ak-47"
name = state["name"] + " | " + state["skin"]
try:
result, status_code = await get_price(name)
except FileNotFoundError:
@@ -57,19 +56,29 @@ async def arg_handle(bot: Bot, event: Event, state: T_State):
await search_skin.finish(result)
if result:
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'}) 查询皮肤:" + name)
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 查询皮肤:"
+ name
)
_ulmt.set_False(event.user_id)
await search_skin.finish(result)
else:
logger.info(f"USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'}"
f" 查询皮肤:{name} 没有查询到")
logger.info(
f"USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}"
f" 查询皮肤:{name} 没有查询到"
)
_ulmt.set_False(event.user_id)
await search_skin.finish("没有查询到哦,请检查格式吧")
update_buff_session = on_command("更新cookie", rule=to_me(), permission=SUPERUSER, priority=1)
update_buff_session = on_command(
"更新cookie", rule=to_me(), permission=SUPERUSER, priority=1
)
@update_buff_session.handle()
async def _(bot: Bot, event: Event, state: T_State):
await update_buff_session.finish(update_buff_cookie(str(event.get_message())), at_sender=True)
async def _(bot: Bot, event: MessageEvent, state: T_State):
await update_buff_session.finish(
update_buff_cookie(str(event.get_message())), at_sender=True
)

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