diff options
Diffstat (limited to 'ATRI/plugins')
-rw-r--r-- | ATRI/plugins/admin.py | 146 | ||||
-rw-r--r-- | ATRI/plugins/admin/__init__.py | 7 | ||||
-rw-r--r-- | ATRI/plugins/admin/data_source.py | 0 | ||||
-rw-r--r-- | ATRI/plugins/character.py | 219 | ||||
-rw-r--r-- | ATRI/plugins/curse.py | 55 | ||||
-rw-r--r-- | ATRI/plugins/curse/__init__.py | 48 | ||||
-rw-r--r-- | ATRI/plugins/essential.py | 297 | ||||
-rw-r--r-- | ATRI/plugins/funny.py | 47 | ||||
-rw-r--r-- | ATRI/plugins/funny/__init__.py | 0 | ||||
-rw-r--r-- | ATRI/plugins/hitokoto.py | 106 | ||||
-rw-r--r-- | ATRI/plugins/setu/__init__.py | 77 | ||||
-rw-r--r-- | ATRI/plugins/setu/data_source.py | 27 | ||||
-rw-r--r-- | ATRI/plugins/utils/__init__.py | 76 | ||||
-rw-r--r-- | ATRI/plugins/utils/data_source.py | 240 | ||||
-rw-r--r-- | ATRI/plugins/utils/main.bin | bin | 3992353 -> 0 bytes |
15 files changed, 583 insertions, 762 deletions
diff --git a/ATRI/plugins/admin.py b/ATRI/plugins/admin.py new file mode 100644 index 0000000..1a158b5 --- /dev/null +++ b/ATRI/plugins/admin.py @@ -0,0 +1,146 @@ +import json +from pathlib import Path +from datetime import datetime + +from nonebot.permission import SUPERUSER +from nonebot.plugin import on_command, on_message +from nonebot.adapters.cqhttp import ( + Bot, + MessageEvent, + GroupMessageEvent +) + +from ATRI.exceptions import WriteError +from ATRI.log import logger + + +ADMIN_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'admin' + + +# 收集bot所在的群聊聊天记录 +chat_monitor = on_message() + +@chat_monitor.handle() +async def _chat_monitor(bot: Bot, event: GroupMessageEvent) -> None: + now_time = datetime.now().strftime('%Y-%m-%d') + file_name = f"{now_time}-chat.json" + path = ADMIN_DIR / f"{event.group_id}" / file_name + path.parent.mkdir(exist_ok=True, parents=True) + path.parent.touch(exist_ok=True) + + try: + data = json.loads(path.read_bytes()) + except FileExistsError: + data = {} + data[event.message_id] = { + "post_type": event.post_type, + "sub_type": event.sub_type, + "user_id": event.user_id, + "group_id": event.group_id, + "message_type": event.message_type, + "message": event.message, + "raw_message": event.raw_message, + "font": event.font, + "sender": event.sender, + "to_me": event.to_me + } + try: + with open(path, 'w', encoding='utf-8') as r: + r.write( + json.dumps( + data, indent=4 + ) + ) + logger.debug(f"写入消息成功,id: {event.message_id}") + except WriteError: + logger.error("消息记录失败,可能是缺少文件的原因!") + + +ESSENTIAL_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'essential' + +request_friend = on_command( + "好友申请", + permission=SUPERUSER +) + +@request_friend.handle() +async def _request_friend(bot: Bot, event: MessageEvent) -> None: + msg = str(event.message).split(" ") + key = msg[0] + data = {} + path = ESSENTIAL_DIR / "request_friend.json" + try: + data = json.loads(path.read_bytes()) + except FileExistsError: + await request_friend.finish("读取数据失败,可能并没有请求...") + + if key == "list": + msg0 = "" + for i in data.keys(): + msg0 += f"{i} | {data[i]['user_id']} | {data[i]['comment']}\n" + + msg = "好友申请列表如下:\n" + msg += msg0 + await request_friend.finish(msg) + + elif key == "y": + arg = msg[1] + await bot.set_friend_add_request(flag=arg, approve=True) + await request_friend.finish(f"完成~!已同意 {data[arg]['user_id']} 的申请") + + elif key == "n": + arg = msg[1] + await bot.set_friend_add_request(flag=arg, approve=False) + await request_friend.finish(f"完成~!已拒绝 {data[arg]['user_id']} 的申请") + + else: + await request_friend.finish("阿...请检查输入——!") + + +request_group = on_command( + "群聊申请", + permission=SUPERUSER +) + +@request_group.handle() +async def _request_group(bot: Bot, event: MessageEvent) -> None: + msg = str(event.message).split(" ") + key = msg[0] + data = {} + path = ESSENTIAL_DIR / "request_group.json" + try: + data = json.loads(path.read_bytes()) + except FileExistsError: + await request_friend.finish("读取数据失败,可能并没有请求...") + + if key == "list": + msg0 = "" + for i in data.keys(): + msg0 += f"{i} | {data[i]['sub_type']} | {data[i]['user_id']} | {data[i]['comment']}\n" + + msg = "群申请列表如下:\n" + msg += msg0 + await request_friend.finish(msg) + + elif key == "y": + arg = msg[1] + try: + await bot.set_group_add_request(flag=arg, + sub_type=data[arg]['sub_type'], + approve=False) + await request_friend.finish(f"完成~!已同意 {data[arg]['user_id']} 的申请") + except: + await request_friend.finish("请检查输入的值是否正确——!") + + elif key == "n": + arg = msg[1] + try: + await bot.set_group_add_request(flag=arg, + sub_type=data[arg]['sub_type'], + approve=False) + await request_friend.finish(f"完成~!已拒绝 {data[arg]['user_id']} 的申请") + except: + await request_friend.finish("请检查输入的值是否正确——!") + + else: + await request_friend.finish("阿...请检查输入——!") diff --git a/ATRI/plugins/admin/__init__.py b/ATRI/plugins/admin/__init__.py deleted file mode 100644 index dfc8f4b..0000000 --- a/ATRI/plugins/admin/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# ===========================[Begin Command Processing]=========================== - - - - - -# ===========================[End Command Processing]============================= diff --git a/ATRI/plugins/admin/data_source.py b/ATRI/plugins/admin/data_source.py deleted file mode 100644 index e69de29..0000000 --- a/ATRI/plugins/admin/data_source.py +++ /dev/null diff --git a/ATRI/plugins/character.py b/ATRI/plugins/character.py deleted file mode 100644 index 93dbc02..0000000 --- a/ATRI/plugins/character.py +++ /dev/null @@ -1,219 +0,0 @@ -from random import choice -from typing import Optional - -from nonebot.plugin import on_command, on_regex -from nonebot.adapters.cqhttp import Bot, Event - -from ATRI.rule import is_in_ban_list, is_in_dormant, to_bot -from ATRI.utils import count_list, del_list_aim, now_time -from ATRI.config import BOT_CONFIG, RUNTIME_CONFIG -from ATRI.service.plugin import Plugin - -# ===========================[Begin Command Processing]=========================== - -__plugin_name__ = 'call_robot' -__doc__ = """使用正则触发""" -Plugin.register(__plugin_name__, "func", __doc__, - command=BOT_CONFIG['callRobot']['command']) - -call_robot = on_regex('|'.join(BOT_CONFIG['callRobot']['command']), - rule=is_in_ban_list() & is_in_dormant(), - priority=4) - -@call_robot.handle() -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().call_robot(int(event.get_user_id()))) - - -__plugin_name__ = 'call_me' -__doc__ = """正确地呼叫咱""" -Plugin.register(__plugin_name__, "func", __doc__, - RUNTIME_CONFIG['nickname']) - -call_me = on_command(list(RUNTIME_CONFIG['nickname'])[0], - aliases=RUNTIME_CONFIG['nickname'], - rule=is_in_ban_list() & is_in_dormant()) - -@call_me.handle() -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().call_me()) - - -__plugin_name__ = 'tee_tee' -__doc__ = """一般人员不许贴! -需at""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['teetee']['command']) - -teeTee = on_command(BOT_CONFIG['teetee']['command'][0], - aliases=set(BOT_CONFIG['teetee']['command']), - rule=is_in_ban_list() & is_in_dormant() & to_bot()) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().tee_tee(int(event.get_user_id()))) - - - -__plugin_name__ = 'kani' -__doc__ = """カニ!カニ!!! -使用正则匹配""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['kani']['command']) - -kani = on_regex('|'.join(BOT_CONFIG['kani']['command']), - rule=is_in_ban_list() & is_in_dormant()) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().kani()) - - -__plugin_name__ = 'waste' -__doc__ = """不准骂咱废物 -使用正则匹配,需at""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['waste']['command']) - -waste = on_regex('|'.join(BOT_CONFIG['waste']['command']), - rule=is_in_ban_list() & is_in_dormant() & to_bot(), - priority=5) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().waste()) - - -__plugin_name__ = 'good_morning' -__doc__ = """略带涩气的早安 -需at""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['morning']['command']) - -morning = on_command(BOT_CONFIG['morning']['command'][0], - aliases=set(BOT_CONFIG['morning']['command']), - rule=is_in_ban_list() & is_in_dormant() & to_bot()) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().morning()) - - -__plugin_name__ = 'good_noon' -__doc__ = """做白日梦 -需at""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['noon']['command']) - -noon = on_command(BOT_CONFIG['noon']['command'][0], - aliases=set(BOT_CONFIG['noon']['command']), - rule=is_in_ban_list() & is_in_dormant() & to_bot()) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().noon()) - - -__plugin_name__ = 'good_night' -__doc__ = """晚安~! -需at""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['night']['command']) - -night = on_command(BOT_CONFIG['night']['command'][0], - aliases=set(BOT_CONFIG['night']['command']), - rule=is_in_ban_list() & is_in_dormant() & to_bot()) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().night()) - - -__plugin_name__ = 'cant_do_anything' -__doc__ = """吃饭第一名!好吃就是高兴!! -使用正则匹配""" -Plugin.register(__plugin_name__, "func", __doc__, - BOT_CONFIG['cantdo']['command']) - -cantdo = on_regex('|'.join(BOT_CONFIG['cantdo']['command']), - rule=is_in_ban_list() & is_in_dormant()) - -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, ATRI().cantdo()) - - -# ===========================[End Command Processing]============================= - -callrobot_list = [] - - -class ATRI: - def call_robot(self, user: Optional[int]) -> str: - global callrobot_list - result = '' - for i in range(0, 5): - if count_list(callrobot_list, user) == i: - result = choice(BOT_CONFIG['callRobot']['repo'][i]) - callrobot_list.append(user) - if count_list(callrobot_list, user) == 5: - callrobot_list = del_list_aim(callrobot_list, user) - break - else: - continue - return result - - def call_me(self) -> str: - return choice(BOT_CONFIG['atri']['repo']) - - def tee_tee(self, user: Optional[int]) -> str: - if user in RUNTIME_CONFIG['superusers']: - return choice(BOT_CONFIG['teetee']['repo']['superusers']) - else: - return choice(BOT_CONFIG['teetee']['repo']['user']) - - def kani(self) -> str: - return choice(BOT_CONFIG['kani']['repo']) - - def waste(self) -> str: - return choice(BOT_CONFIG['waste']['repo']) - - def morning(self) -> str: - period = BOT_CONFIG['morning']['repo'] - if period[0]['period'][0] <= now_time() < period[0]['period'][1]: - return choice(period[0]['repo']) - elif period[1]['period'][0] <= now_time() < period[1]['period'][1]: - return choice(period[1]['repo']) - elif period[2]['period'][0] <= now_time() < period[2]['period'][1]: - return choice(period[2]['repo']) - elif period[3]['period'][0] <= now_time() < period[3]['period'][1]: - return choice(period[3]['repo']) - elif period[4]['period'][0] <= now_time() < period[4]['period'][1]: - return choice(period[4]['repo']) - else: - return choice(period['error']) - - def noon(self) -> str: - if BOT_CONFIG['noon']['period'][0] <= now_time( - ) < BOT_CONFIG['noon']['period'][1]: - return choice(BOT_CONFIG['noon']['repo']) - else: - return choice(BOT_CONFIG['noon']['error']) - - def night(self) -> str: - period = BOT_CONFIG['night']['repo'] - if period[0]['period'][0] <= now_time() < period[0]['period'][1]: - return choice(period[0]['repo']) - elif period[1]['period'][0] <= now_time() < period[1]['period'][1]: - return choice(period[1]['repo']) - elif period[2]['period'][0] <= now_time() < period[2]['period'][1]: - return choice(period[2]['repo']) - elif period[3]['period'][0] <= now_time() < period[3]['period'][1]: - return choice(period[3]['repo']) - elif period[4]['period'][0] <= now_time() < period[4]['period'][1]: - return choice(period[4]['repo']) - else: - return choice(period['error']) - - def cantdo(self) -> str: - return choice(BOT_CONFIG['cantdo']['repo']) diff --git a/ATRI/plugins/curse.py b/ATRI/plugins/curse.py deleted file mode 100644 index 2fa4986..0000000 --- a/ATRI/plugins/curse.py +++ /dev/null @@ -1,55 +0,0 @@ -from random import choice -from nonebot.plugin import on_command -from nonebot.adapters.cqhttp import Bot - -from ATRI.request import Request -from ATRI.utils import count_list, del_list_aim -from ATRI.config import CURSE_CONFIG -from ATRI.exceptions import InvalidRequest -from ATRI.service.plugin import Plugin -from ATRI.rule import is_in_ban_list, is_in_service, is_in_dormant, to_bot - - - -# ===========================[Begin Command Processing]=========================== - - -__plugin_name__ = 'curse' -__doc__ = """口臭一下""" -Plugin.register(__plugin_name__, "func", __doc__, - CURSE_CONFIG['curse']['command']) - -curse = on_command(CURSE_CONFIG['curse']['command'][0], - aliases=set(CURSE_CONFIG['curse']['command']), - rule=is_in_ban_list() & is_in_dormant() - & is_in_service(__plugin_name__) - & to_bot()) - -async def _(bot: Bot, event) -> None: - await bot.send( - event, await Function().curse(str(event.get_user_id()))) - - -# ===========================[End Command Processing]============================= - -curse_list = [] - - -class Function: - async def curse(self, user: str): - global curse_list - - if count_list(curse_list, user) == 3: - curse_list.append(user) - return choice(CURSE_CONFIG['curse']['times'][3]['repo']) - elif count_list(curse_list, user) == 6: - curse_list = del_list_aim(curse_list, user) - return choice(CURSE_CONFIG['curse']['times'][6]['repo']) - else: - try: - curse_list.append(user) - return str(await Request.get_text( - url=CURSE_CONFIG['curse']['url'])) - except InvalidRequest: - raise InvalidRequest('请求失败') diff --git a/ATRI/plugins/curse/__init__.py b/ATRI/plugins/curse/__init__.py new file mode 100644 index 0000000..e2edbb5 --- /dev/null +++ b/ATRI/plugins/curse/__init__.py @@ -0,0 +1,48 @@ +from nonebot.plugin import on_command +from nonebot.adapters.cqhttp import Bot, MessageEvent + +from ATRI.rule import ( + is_in_banlist, + is_in_dormant, + is_in_service +) +from ATRI.utils.list import count_list, del_list_aim +from ATRI.utils.request import get_text +from ATRI.exceptions import RequestTimeOut + + +URL = "https://zuanbot.com/api.php?level=min&lang=zh_cn" +sick_list = [] + + +__plugin_name__ = 'curse' + +curse = on_command( + "口臭一下", + aliases={"口臭", "骂我"}, + rule=is_in_banlist() & is_in_dormant() + & is_in_service(__plugin_name__) +) + +async def _curse(bot: Bot, event: MessageEvent) -> None: + global sick_list + user = event.get_user_id() + + if count_list(sick_list, user) == 3: + sick_list.append(user) + repo = ( + "不是??你这么想被咱骂的嘛??" + "被咱骂就这么舒服的吗?!" + "该......你该不会是.....M吧!" + ) + await curse.finish(repo) + elif count_list(sick_list, user) == 6: + sick_list = del_list_aim(sick_list, user) + await curse.finish("给我适可而止阿!?") + else: + sick_list.append(user) + try: + await curse.finish(await get_text(URL)) + except RequestTimeOut: + raise RequestTimeOut("Time out!") diff --git a/ATRI/plugins/essential.py b/ATRI/plugins/essential.py new file mode 100644 index 0000000..22f641f --- /dev/null +++ b/ATRI/plugins/essential.py @@ -0,0 +1,297 @@ +import time +import json +import shutil +from pathlib import Path +from random import choice + +from nonebot.adapters import Bot +from nonebot.plugin import on_notice, on_request +from nonebot.adapters.cqhttp.message import Message +from nonebot.adapters.cqhttp import ( + FriendRequestEvent, + GroupRequestEvent, + GroupIncreaseNoticeEvent, + GroupDecreaseNoticeEvent, + GroupAdminNoticeEvent, + GroupBanNoticeEvent, + LuckyKingNotifyEvent, + GroupUploadNoticeEvent, + GroupRecallNoticeEvent, + FriendRecallNoticeEvent +) + +from ATRI.log import logger +from ATRI.exceptions import WriteError +from ATRI.config import nonebot_config +from ATRI.rule import is_in_banlist +from ATRI.service.httppost import HttpPost +from main import driver + + +PLUGIN_INFO_DIR = Path('.') / 'ATRI' / 'data' / 'service' / 'plugins' + [email protected]_startup +async def startup() -> None: + logger.info("アトリは、高性能ですから!") + + [email protected]_shutdown +async def shutdown() -> None: + logger.info("Thanks for using.") + logger.debug("bot已停止运行,正在清理插件信息...") + try: + shutil.rmtree(PLUGIN_INFO_DIR) + logger.debug("成功!") + except: + repo = ( + '清理插件信息失败', + '请前往 ATRI/data/service 下', + '将 plugins 整个文件夹删除' + ) + logger.error(repo) + time.sleep(10) + pass + + [email protected]_bot_connect +async def connect(bot) -> None: + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + int(superuser), + "WebSocket 成功连接,数据开始传输。" + ) + + [email protected]_bot_disconnect +async def disconnect(bot) -> None: + for superuser in nonebot_config["superusers"]: + try: + await HttpPost.send_private_msg( + int(superuser), + "WebSocket 貌似断开了呢..." + ) + except: + logger.error("WebSocket 已断开,等待重连") + + +ESSENTIAL_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'essential' + +# 处理:好友请求 +request_friend_event = on_request(rule=is_in_banlist()) + +@request_friend_event.handle() +async def _request_friend_event(bot, event: FriendRequestEvent) -> None: + file_name = "request_friend.json" + path = ESSENTIAL_DIR / file_name + path.parent.mkdir(exist_ok=True, parents=True) + + try: + data = json.loads(path.read_bytes()) + except FileExistsError: + data = {} + data[event.flag] = { + "user_id": event.user_id, + "comment": event.comment + } + try: + with open(path, 'w', encoding='utf-8') as r: + r.write( + json.dumps( + data, indent=4 + ) + ) + except WriteError: + raise WriteError("Writing file failed!") + + for superuser in nonebot_config["superusers"]: + msg = ( + "主人,收到一条好友请求:\n" + f"请求人:{event.get_user_id()}\n" + f"申请信息:{event.comment}\n" + f"申请码:{event.flag}" + ) + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) + + +# 处理:邀请入群,如身为管理,还附有入群请求 +request_group_event = on_request(rule=is_in_banlist()) + +@request_group_event.handle() +async def _request_group_event(bot, event: GroupRequestEvent) -> None: + file_name = "request_group.json" + path = ESSENTIAL_DIR / file_name + path.parent.mkdir(exist_ok=True, parents=True) + + try: + data = json.loads(path.read_bytes()) + except FileExistsError: + data = {} + data[event.flag] = { + "user_id": event.user_id, + "group_id": event.group_id, + "sub_type": event.sub_type, + "comment": event.comment + } + try: + with open(path, 'w', encoding='utf-8') as r: + r.write( + json.dumps( + data, indent=4 + ) + ) + except WriteError: + raise WriteError("Writing file failed!") + + for superuser in nonebot_config["superusers"]: + msg = ( + "主人,收到一条入群请求:\n" + f"请求人:{event.get_user_id()}\n" + f"申请信息:{event.comment}\n" + f"申请码:{event.flag}" + ) + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) + + +# 处理群成员变动 +group_member_event = on_notice() + +@group_member_event.handle() +async def _group_member_event(bot: Bot, event) -> None: + if isinstance(event, GroupIncreaseNoticeEvent): + msg = ( + "好欸!事新人!\n" + f"在下 {choice(list(nonebot_config['nickname']))} 哒!w!" + ) + await group_member_event.finish(msg) + + elif isinstance(event, GroupDecreaseNoticeEvent): + if event.is_tome(): + msg = ( + "呜呜呜,主人" + f"咱被群 {event.group_id} 里的 {event.operator_id} 扔出来了..." + ) + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) + else: + await group_member_event.finish(f"{event.user_id} 离开了我们...") + + +# 处理群管理事件 +group_admin_event = on_notice() + +@group_admin_event.handle() +async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent) -> None: + if event.is_tome(): + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + user_id=int(superuser), + message=f"好欸!主人!我在群 {event.group_id} 成为了管理!!" + ) + + +# 处理群禁言事件 +group_ban_event = on_notice() + +@group_ban_event.handle() +async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent) -> None: + if event.is_tome(): + if event.duration: + msg = ( + "那个..。,主人\n" + f"咱在群 {event.group_id} 被 {event.operator_id} 塞上了口球...\n" + f"时长...是 {event.duration} 秒" + ) + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) + else: + msg = ( + "好欸!主人\n" + f"咱在群 {event.group_id} 被 {event.operator_id} 上的口球解除了!" + ) + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) + + +# 处理群红包运气王事件 +lucky_read_bag_event = on_notice() + +@lucky_read_bag_event.handle() +async def _lucky_read_bag_event(bot, event: LuckyKingNotifyEvent) -> None: + msg = ( + "8行,这可忍?" + f"gkd [CQ:at,qq={event.user_id}] 发一个!" + ) + await lucky_read_bag_event.finish(Message(msg)) + + +# 处理群文件上传事件 +group_file_upload_event = on_notice() + +@group_file_upload_event.handle() +async def _group_file_upload_event(bot, event: GroupUploadNoticeEvent) -> None: + await group_file_upload_event.finish("让我康康传了啥好东西") + + +# 处理撤回事件 +recall_event = on_notice() + +@recall_event.handle() +async def _recall_event(bot: Bot, event) -> None: + if isinstance(event, GroupRecallNoticeEvent): + repo = await bot.call_api( + "get_msg", + message_id=event.message_id + ) + repo = str(repo["message"]) + if "CQ" in repo: + repo = repo.replace("CQ", "QC") + + msg = ( + "主人,咱拿到了一条撤回信息!\n" + f"{event.user_id}@[群:{event.group_id}]\n" + "撤回了\n" + f"{repo}" + ) + + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) + + elif isinstance(event, FriendRecallNoticeEvent): + repo = await bot.call_api( + "get_msg", + message_id=event.message_id + ) + repo = str(repo["message"]) + if "CQ" in repo: + repo = repo.replace("CQ", "QC") + + msg = ( + "主人,咱拿到了一条撤回信息!\n" + f"{event.user_id}@[私聊]" + "撤回了\n" + f"{repo}" + ) + + for superuser in nonebot_config["superusers"]: + await HttpPost.send_private_msg( + user_id=int(superuser), + message=msg + ) diff --git a/ATRI/plugins/funny.py b/ATRI/plugins/funny.py new file mode 100644 index 0000000..9d31ef6 --- /dev/null +++ b/ATRI/plugins/funny.py @@ -0,0 +1,47 @@ +from pathlib import Path +from random import choice, randint + +from nonebot.adapters.cqhttp import Bot, MessageEvent +from nonebot.plugin import on_command, on_message + +from ATRI.rule import ( + is_in_banlist, + is_in_dormant, + is_in_service +) + + +__plugin_name__ = "laugh" + +get_laugh = on_command( + "来句笑话", + rule=is_in_banlist() & is_in_dormant() + & is_in_service(__plugin_name__) +) + +@get_laugh.handle() +async def _get_laugh(bot: Bot, event: MessageEvent) -> None: + user_name = event.sender.nickname + laugh_list = [] + + FILE = Path('.') / 'ATRI' / 'data' / 'database' / 'funny' / 'laugh.txt' + with open(FILE, 'r', encoding='utf-8') as r: + for line in r: + laugh_list.append(line.strip('\n')) + + result = choice(laugh_list) + await get_laugh.finish(result.replace("%name", user_name)) + + +__plugin_name__ = "wty" + +me_to_you = on_message( + rule=is_in_banlist() & is_in_dormant() & is_in_service(__plugin_name__) +) + +@me_to_you.handle() +async def _me_to_you(bot: Bot, event: MessageEvent) -> None: + rd = randint(0, 4) + if rd == 1: + msg = str(event.get_message()) + await me_to_you.finish(msg.replace('我', '你')) diff --git a/ATRI/plugins/funny/__init__.py b/ATRI/plugins/funny/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/ATRI/plugins/funny/__init__.py +++ /dev/null diff --git a/ATRI/plugins/hitokoto.py b/ATRI/plugins/hitokoto.py index cf03b6f..7f7eae6 100644 --- a/ATRI/plugins/hitokoto.py +++ b/ATRI/plugins/hitokoto.py @@ -1,76 +1,56 @@ +import os import json from pathlib import Path from random import choice, randint from nonebot.plugin import on_command -from nonebot.adapters.cqhttp import Bot, Event +from nonebot.adapters.cqhttp import Bot, MessageEvent -from ATRI.exceptions import InvalidLoad -from ATRI.rule import is_in_ban_list, is_in_dormant, is_in_service, to_bot -from ATRI.utils import del_list_aim, count_list -from ATRI.request import Request -from ATRI.config import HITOKOTO_CONFIG -from ATRI.service.plugin import Plugin +from ATRI.rule import ( + is_in_banlist, + is_in_dormant, + is_in_service, + to_bot +) +from ATRI.exceptions import LoadingError +from ATRI.utils.list import count_list, del_list_aim -# ===========================[Begin Command Processing]=========================== + +HITOKOTO_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'hitokoto' +sick_list = [] __plugin_name__ = 'hitokoto' -__doc__ = """一言""" -Plugin.register(__plugin_name__, "func", __doc__, - HITOKOTO_CONFIG['hitokoto']['command']) -hitokoto = on_command(HITOKOTO_CONFIG['hitokoto']['command'][0], - aliases=set(HITOKOTO_CONFIG['hitokoto']['command']), - rule=is_in_ban_list() & is_in_dormant() - & is_in_service(__plugin_name__) - & to_bot()) +hitokoto = on_command( + "一言", + aliases={"抑郁一下", "网抑云"}, + rule=is_in_banlist() & is_in_dormant() + & is_in_service(__plugin_name__) & to_bot() +) @hitokoto.handle() -async def _(bot: Bot, event: Event) -> None: - await bot.send(event, await Function().hitokoto(str(event.get_user_id()))) - - -# ===========================[End Command Processing]============================= - -hitokoto_list = [] -local_path = Path('.') / 'ATRI' / 'data' / 'database' / 'hitokoto' - -class Function: - async def hitokoto(self, user: str): - def local() -> str: - rd = choice(HITOKOTO_CONFIG['hitokoto']['local']['file']) - path = local_path / f"{rd}" - data = {} - try: - data = json.loads(path.read_bytes()) - except InvalidLoad: - raise InvalidLoad('Failed to read file!') - return data[randint(1, len(data)) - 1]['hitokoto'] - - async def link() -> str: - url = HITOKOTO_CONFIG['hitokoto']['link']['url'] - return str( - await Request.get_text( - url=url - ) - ) - - global hitokoto_list - - if count_list(hitokoto_list, user) == 3: - hitokoto_list.append(user) - return choice(HITOKOTO_CONFIG['hitokoto']['times'][3]['repo']) - elif count_list(hitokoto_list, user) == 6: - hitokoto_list = del_list_aim(hitokoto_list, user) - return choice(HITOKOTO_CONFIG['hitokoto']['times'][6]['repo']) - else: - hitokoto_list.append(user) - if HITOKOTO_CONFIG['hitokoto']['link']['use']: - rd = randint(1,2) - if rd == 1: - return await link() - else: - return local() - else: - return local() +async def _hitokoto(bot: Bot, event: MessageEvent) -> None: + global sick_list + user = event.get_user_id() + + if count_list(sick_list, user) == 3: + sick_list.append(user) + await hitokoto.finish("额......需要咱安慰一下嘛~?") + elif count_list(sick_list, user) == 6: + sick_list = del_list_aim(sick_list, user) + msg = ( + "如果心里感到难受就赶快去睡觉!别再憋自己了!\n" + "我...我会守在你身边的!...嗯..一定" + ) + await hitokoto.finish(msg) + else: + sick_list.append(user) + rd = choice(os.listdir(HITOKOTO_DIR)) + path = HITOKOTO_DIR / rd + data = {} + try: + data = json.loads(path.read_bytes()) + except LoadingError: + raise LoadingError("Loading error!") + await hitokoto.finish(data[randint(1, len(data) - 1)]['hitokoto']) diff --git a/ATRI/plugins/setu/__init__.py b/ATRI/plugins/setu/__init__.py deleted file mode 100644 index 2d630de..0000000 --- a/ATRI/plugins/setu/__init__.py +++ /dev/null @@ -1,77 +0,0 @@ -import random - -from nonebot.plugin import on_regex, on_command -from nonebot.adapters.cqhttp.message import MessageSegment, Message -from nonebot.adapters.cqhttp import Bot -from nonebot.permission import SUPERUSER -from nonebot.adapters.cqhttp.event import MessageEvent - -from ATRI.service.plugin import Plugin -from ATRI.config import SETU_CONFIG -from ATRI.utils import compress_image -from ATRI.request import Request -from ATRI.rule import is_in_service, is_in_ban_list, is_in_dormant - -from .data_source import setu_port - -# ===========================[Begin Command Processing]=========================== - -resolution = 1 - - -__plugin_name__ = 'setu' -__doc__ = """ -涩图,开冲! -使用正则匹配 -""" -Plugin.register(plugin_name=__plugin_name__, _type="func", doc=__doc__, command=SETU_CONFIG['setu']['command']) - -setu = on_regex('|'.join(SETU_CONFIG['setu']['command']), - rule=is_in_service(__plugin_name__) & is_in_ban_list() - & is_in_dormant()) - -async def _(bot: Bot, event: MessageEvent) -> None: - await bot.send(event, SETU_CONFIG['setu']['repo']['waiting']) - rd = random.randint(1, 2) - - if rd == 1: - data = await setu_port() - else: - data = await setu_port() - - if resolution == 1: - img = compress_image(await Request.get_image(data['data'][0]['url'])) - else: - img = await Request.get_image(data['data'][0]['url']) - - msg0 = ( - f"{data['data'][0]['title']}\n" - f"pid: {data['data'][0]['pid']}\n" - f"{MessageSegment.image(file=f'file:///{img}')}" - ) - - await setu.finish(Message(msg0)) - - -setu_resolution = on_command(SETU_CONFIG['admin']['command'][0], - aliases=set(SETU_CONFIG['admin']['command']), - permission=SUPERUSER) - -@setu_resolution.handle() -async def _(bot, event: MessageEvent, state: dict) -> None: - msg = str(event.get_message()).strip() - if msg: - state['msg'] = msg - -@setu_resolution.got('msg', prompt='请键入正确参数奥') -async def _(bot, event: MessageEvent, state: dict) -> None: - global resolution - resolution = int(state['msg']) - - if resolution == 1: - await setu_resolution.finish('完成~!已启用涩图压缩') - else: - await setu_resolution.finish('完成~!已关闭涩图压缩') - -# ===========================[End Command Processing]============================= diff --git a/ATRI/plugins/setu/data_source.py b/ATRI/plugins/setu/data_source.py deleted file mode 100644 index 521b716..0000000 --- a/ATRI/plugins/setu/data_source.py +++ /dev/null @@ -1,27 +0,0 @@ -import json -from pathlib import Path - -from ATRI.config import SETU_CONFIG -from ATRI.request import Request -from ATRI.exceptions import InvalidRequest - - -DATA_PATH = Path('.') / 'ATRI' / 'data' / 'database' - -async def setu_port() -> dict: - url = SETU_CONFIG['setu']['link']['url'] - params = { - "apikey": SETU_CONFIG['setu']['link']['api_key'], - "r18": 0, - "num": 1 - } - data = {} - try: - data = json.loads(await Request.post_bytes(url, params)) - except InvalidRequest: - raise InvalidRequest('Request failed!') - return data - - -async def setu_local() -> str: - ... diff --git a/ATRI/plugins/utils/__init__.py b/ATRI/plugins/utils/__init__.py index 4204cfb..e69de29 100644 --- a/ATRI/plugins/utils/__init__.py +++ b/ATRI/plugins/utils/__init__.py @@ -1,76 +0,0 @@ -import re -from nonebot.matcher import Matcher -from nonebot.plugin import on_command -from nonebot.adapters.cqhttp import Bot, Event - -from ATRI.config import UTILS_CONFIG -from ATRI.rule import is_in_ban_list, is_in_dormant, is_in_service - -from .data_source import Function - -# ===========================[Begin Command Processing]=========================== - - -__plugin_name_0__ = 'roll' -roll = on_command(UTILS_CONFIG['utils']['roll']['command'][0], - aliases=set(UTILS_CONFIG['utils']['roll']['command']), - rule=is_in_ban_list() & is_in_dormant() - & is_in_service(__plugin_name_0__)) - -__plugin_name_1__ = 'rcnb' -rcnbEncode = on_command( - UTILS_CONFIG['utils']['rcnb']['encode']['command'][0], - aliases=set( - UTILS_CONFIG['utils']['rcnb']['encode']['command']), - rule=is_in_ban_list() & is_in_dormant() - & is_in_service(__plugin_name_1__)) - -rcnbDecode = on_command( - UTILS_CONFIG['utils']['rcnb']['decode']['command'][0], - aliases=set( - UTILS_CONFIG['utils']['rcnb']['decode']['command']), - rule=is_in_ban_list() & is_in_dormant() - & is_in_service(__plugin_name_1__)) - - -async def _(bot, event: Event, state: dict) -> None: - args = str(event.get_message()).strip() - print(args) - if args: - state['result'] = args - [email protected]('result', prompt='roll参数不能为空!..\ndemo: 1d10 或 2d10+3d10') -async def _(matcher: Matcher, bot: Bot, event: Event, state: dict) -> None: - resu = state['result'] - match = re.match(r'^([\dd+\s]+?)$', resu) - print(match) - if not match: - await matcher.reject('格式不-正-确!\ndemo: 1d10 或 2d10+3d10') - await bot.send(event, Function.roll_dice(par=resu)) - - -async def _(bot, event: Event, state: dict) -> None: - args = str(event.get_message()).strip() - if args: - state['result'] = args - [email protected]('result', prompt='请告诉咱需要加密的字符~!') -async def _(bot: Bot, event: Event, state: dict) -> None: - print(state['result']) - await bot.send(event, Function.RCNB.encode(state['result'])) - - -async def _(bot, event: Event, state: dict) -> None: - args = str(event.get_message()).strip() - if args: - state['result'] = args - [email protected]('result', prompt='请告诉咱需要解密的字符~!') -async def _(bot: Bot, event: Event, state: dict) -> None: - await bot.send(event, Function.RCNB.decode(state['result'])) - - -# ===========================[End Command Processing]============================= diff --git a/ATRI/plugins/utils/data_source.py b/ATRI/plugins/utils/data_source.py index 4d7ddb6..b83cd33 100644 --- a/ATRI/plugins/utils/data_source.py +++ b/ATRI/plugins/utils/data_source.py @@ -1,239 +1,3 @@ -import re -import os -import json -import random -from math import floor -from pathlib import Path -from zipfile import PyZipFile -from typing import Tuple, Union -from random import choice, randint -from typing import Dict, List +from nonebot.adapters.cqhttp.message import MessageSegment -from ATRI.config import UTILS_CONFIG - - -class Function: - @staticmethod - def roll_dice(par: str) -> str: - result = 0 - proc = '' - proc_list = [] - p = par.split('+') - - for i in p: - args = re.findall(r"(\d{0,10})(?:(d)(\d{1,10}))", i) - args = list(args[0]) - if not args[0]: - args[0] = 1 - if int(args[0]) >= 5000 or int(args[2]) >= 5000: - return choice(UTILS_CONFIG['utils']['roll']['tooBig']['repo']) - for a in range(1, int(args[0]) + 1): - rd = randint(1, int(args[2])) - result = result + rd - if len(proc_list) <= 10: - proc_list.append(rd) - - if len(proc_list) <= 10: - proc += '+'.join(map(str, proc_list)) - elif len(proc_list) >= 10: - proc += choice(UTILS_CONFIG['utils']['roll']['tooLong']['repo']) - else: - proc += str(result) - - msg = f'{par}=({proc})={result}' - print(msg) - return msg - - class Generate: - ''' - (*彩蛋*) - 由于此功能触及法律故不用作上线功能,写于此地只为学习 - 请勿用作网上购物、交易和注册 - 随机身份证根据国家标准(GB11643-1999)生成 - 并不存在所谓: - - 生成在逃犯号码 - ''' - @classmethod - def __init__(cls) -> None: - cls.DATA_PATH = Path('.') / 'ATRI' / 'plugins' / 'utils' / 'main.bin' - - @classmethod - def info_id(cls) -> Tuple[Dict[str, List[str]], Dict[str, str]]: - with PyZipFile(os.path.abspath(cls.DATA_PATH), 'r') as zipFile: - with zipFile.open('name.json', 'r') as f: - name = json.loads(f.read().decode()) - with zipFile.open('area.json', 'r') as f: - area = json.loads(f.read().decode()) - return name, area - - @staticmethod - def number_id(area: int, gender: int, birth: int) -> str: - ''' - 校验码计算公式: (12-∑(Ai×Wi)(mod 11))mod 11 - 验证公式: 请查阅(ISO 7064:1983.MOD 11-2) - ''' - def check_sum(full_code: str): - assert len(full_code) == 17 - check_sum = sum([((1 << (17 - i)) % 11) * int(full_code[i]) - for i in range(0, 17)]) - check_digit = (12 - (check_sum % 11)) % 11 - if check_digit < 10: - return check_digit - else: - return 'X' - - order_code = str(random.randint(10, 99)) - gender_code = str(random.randrange(gender, 10, step=2)) - full_code = str(area) + str(birth) + str(order_code) + str(gender_code) - full_code += str(check_sum(full_code)) - return full_code - - class RCNB: - @classmethod - def __init__(cls) -> None: - cls.cr = 'rRŔŕŖŗŘřƦȐȑȒȓɌɍ' - cls.cc = 'cCĆćĈĉĊċČčƇƈÇȻȼ' - cls.cn = 'nNŃńŅņŇňƝƞÑǸǹȠȵ' - cls.cb = 'bBƀƁƃƄƅßÞþ' - - cls.sr = len(cls.cr) - cls.sc = len(cls.cc) - cls.sn = len(cls.cn) - cls.sb = len(cls.cb) - cls.src = cls.sr * cls.sc - cls.snb = cls.sn * cls.sb - cls.scnb = cls.sc * cls.snb - - @staticmethod - def _div(a: int, b: int) -> int: - return floor(a / b) - - @classmethod - def _encode_byte(cls, i) -> Union[str, None]: - if i > 0xFF: - raise ValueError('ERROR! rc/nb overflow') - - if i > 0x7F: - i = i & 0x7F - return cls.cn[i // cls.sb] + cls.cb[i % cls.sb] - # return f'{cls.cn[i // cls.sb]}{cls.cb[i % cls.sb]}' - # return cls.cn[cls._div(i, cls.sb) + int(cls.cb[i % cls.sb])] - - return cls.cr[i // cls.sc] + cls.cc[i % cls.sc] - # return cls.cr[cls._div(i, cls.sc) + int(cls.cc[i % cls.sc])] - - @classmethod - def _encode_short(cls, i) -> str: - if i > 0xFFFF: - raise ValueError('ERROR! rcnb overflow') - - reverse = False - if i > 0x7FFF: - reverse = True - i = i & 0x7FFF - - char = [ - cls._div(i, cls.scnb), - cls._div(i % cls.scnb, cls.snb), - cls._div(i % cls.snb, cls.sb), i % cls.sb - ] - char = [ - cls.cr[char[0]], cls.cc[char[1]], cls.cn[char[2]], - cls.cb[char[3]] - ] - - if reverse: - return char[2] + char[3] + char[0] + char[1] - - return ''.join(char) - - @classmethod - def _decodeByte(cls, c) -> int: - nb = False - idx = [cls.cr.index(c[0]), cls.cc.index(c[1])] - if idx[0] < 0 or idx[1] < 0: - idx = [cls.cn.index(c[0]), cls.cb.index(c[1])] - nb = True - raise ValueError('ERROR! rc/nb overflow') - - result = idx[0] * cls.sb + idx[1] if nb else idx[0] * cls.sc + idx[1] - if result > 0x7F: - raise ValueError('ERROR! rc/nb overflow') - - return result | 0x80 if nb else 0 - - @classmethod - def _decodeShort(cls, c) -> int: - reverse = c[0] not in cls.cr - if not reverse: - idx = [ - cls.cr.index(c[0]), - cls.cc.index(c[1]), - cls.cn.index(c[2]), - cls.cb.index(c[3]) - ] - else: - idx = [ - cls.cr.index(c[2]), - cls.cc.index(c[3]), - cls.cn.index(c[0]), - cls.cb.index(c[1]) - ] - - if idx[0] < 0 or idx[1] < 0 or idx[2] < 0 or idx[3] < 0: - raise ValueError('ERROR! not rcnb') - - result = (idx[0] * cls.scnb + - idx[1] * cls.snb + - idx[2] * cls.sb + idx[3]) - if result > 0x7FFF: - raise ValueError('ERROR! rcnb overflow') - - result |= 0x8000 if reverse else 0 - return result - - @classmethod - def _encodeBytes(cls, b) -> str: - result = [] - for i in range(0, (len(b) >> 1)): - result.append(cls._encode_short((b[i * 2] << 8 | b[i * 2 + 1]))) - - if len(b) & 1 == 1: - result.append(cls._encode_byte(b[-1])) - - return ''.join(result) - - @classmethod - def encode(cls, s: str, encoding: str = 'utf-8'): - if not isinstance(s, str): - raise ValueError('Please enter str instead of other') - - return cls._encodeBytes(s.encode(encoding)) - - @classmethod - def _decodeBytes(cls, s: str): - if not isinstance(s, str): - raise ValueError('Please enter str instead of other') - - if len(s) & 1: - raise ValueError('ERROR length') - - result = [] - for i in range(0, (len(s) >> 2)): - result.append(bytes([cls._decodeShort(s[i * 4:i * 4 + 4]) >> 8])) - result.append(bytes([cls._decodeShort(s[i * 4:i * 4 + 4]) & 0xFF])) - - if (len(s) & 2) == 2: - result.append(bytes([cls._decodeByte(s[-2:])])) - - return b''.join(result) - - @classmethod - def decode(cls, s: str, encoding: str = 'utf-8') -> str: - if not isinstance(s, str): - raise ValueError('Please enter str instead of other') - - try: - return cls._decodeBytes(s).decode(encoding) - except UnicodeDecodeError: - raise ValueError('Decoding failed') +MessageSegment.
\ No newline at end of file diff --git a/ATRI/plugins/utils/main.bin b/ATRI/plugins/utils/main.bin Binary files differdeleted file mode 100644 index 6e74a60..0000000 --- a/ATRI/plugins/utils/main.bin +++ /dev/null |