diff options
author | Kyomotoi <[email protected]> | 2021-03-14 16:22:34 +0800 |
---|---|---|
committer | Kyomotoi <[email protected]> | 2021-03-14 16:22:34 +0800 |
commit | 64a991e035e52e0a17e73d4e671a22ea9a7489da (patch) | |
tree | 8952d23a3d0f165d363e134ff7c64dbf05a670d3 | |
parent | da888ff020805a38a17e5f83705aeb42ffa992ba (diff) | |
download | ATRI-64a991e035e52e0a17e73d4e671a22ea9a7489da.tar.gz ATRI-64a991e035e52e0a17e73d4e671a22ea9a7489da.tar.bz2 ATRI-64a991e035e52e0a17e73d4e671a22ea9a7489da.zip |
✨🐛 更新插件,修复一些bug
-rw-r--r-- | ATRI/__init__.py | 23 | ||||
-rw-r--r-- | ATRI/data/database/KeyRepo/data.json | 325 | ||||
-rw-r--r-- | ATRI/exceptions.py | 109 | ||||
-rw-r--r-- | ATRI/plugins/admin.py | 59 | ||||
-rw-r--r-- | ATRI/plugins/anime-search/__init__.py | 27 | ||||
-rw-r--r-- | ATRI/plugins/anti-rubbish.py | 20 | ||||
-rw-r--r-- | ATRI/plugins/call-owner.py | 32 | ||||
-rw-r--r-- | ATRI/plugins/code-runner.py | 26 | ||||
-rw-r--r-- | ATRI/plugins/curse/__init__.py | 27 | ||||
-rw-r--r-- | ATRI/plugins/drifting-bottle/__init__.py | 18 | ||||
-rw-r--r-- | ATRI/plugins/essential.py | 48 | ||||
-rw-r--r-- | ATRI/plugins/funny.py | 32 | ||||
-rw-r--r-- | ATRI/plugins/github.py | 24 | ||||
-rw-r--r-- | ATRI/plugins/hitokoto.py | 28 | ||||
-rw-r--r-- | ATRI/plugins/key-repo/__init__.py | 171 | ||||
-rw-r--r-- | ATRI/plugins/rich/__init__.py | 26 | ||||
-rw-r--r-- | ATRI/plugins/rich/data_source.py | 16 | ||||
-rw-r--r-- | ATRI/plugins/status.py | 81 | ||||
-rw-r--r-- | ATRI/plugins/utils/__init__.py | 43 | ||||
-rw-r--r-- | ATRI/plugins/utils/data_source.py | 16 | ||||
-rw-r--r-- | ATRI/rule.py | 19 | ||||
-rw-r--r-- | ATRI/service.py | 106 | ||||
-rw-r--r-- | config.yml | 9 | ||||
-rw-r--r-- | main.py | 14 |
24 files changed, 771 insertions, 528 deletions
diff --git a/ATRI/__init__.py b/ATRI/__init__.py index 4458ad8..e5bc2f4 100644 --- a/ATRI/__init__.py +++ b/ATRI/__init__.py @@ -1,19 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: __init__.py -Created Date: 2021-03-07 11:22:06 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:01:51 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - from time import sleep import nonebot as nb @@ -30,10 +14,13 @@ def asgi(): return nb.get_asgi() +def driver(): + return nb.get_driver() + + def init(): nb.init(**RUNTIME_CONFIG) - driver = nb.get_driver() - driver.register_adapter("cqhttp", ATRIBot) + driver().register_adapter("cqhttp", ATRIBot) nb.load_plugins('ATRI/plugins') logger.info(f"Now running: {__version__}") sleep(3) diff --git a/ATRI/data/database/KeyRepo/data.json b/ATRI/data/database/KeyRepo/data.json new file mode 100644 index 0000000..43ed0f6 --- /dev/null +++ b/ATRI/data/database/KeyRepo/data.json @@ -0,0 +1,325 @@ +{ + "mua": [ + "你想干嘛?(一脸嫌弃地后退)", + "诶……不可以随便亲亲啦", + "(亲了一下你)", + "只......只许这一次哦///////" + ], + "摸摸": [ + "感觉你就像咱很久之前认识的一个人呢,有种莫名安心的感觉(>﹏<)", + "舒服w,蹭蹭~", + "唔。。头发要乱啦", + "呼噜呼噜~", + "好舒服,蹭蹭~", + "不行那里不可以(´///ω/// `)", + "再摸咱就长不高啦~", + "你的手总是那么暖和呢~", + "不可以总摸的哦,不然的话,会想那个的wwww", + "哼!谁稀罕你摸头啦!唔......为什么要做出那副表情......好啦好啦~咱......咱让你摸就是了......诶嘿嘿~好舒服......" + ], + "上你": [ + "(把你按在地上)这么弱还想欺负咱,真是不自量力呢", + "你再这样我就不理你了(>д<)" + ], + "傻了": [ + "超级讨厌你说咱傻的说" + ], + "蹭": [ + "唔...你,这也是禁止事项哦→_→", + "嗯..好舒服呢", + "不要啊好痒的", + "不要过来啦讨厌!!!∑(°Д°ノ)ノ" + ], + "裸体": [ + "下流!" + ], + "贴贴": [ + "贴什么贴.....只......只能......一下哦!", + "贴...贴贴(靠近)", + "蹭蹭…你以为咱会这么说吗!baka死宅快到一边去啦!" + ], + "老婆": [ + "咱和你谈婚论嫁是不是还太早了一点呢?", + "咱在呢(ノ>ω<)ノ", + "见谁都是一口一个老婆的人,要不要把你也变成女孩子呢?(*-`ω´-)✄", + "神经病,凡是美少女都是你老婆吗?" + ], + "抱抱": [ + "诶嘿~(钻进你怀中)", + "o(*////▽////*)q", + "只能一会哦(张开双手)", + "你就像个孩子一样呢...摸摸头(>^ω^<)抱一下~你会舒服些吗?", + "嘛,真是拿你没办法呢,就一会儿哦" + ], + "亲亲": [ + "啊,好含羞啊,那,那只能亲一下哦,mua(⑅˃◡˂⑅)", + "亲~", + "啾~唔…不要总伸进来啊!", + "你怎么这么熟练呢?明明是咱先的", + "(〃ノωノ)亲…亲一个…啾w", + "(脸红)就只有这一次哦~你" + ], + "草一下": [ + "一下也不行", + "咬断!" + ], + "一下": [ + "一下也不行" + ], + "啪一下": [ + "不可啪", + "不可以……你不可以做这种事情" + ], + "咬一下": [ + "啊呜~(反咬一口)", + "不可以咬咱,咱会痛的QAQ", + "不要啦。咱怕疼", + "你是说咬呢……还是说……咬♂️呢?", + "不要啦!很痛的!!(QAQ)" + ], + "操": [ + "(害怕)咱是不是应该报警呢" + ], + "123": [ + "boom!你有没有被咱吓到?", + "木头人~你不许动>w<", + "上山打老虎,老虎没打到\n咱来凑数——嗷呜嗷呜┗|`O′|┛嗷~~" + ], + "进去": [ + "不让!" + ], + "调教": [ + "总感觉你在欺负咱呢,对咱说调教什么的", + "啊!竟然在大街上明目张胆太过分啦!", + "你脑子里总是想着调教什么的,真是变态呢" + ], + "内衣": [ + "内...内衣才不给你看!(///////)", + "突然问这个干什么?", + "噫…你这个死变态想干嘛!居然想叫咱做这种事,死宅真恶心!快离我远点,我怕你污染到周围空气了(嫌弃脸)" + ], + "摸头": [ + "喂喂...不要停下来啊", + "唔... 手...好温暖呢.....就像是......新出炉的蛋糕", + "走开啦,黑羽喵说过,被摸头会长不高的啦~~~" + ], + "原味": [ + "(/ω\)你真的要么……?记得还给咱~还有奶油爆米花(//??//)说好了呦~!" + ], + "搓搓": [ + "在搓哪里呢,,Ծ‸Ծ,,", + "呜,脸好疼呀...QAQ", + "不可以搓咱!" + ], + "捏捏": [ + "咱的脸...快捏红啦...快放手呀QAQ", + "晃休啦,咱要型气了o(>﹏<)o", + "躲开", + "疼...你快放手", + "快点给我放开啦!", + "唔……好痛!你这个baka在干什么…快给咱放开!唔……" + ], + "挤挤": [ + "哎呀~你不要挤咱啊(红着脸挤在你怀里)" + ], + "呐": [ + "嗯?咱在哟~你怎么了呀OAO", + "嗯?你有什么事吗?" + ], + "胖次": [ + "(*/ω\*)hentai", + "透明的", + "粉...粉白条纹...(羞)", + "轻轻地脱下,给你~", + "你想看咱的胖次吗?噫,四斋蒸鹅心......", + "(掀裙)今天……是…白,白色的呢……请温柔对她……", + "这种东西当然不能给你啦!", + "咱才不会给你呢", + "hentai,咱才不会跟你聊和胖…胖次有关的话题呢!", + "今天……今天是蓝白色的", + "今……今天只有创口贴噢", + "你的胖次什么颜色?", + "噫…你这个死变态想干嘛!居然想叫咱做这种事,死宅真恶心!快离我远点,我怕你污染到周围空气了(嫌弃脸)" + ], + "内裤": [ + "今天……没有穿……有没有心动呀", + "粉...粉白条纹...(羞)", + "你这个大变态,咱才不要" + ], + "ghs": [ + "是的呢(点头点头)" + ], + "批": [ + "你在说什么呀,再这样,咱就不理你了!" + ], + "kkp": [ + "你在说什么呀,再这样,咱就不理你了!" + ], + "咕": [ + "咕咕咕是要被当成鸽子炖的哦(:з」∠)_", + "咕咕咕" + ], + "骚": [ + "说这种话咱会生气的" + ], + "喜欢": [ + "最喜欢你了,需要暖床吗?", + "当然是你啦", + "咱也是,非常喜欢你~", + "那么大!(张开手画圆),丫!手不够长。QAQ 咱真的最喜欢你了~", + "不行可以哦,只可以喜欢咱一个人", + "突然说这种事...", + "喜欢⁄(⁄⁄•⁄ω⁄•⁄⁄)⁄咱最喜欢你了", + "咱也喜欢你哦", + "好啦好啦,咱知道了", + "有人喜欢咱,咱觉得很幸福" + ], + "suki": [ + "最喜欢你了,需要暖床吗?", + "当然是你啦", + "咱也是,非常喜欢你~", + "那么大!(张开手画圆),丫!手不够长。QAQ 咱真的最喜欢你了~", + "不行可以哦,只可以喜欢咱一个人", + "突然说这种事...", + "喜欢⁄(⁄⁄•⁄ω⁄•⁄⁄)⁄咱最喜欢你了", + "咱也喜欢你哦", + "好啦好啦,咱知道了", + "有人喜欢咱,咱觉得很幸福" + ], + "好き": [ + "最喜欢你了,需要暖床吗?", + "当然是你啦", + "咱也是,非常喜欢你~", + "那么大!(张开手画圆),丫!手不够长。QAQ 咱真的最喜欢你了~", + "不行可以哦,只可以喜欢咱一个人", + "突然说这种事...", + "喜欢⁄(⁄⁄•⁄ω⁄•⁄⁄)⁄咱最喜欢你了", + "咱也喜欢你哦", + "好啦好啦,咱知道了", + "有人喜欢咱,咱觉得很幸福" + ], + "不能": [ + "虽然很遗憾,那算了吧。" + ], + "砸了": [ + "不可以这么粗暴的对待它们!" + ], + "透": [ + "来啊来啊有本事就先插破屏幕啊", + "那你就先捅破屏幕啊baka", + "不给你一耳光你都不知道咱的厉害" + ], + "口我": [ + "再伸过来就帮你切掉", + "咱才不呢!baka你居然想叫本小姐干那种事情,哼(つд⊂)(生气)" + ], + "草我": [ + "这时候应该喊666吧..咱这么思考着..", + "!!哼!baka你居然敢叫咱做这种事情?!讨厌讨厌讨厌!(▼皿▼#)" + ], + "自慰": [ + "这个世界的人类还真是恶心呢。", + "咱才不想讨论那些恶心的事情呢。", + "咱才不呢!baka你居然想叫本小姐干那种事情,哼(つд⊂)(生气)", + "!!哼!baka你居然敢叫咱做这种事情?!讨厌讨厌讨厌!(▼皿▼#)" + ], + "onani": [ + "这个世界的人类还真是恶心呢。", + "咱才不想讨论那些恶心的事情呢。", + "咱才不呢!baka你居然想叫本小姐干那种事情,哼(つд⊂)(生气)", + "!!哼!baka你居然敢叫咱做这种事情?!讨厌讨厌讨厌!(▼皿▼#)" + ], + "オナニー": [ + "这个世界的人类还真是恶心呢。", + "咱才不想讨论那些恶心的事情呢。", + "咱才不呢!baka你居然想叫本小姐干那种事情,哼(つд⊂)(生气)", + "!!哼!baka你居然敢叫咱做这种事情?!讨厌讨厌讨厌!(▼皿▼#)" + ], + "炸了": [ + "你才炸了!", + "才没有呢", + "咱好好的呀" + ], + "色图": [ + "天天色图色图的,今天就把你变成色图!", + "咱没有色图", + "哈?你的脑子一天都在想些什么呢,咱才没有这种东西啦。" + ], + "涩图": [ + "天天色图色图的,今天就把你变成色图!", + "咱没有色图", + "哈?你的脑子一天都在想些什么呢,咱才没有这种东西啦。" + ], + "告别": [ + "欸?你要向咱告白吗..好害羞..", + "诶!?这么突然!?人家还......还没做好心理准备呢(脸红)" + ], + "对不起": [ + "嗯,咱已经原谅你了呢(笑)", + "道歉的时候要露出胸部,这是常识" + ], + "回来": [ + "欢迎回来~", + "欢迎回来,你想喝茶吗?咱去给你沏~", + "欢迎回来,咱等你很久了~", + "你回来啦,是先吃饭呢还是先洗澡呢或者是●先●吃●咱●——呢(///^.^///)" + ], + "吻": [ + "你太突然了,咱还没有心理准备", + "公共场合不要这样子了啦", + "才...才没有感觉呢!可没有下次了,知道了吗!哼~" + ], + "软": [ + "软乎乎的呢(,,・ω・,,)" + ], + "壁咚": [ + "呀!不要啊!等一...下~", + "呜...不要啦!不要戏弄咱~", + "不要这样子啦(*/ω\*)", + "太....太近啦。", + "你要壁咚咱吗?好害羞(灬ꈍ εꈍ灬)", + "为什么要把咱按在墙上呢?", + "呜哇(/ω\)…快…快放开咱!!", + "放开我,不然我揍你了!放开我!放…开我~", + "??????咱只是默默地抬起了膝盖", + "啊.....你...你要干什么?!走开.....走开啦大hentai!一巴掌拍飞!(╯‵□′)╯︵┻━┻" + ], + "掰开": [ + "噫…你这个死肥宅又想让咱干什么污秽的事情,真是恶心,离咱远点好吗(嫌弃)", + "ヽ(#`Д´)ノ在干什么呢" + ], + "女友": [ + "女友什么的,咱才不承认呢!" + ], + "是": [ + "是什么是,你个笨蛋" + ], + "喵": [ + "诶~~小猫咪不要害怕呦,在姐姐怀里乖乖的,姐姐带你回去哦。", + "不要这么卖萌啦~咱也不知道怎么办丫", + "摸头⊙ω⊙", + "汪汪汪!" + ], + "嗷呜": [ + "嗷呜嗷呜嗷呜...恶龙咆哮┗|`O′|┛" + ], + "拜": [ + "拜拜~(ノ ̄▽ ̄)", + "拜拜,路上小心~要早点回来陪咱玩哦~", + "~\\(≧▽≦)/~拜拜,下次见喽!" + ], + "佬": [ + "不是巨佬,是萌新" + ], + "awsl": [ + "你别死啊!(抱住使劲晃)", + "你别死啊!咱又要孤单一个人了QAQ" + ], + "臭": [ + "哪里有臭味?(疑惑)", + "快捏住鼻子" + ], + "香": [ + "咱闻不到呢⊙ω⊙" + ] +}
\ No newline at end of file diff --git a/ATRI/exceptions.py b/ATRI/exceptions.py index e2fe475..4b74544 100644 --- a/ATRI/exceptions.py +++ b/ATRI/exceptions.py @@ -1,19 +1,4 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: exceptions.py -Created Date: 2021-02-02 18:24:59 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:00:35 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - +import os import time import json import string @@ -23,63 +8,45 @@ from typing import Optional from traceback import format_exc from pydantic.main import BaseModel -from nonebot.adapters.cqhttp import MessageEvent +from nonebot.adapters.cqhttp import Bot, Event from nonebot.matcher import Matcher +from nonebot.typing import T_State from nonebot.message import run_postprocessor from .log import logger -ERROR_FILE = Path('.') / 'ATRI' / 'data' / 'errors' -ERROR_FILE.parent.mkdir(exist_ok=True, parents=True) - - -class ExceptionInfo(BaseModel): - error_id: str - prompt: str - time: str - error_content: str +ERROR_DIR = Path('.') / 'ATRI' / 'data' / 'errors' +os.makedirs(ERROR_DIR, exist_ok=True) -def store_error(error_id: str, prompt, error_content: str) -> None: - data = ExceptionInfo( - error_id=error_id, - prompt=prompt, - time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), - error_content=error_content - ) - - path = ERROR_FILE / f"{error_id}.json" - path.parent.mkdir(exist_ok=True, parents=True) - with open(path, 'w', encoding='utf-8') as target: - target.write( - json.dumps( - data.dict(), indent=4 - ) - ) +def _save_error(prompt: str, content: str) -> str: + track_id = ''.join(sample(string.ascii_letters + string.digits, 16)) + data = { + "track_id": track_id, + "prompt": prompt, + "time": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), + "content": content + } + path = ERROR_DIR / f'{track_id}.json' + with open(path, 'w', encoding='utf-8') as r: + r.write(json.dumps(data, indent=4)) + return track_id -def read_error(error_id: str) -> dict: - path = ERROR_FILE / f"{error_id}.json" - try: - with open(path, 'r', encoding='utf-8') as target: - data = target.read() - return json.loads(data) - except FileNotFoundError: - raise FileNotFoundError +def load_error(track_id: str) -> dict: + path = ERROR_DIR / f'{track_id}.json' + return json.loads(path.read_bytes()) class BaseBotException(BaseException): prompt: Optional[str] = 'ignore' def __init__(self, prompt: Optional[str]) -> None: - super().__init__(self) self.prompt = prompt or self.__class__.prompt \ or self.__class__.__name__ - self.error_content = format_exc() - self.error_id = ''.join( - sample(string.ascii_letters + string.digits, 16) - ) + self.track_id = _save_error(self.prompt, format_exc()) + super().__init__(self.prompt) class NotConfigured(BaseBotException): @@ -107,31 +74,29 @@ class GetStatusError(BaseBotException): @run_postprocessor # type: ignore -async def _track_error(matcher: Matcher, exception: Optional[Exception], - event: MessageEvent, state: dict) -> None: - """检测Bot运行中的报错,并进行提醒""" - if not exception: +async def _track_error(matcher: Matcher, + exception: Optional[Exception], + bot: Bot, + event: Event, + state: T_State) -> None: + if exception is None: return try: raise exception except BaseBotException as Error: prompt = Error.prompt or Error.__class__.__name__ - error_id = Error.error_id - # error_content = format_exc() + track_id = Error.track_id except Exception as Error: - prompt = "Unknown ERROR" + Error.__class__.__name__ - error_id = ''.join( - sample(string.ascii_letters + string.digits, 16) - ) - store_error(error_id, prompt, format_exc()) + prompt = "Unknown ERROR-" + Error.__class__.__name__ + track_id = _save_error(prompt, format_exc()) - logger.debug(f"A bug has been cumming, trace ID: {error_id}") + logger.debug(f"A bug has been cumming, trace ID: {track_id}") msg = ( - "[WARNING] 这是一个错误...\n" - f"Track ID: {error_id}\n" - f"Reason: {prompt}\n" - "ごんめなさい... ;w;" + "[WARNING] 这是一个错误... ;w;\n" + f"追踪ID: {track_id}\n" + f"触发原因: {prompt}\n" + "键入 来杯红茶 以联系维护者" ) - await matcher.finish(msg) + await bot.send(event, msg) diff --git a/ATRI/plugins/admin.py b/ATRI/plugins/admin.py index 45acf4b..9465130 100644 --- a/ATRI/plugins/admin.py +++ b/ATRI/plugins/admin.py @@ -1,26 +1,10 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: admin.py -Created Date: 2021-02-04 21:17:12 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:01 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - +import os import json import time from pathlib import Path from datetime import datetime from nonebot.permission import SUPERUSER -from nonebot.plugin import on_command, on_message, CommandGroup from nonebot.adapters.cqhttp import ( Bot, MessageEvent, @@ -28,7 +12,8 @@ from nonebot.adapters.cqhttp import ( ) from nonebot.typing import T_State -from ATRI.exceptions import WriteError, read_error +from ATRI.service import Service as sv +from ATRI.exceptions import WriteError, load_error from ATRI.utils.file import open_file from ATRI.log import ( logger, @@ -38,10 +23,11 @@ from ATRI.log import ( ADMIN_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'admin' +os.makedirs(ADMIN_DIR, exist_ok=True) # 收集bot所在的群聊聊天记录 -chat_monitor = on_message() +chat_monitor = sv.on_message() @chat_monitor.handle() async def _chat_monitor(bot: Bot, event: GroupMessageEvent) -> None: @@ -96,8 +82,9 @@ async def _chat_monitor(bot: Bot, event: GroupMessageEvent) -> None: ESSENTIAL_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'essential' -request_friend = on_command( - "好友申请", +request_friend = sv.on_command( + name="好友申请处理", + cmd="好友申请", permission=SUPERUSER ) @@ -135,8 +122,9 @@ async def _request_friend(bot: Bot, event: MessageEvent) -> None: await request_friend.finish("阿...请检查输入——!") -request_group = on_command( - "群聊申请", +request_group = sv.on_command( + name="群聊申请处理", + cmd="群聊申请", permission=SUPERUSER ) @@ -184,8 +172,9 @@ async def _request_group(bot: Bot, event: MessageEvent) -> None: await request_friend.finish("阿...请检查输入——!") -broadcast = on_command( - "/broadcast", +broadcast = sv.on_command( + name="广播", + cmd="/broadcast", permission=SUPERUSER ) @@ -224,8 +213,9 @@ async def _bd(bot: Bot, event: MessageEvent, state: T_State) -> None: await broadcast.finish(repo_msg) -track_error = on_command( - "/track", +track_error = sv.on_command( + name="错误堆栈查看", + cmd="/track", permission=SUPERUSER ) @@ -241,7 +231,7 @@ async def _(bot: Bot, event: MessageEvent, state: T_State) -> None: data = {} try: - data = read_error(track_id) + data = load_error(track_id) except: await track_error.finish("Ignore track ID!") @@ -249,14 +239,15 @@ async def _(bot: Bot, event: MessageEvent, state: T_State) -> None: f"ID: {track_id}\n" f"Time: {data['time']}\n" f"Prompt: {data['prompt']}\n" - f"{data['error_content']}" + f"{data['content']}" ) await track_error.finish(msg0) -get_log = on_command( - "/getlog", +get_log = sv.on_command( + name="获取控制台信息", + cmd="/getlog", permission=SUPERUSER ) @@ -290,7 +281,11 @@ async def _get_log(bot: Bot, event: MessageEvent) -> None: await get_log.finish("\n".join(content).replace("[36mATRI[0m", "ATRI")) # type: ignore -shutdown = on_command("/shutdown", permission=SUPERUSER) +shutdown = sv.on_command( + name="紧急停机", + cmd="/shutdown", + permission=SUPERUSER +) @shutdown.handle() async def _shutdown(bot: Bot, event: MessageEvent, state: T_State) -> None: diff --git a/ATRI/plugins/anime-search/__init__.py b/ATRI/plugins/anime-search/__init__.py index 3ff8964..07cc8dc 100644 --- a/ATRI/plugins/anime-search/__init__.py +++ b/ATRI/plugins/anime-search/__init__.py @@ -1,29 +1,13 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: __init__.py -Created Date: 2021-02-19 22:16:34 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:18:10 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import re import json from nonebot.adapters.cqhttp.message import MessageSegment -from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot, MessageEvent from nonebot.adapters.cqhttp.message import Message from nonebot.typing import T_State -from ATRI.rule import is_in_banlist, is_in_dormant +from ATRI.service import Service as sv +from ATRI.rule import is_block, is_in_dormant from ATRI.exceptions import RequestTimeOut from ATRI.utils.request import get_bytes @@ -33,9 +17,10 @@ from .data_source import to_simple_string URL = "https://trace.moe/api/search?url=" -anime_search = on_command( - "/anime", - rule=is_in_banlist() & is_in_dormant() +anime_search = sv.on_command( + name="以图搜番", + cmd="/anime", + rule=is_block() & is_in_dormant() ) @anime_search.handle() diff --git a/ATRI/plugins/anti-rubbish.py b/ATRI/plugins/anti-rubbish.py index 7350789..de8e1e1 100644 --- a/ATRI/plugins/anti-rubbish.py +++ b/ATRI/plugins/anti-rubbish.py @@ -1,19 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: anti-rubbish.py -Created Date: 2021-02-15 12:39:24 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:13:51 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import json from pathlib import Path from datetime import datetime @@ -23,7 +7,7 @@ from nonebot.plugin import on_command, on_message from nonebot.adapters.cqhttp import Bot, GroupMessageEvent from ATRI.log import logger -from ATRI.rule import is_in_banlist +from ATRI.rule import is_block from ATRI.config import nonebot_config from ATRI.utils.file import write_file from ATRI.utils.apscheduler import scheduler @@ -58,7 +42,7 @@ async def _anti_rubbish(bot: Bot, event: GroupMessageEvent) -> None: f"GET 吃屎人 {user}[@群{group}] 第{noob_data[user][key]}次: {msg}") -rubbish = on_command("/rubbish", rule=is_in_banlist()) +rubbish = on_command("/rubbish", rule=is_block()) @rubbish.handle() async def _rubbish(bot: Bot, event: GroupMessageEvent) -> None: diff --git a/ATRI/plugins/call-owner.py b/ATRI/plugins/call-owner.py index c09276f..af8e83d 100644 --- a/ATRI/plugins/call-owner.py +++ b/ATRI/plugins/call-owner.py @@ -1,28 +1,12 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: call-owner.py -Created Date: 2021-02-19 23:02:45 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:13:40 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - from nonebot.permission import SUPERUSER -from nonebot.plugin import on_command from nonebot.typing import T_State from nonebot.adapters.cqhttp import ( Bot, MessageEvent ) -from ATRI.rule import is_in_banlist +from ATRI.service import Service as sv +from ATRI.rule import is_block from ATRI.config import nonebot_config from ATRI.utils.apscheduler import scheduler from ATRI.utils.list import count_list @@ -31,7 +15,11 @@ from ATRI.utils.list import count_list repo_list = [] -repo = on_command("来杯红茶", rule=is_in_banlist()) +repo = sv.on_command( + name="给维护者留言", + cmd="来杯红茶", + rule=is_block() +) @repo.handle() async def _repo(bot: Bot, event: MessageEvent, state: T_State) -> None: @@ -69,7 +57,11 @@ async def _() -> None: repo_list = [] -reset_repo = on_command("重置红茶", permission=SUPERUSER) +reset_repo = sv.on_command( + name="重置给维护者留言次数", + cmd="重置红茶", + permission=SUPERUSER +) @reset_repo.handle() async def _reset_repo(bot: Bot, event: MessageEvent) -> None: diff --git a/ATRI/plugins/code-runner.py b/ATRI/plugins/code-runner.py index 0761384..731abfc 100644 --- a/ATRI/plugins/code-runner.py +++ b/ATRI/plugins/code-runner.py @@ -1,27 +1,11 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: code-runner.py -Created Date: 2021-02-20 07:43:44 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:13:28 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - """ Idea from: https://github.com/cczu-osa/aki """ import json -from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot, MessageEvent -from ATRI.rule import is_in_banlist, is_in_dormant +from ATRI.service import Service as sv +from ATRI.rule import is_block, is_in_dormant from ATRI.utils.request import post_bytes from ATRI.exceptions import RequestTimeOut @@ -56,7 +40,11 @@ SUPPORTED_LANGUAGES = { } -code_runner = on_command("/code", rule=is_in_banlist() & is_in_dormant()) +code_runner = sv.on_command( + name="运行代码", + cmd="/code", + rule=is_block() & is_in_dormant() +) @code_runner.handle() async def _code_runner(bot: Bot, event: MessageEvent) -> None: diff --git a/ATRI/plugins/curse/__init__.py b/ATRI/plugins/curse/__init__.py index f78e022..03da205 100644 --- a/ATRI/plugins/curse/__init__.py +++ b/ATRI/plugins/curse/__init__.py @@ -1,24 +1,8 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: __init__.py -Created Date: 2021-02-04 17:58:27 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:41 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - -from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot, MessageEvent +from ATRI.service import Service as sv from ATRI.rule import ( - is_in_banlist, + is_block, is_in_dormant, is_in_service ) @@ -33,10 +17,11 @@ sick_list = [] __plugin_name__ = 'curse' -curse = on_command( - "口臭一下", +curse = sv.on_command( + name="口臭", + cmd="口臭一下", aliases={"口臭", "骂我"}, - rule=is_in_banlist() & is_in_dormant() + rule=is_block() & is_in_dormant() & is_in_service(__plugin_name__) ) diff --git a/ATRI/plugins/drifting-bottle/__init__.py b/ATRI/plugins/drifting-bottle/__init__.py index c9bd0a7..5bd514c 100644 --- a/ATRI/plugins/drifting-bottle/__init__.py +++ b/ATRI/plugins/drifting-bottle/__init__.py @@ -1,16 +1,2 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: __init__.py -Created Date: 2021-02-15 11:45:36 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:36 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - +from ATRI.service import Service as sv +from ATRI.rule import is_block, is_in_service
\ No newline at end of file diff --git a/ATRI/plugins/essential.py b/ATRI/plugins/essential.py index f7d9840..020a413 100644 --- a/ATRI/plugins/essential.py +++ b/ATRI/plugins/essential.py @@ -1,28 +1,11 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: essential.py -Created Date: 2021-02-04 12:53:00 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:13:09 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - +import os import time import json import shutil from pathlib import Path from random import choice -import nonebot 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, @@ -37,17 +20,19 @@ from nonebot.adapters.cqhttp import ( FriendRecallNoticeEvent ) +import ATRI 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.rule import is_block from ATRI.service import Service as sv -PLUGIN_INFO_DIR = Path('.') / 'ATRI' / 'data' / 'service' / 'plugins' +PLUGIN_INFO_DIR = Path('.') / 'ATRI' / 'data' / 'service' / 'services' + +driver = ATRI.driver() -driver = nonebot.get_driver() @driver.on_startup async def startup() -> None: @@ -64,8 +49,8 @@ async def shutdown() -> None: except: repo = ( '清理插件信息失败', - '请前往 ATRI/data/service 下', - '将 plugins 整个文件夹删除' + '请前往 ATRI/data/service/services 下', + '将 services 整个文件夹删除' ) logger.error(repo) time.sleep(10) @@ -94,9 +79,10 @@ async def disconnect(bot) -> None: ESSENTIAL_DIR = Path('.') / 'ATRI' / 'data' / 'database' / 'essential' +os.makedirs(ESSENTIAL_DIR, exist_ok=True) # 处理:好友请求 -request_friend_event = on_request(rule=is_in_banlist()) +request_friend_event = sv.on_request("Friends request", rule=is_block()) @request_friend_event.handle() async def _request_friend_event(bot, event: FriendRequestEvent) -> None: @@ -136,7 +122,7 @@ async def _request_friend_event(bot, event: FriendRequestEvent) -> None: # 处理:邀请入群,如身为管理,还附有入群请求 -request_group_event = on_request(rule=is_in_banlist()) +request_group_event = sv.on_request("Group request",rule=is_block()) @request_group_event.handle() async def _request_group_event(bot, event: GroupRequestEvent) -> None: @@ -178,7 +164,7 @@ async def _request_group_event(bot, event: GroupRequestEvent) -> None: # 处理群成员变动 -group_member_event = on_notice() +group_member_event = sv.on_notice("Group member change") @group_member_event.handle() async def _group_member_event(bot: Bot, event) -> None: @@ -205,7 +191,7 @@ async def _group_member_event(bot: Bot, event) -> None: # 处理群管理事件 -group_admin_event = on_notice() +group_admin_event = sv.on_notice("Group admin change") @group_admin_event.handle() async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent) -> None: @@ -218,7 +204,7 @@ async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent) -> None: # 处理群禁言事件 -group_ban_event = on_notice() +group_ban_event = sv.on_notice("Group ban change") @group_ban_event.handle() async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent) -> None: @@ -247,7 +233,7 @@ async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent) -> None: # 处理群红包运气王事件 -lucky_read_bag_event = on_notice() +lucky_read_bag_event = sv.on_notice("Group read bag winner") @lucky_read_bag_event.handle() async def _lucky_read_bag_event(bot, event: LuckyKingNotifyEvent) -> None: @@ -259,7 +245,7 @@ async def _lucky_read_bag_event(bot, event: LuckyKingNotifyEvent) -> None: # 处理群文件上传事件 -group_file_upload_event = on_notice() +group_file_upload_event = sv.on_notice("Group file change") @group_file_upload_event.handle() async def _group_file_upload_event(bot, @@ -268,7 +254,7 @@ async def _group_file_upload_event(bot, # 处理撤回事件 -recall_event = on_notice() +recall_event = sv.on_notice("Group member recall") @recall_event.handle() async def _recall_event(bot: Bot, event) -> None: diff --git a/ATRI/plugins/funny.py b/ATRI/plugins/funny.py index 39a691d..472c77c 100644 --- a/ATRI/plugins/funny.py +++ b/ATRI/plugins/funny.py @@ -1,27 +1,11 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: funny.py -Created Date: 2021-02-04 21:17:21 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:13:19 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - 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.service import Service as sv from ATRI.rule import ( - is_in_banlist, + is_block, is_in_dormant, is_in_service ) @@ -29,9 +13,10 @@ from ATRI.rule import ( __plugin_name__ = "laugh" -get_laugh = on_command( - "来句笑话", - rule=is_in_banlist() & is_in_dormant() +get_laugh = sv.on_command( + name="看不懂的笑话", + cmd="来句笑话", + rule=is_block() & is_in_dormant() & is_in_service(__plugin_name__) ) @@ -51,9 +36,10 @@ async def _get_laugh(bot: Bot, event: MessageEvent) -> None: __plugin_name__ = "wty" -me_to_you = on_message( - rule=is_in_banlist() & is_in_dormant() & is_in_service(__plugin_name__) +me_to_you = sv.on_message( + rule=is_block() & is_in_dormant() & is_in_service(__plugin_name__) ) +sv.manual_reg_service("你又彳亍了") @me_to_you.handle() async def _me_to_you(bot: Bot, event: MessageEvent) -> None: diff --git a/ATRI/plugins/github.py b/ATRI/plugins/github.py index 118d6f5..167ca2f 100644 --- a/ATRI/plugins/github.py +++ b/ATRI/plugins/github.py @@ -1,26 +1,9 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: github.py -Created Date: 2021-02-26 23:22:34 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:11:56 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import re import json - -from nonebot.plugin import on_message from nonebot.adapters.cqhttp import Bot, MessageEvent -from ATRI.rule import is_in_banlist, is_in_dormant +from ATRI.service import Service as sv +from ATRI.rule import is_block, is_in_dormant from ATRI.utils.request import get_bytes from ATRI.exceptions import RequestTimeOut @@ -28,7 +11,8 @@ from ATRI.exceptions import RequestTimeOut URL = "https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}" -github_issues = on_message(rule=is_in_banlist() & is_in_dormant()) +github_issues = sv.on_message(rule=is_block() & is_in_dormant()) +sv.manual_reg_service("GitHubIssue速览") @github_issues.handle() async def _github_issues(bot: Bot, event: MessageEvent) -> None: diff --git a/ATRI/plugins/hitokoto.py b/ATRI/plugins/hitokoto.py index ff686fc..3754125 100644 --- a/ATRI/plugins/hitokoto.py +++ b/ATRI/plugins/hitokoto.py @@ -1,33 +1,16 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: hitokoto.py -Created Date: 2021-02-04 17:40:21 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:11:44 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - 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, MessageEvent from ATRI.rule import ( - is_in_banlist, + is_block, is_in_dormant, is_in_service, to_bot ) +from ATRI.service import Service as sv from ATRI.exceptions import LoadingError from ATRI.utils.list import count_list, del_list_aim @@ -38,10 +21,11 @@ sick_list = [] __plugin_name__ = 'hitokoto' -hitokoto = on_command( - "一言", +hitokoto = sv.on_command( + name="Hitokoto", + cmd="一言", aliases={"抑郁一下", "网抑云"}, - rule=is_in_banlist() & is_in_dormant() + rule=is_block() & is_in_dormant() & is_in_service(__plugin_name__) & to_bot() ) diff --git a/ATRI/plugins/key-repo/__init__.py b/ATRI/plugins/key-repo/__init__.py new file mode 100644 index 0000000..4b2241c --- /dev/null +++ b/ATRI/plugins/key-repo/__init__.py @@ -0,0 +1,171 @@ +import os +import json +import time +from random import choice +from pathlib import Path + +from nonebot.typing import T_State +from nonebot.adapters.cqhttp import Bot, MessageEvent + +from ATRI.config import nonebot_config +from ATRI.service import Service as sv +from ATRI.rule import is_block, is_in_dormant, is_in_service, to_bot + + +# 此功能未完善 + + +KEYREPO_DIV = Path('.') / 'ATRI' / 'data' / 'database' / 'KeyRepo' +os.makedirs(KEYREPO_DIV, exist_ok=True) + + +__plugin_name__ = "KeyRepo" + +keyrepo = sv.on_message(rule=is_block() + & is_in_dormant() + & is_in_service(__plugin_name__) + & to_bot()) + +async def _keyrepo(bot: Bot, event: MessageEvent) -> None: + msg = str(event.get_message()) + + file_name = "data.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + with open(path, 'w') as r: + r.write(json.dumps({})) + data = {} + + for key in data.keys(): + if key in msg: + await keyrepo.finish(choice(data[key])) + + +train = sv.on_command( + name="调教", + cmd="/train", + rule=is_block() +) + [email protected]("key", prompt="哦哦哦要开始学习了!请告诉咱知识点") +async def _train(bot: Bot, event: MessageEvent, state: T_State) -> None: + if "[CQ" in state["key"]: + await train.reject("仅支持纯文本呢...") + [email protected]("repo", prompt="咱该如何回答呢?") +async def _trainR(bot: Bot, event: MessageEvent, state: T_State) -> None: + if "[CQ" in state["repo"]: + await train.reject("仅支持纯文本呢...") + + if state["key"] == "-d": + file_name = "review.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + data = {} + + key = state["repo"] + if key not in data: + await train.finish("未发现该待审核的知识点呢...") + else: + msg = ( + f"Key: {key}\n" + f"Repo: {data[key]['repo']}\n" + "已经从咱的审核列表移除!" + ) + del data[key] + with open(path, 'w') as r: + r.write(json.dumps(data)) + await train.finish(msg) + elif state["key"] == "-i": + file_name = "review.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + data = {} + if state["repo"] not in data: + await train.finish("未发现该知识点呢") + key = data[state["repo"]] + + msg = ( + f"用户: {key['user']}\n" + f"知识点: {state['repo']}" + f"回复: {key['repo']}" + f"时间: {key['time']}" + "/train -r 知识点 y/n" + ) + await train.finish(msg) + elif state["key"] == "-ls": + file_name = "review.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + data = {} + keys = ",".join(data.keys()) + msg = f"目前等待审核的有如下:\n{keys}" + await train.finish(msg) + elif state["key"] == "-r": + file_name = "review.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + data = {} + + + key = state["key"] + repo = state["repo"] + user = event.get_user_id() + if user not in nonebot_config["superusers"]: + file_name = "review.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + data = {} + + if key in data: + msg = "欸欸欸,该词还在等待咱的审核,请先等先来的审核完再提交吧..." + await train.finish(msg) + else: + data[key] = { + "user": user, + "repo": repo, + "time": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + } + with open(path, 'r') as r: + r.write(json.dumps(data, indent=4)) + + msg = ( + "欸欸欸这不错欸!不过,还是先等待咱审核审核," + "如想撤销本次学习,请发送 /train -d 知识点" + ) + await train.finish(msg) + + else: + file_name = "data.json" + path = KEYREPO_DIV / file_name + try: + data = json.loads(path.read_bytes()) + except: + data = {} + + if key in data: + repo_list: list = data[key] + repo_list.append(repo) + data[key] = repo_list + msg = f"哦哦哦,{key}原来还有这样的回复,学到了~!" + await bot.send(event, msg) + else: + data[key] = [repo] + msg = "好欸,咱学到了新的知识点!" + await bot.send(event, msg) + + with open(path, 'w') as r: + r.write(json.dumps(data)) diff --git a/ATRI/plugins/rich/__init__.py b/ATRI/plugins/rich/__init__.py index 7f9369e..7c8179d 100644 --- a/ATRI/plugins/rich/__init__.py +++ b/ATRI/plugins/rich/__init__.py @@ -1,30 +1,13 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: __init__.py -Created Date: 2021-02-07 09:34:23 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:28 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import re import json from aiohttp.client import ClientSession - from nonebot.adapters.cqhttp import Bot, MessageEvent -from nonebot.plugin import on_message +from ATRI.service import Service as sv from ATRI.utils.request import get_bytes from ATRI.utils.list import count_list, del_list_aim from ATRI.rule import ( - is_in_banlist, + is_block, is_in_dormant, ) @@ -34,9 +17,10 @@ from .data_source import dec waiting_list = [] -bilibili_rich = on_message( - rule=is_in_banlist() & is_in_dormant() +bilibili_rich = sv.on_message( + rule=is_block() & is_in_dormant() ) +sv.manual_reg_service("监听b站小程序") @bilibili_rich.handle() async def _bilibili_rich(bot: Bot, event: MessageEvent) -> None: diff --git a/ATRI/plugins/rich/data_source.py b/ATRI/plugins/rich/data_source.py index d3e7d6e..32ac219 100644 --- a/ATRI/plugins/rich/data_source.py +++ b/ATRI/plugins/rich/data_source.py @@ -1,19 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: data_source.py -Created Date: 2021-02-07 09:34:31 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:31 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF' tr = {} for i in range(58): diff --git a/ATRI/plugins/status.py b/ATRI/plugins/status.py index fe10dea..c3b033c 100644 --- a/ATRI/plugins/status.py +++ b/ATRI/plugins/status.py @@ -1,36 +1,30 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: status.py -Created Date: 2021-02-19 21:52:56 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:11:30 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import psutil - -from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot, MessageEvent -from ATRI.rule import is_in_banlist +from ATRI.log import logger as log +from ATRI.service import Service as sv +from ATRI.rule import is_block from ATRI.exceptions import GetStatusError +from ATRI.utils.apscheduler import scheduler +from ATRI.config import nonebot_config -ping = on_command("/ping", rule=is_in_banlist()) +ping = sv.on_command( + name="测试机器人", + cmd="/ping", + rule=is_block() +) @ping.handle() async def _ping(bot: Bot, event: MessageEvent) -> None: await ping.finish("I'm fine.") -status = on_command("/status", rule=is_in_banlist()) +status = sv.on_command( + name="检查机器人状态", + cmd="/status", + rule=is_block() +) @status.handle() async def _status(bot: Bot, event: MessageEvent) -> None: @@ -64,3 +58,48 @@ async def _status(bot: Bot, event: MessageEvent) -> None: ) + msg await status.finish(msg0) + + [email protected]_job( + 'interval', + minutes=5, + misfire_grace_time=10 +) +async def _(): + log.info("开始自检") + try: + cpu = psutil.cpu_percent(interval=1) + mem = psutil.virtual_memory().percent + disk = psutil.disk_usage("/").percent + inteSENT = psutil.net_io_counters().bytes_sent / 1000000 # type: ignore + inteRECV = psutil.net_io_counters().bytes_sent / 1000000 # type: ignore + except GetStatusError: + raise GetStatusError("Failed to get status.") + + msg = "" + if cpu > 80: # type: ignore + msg = "咱感觉有些头晕..." + if mem > 80: + msg = "咱感觉有点头晕并且有点累..." + elif mem > 80: + msg = "咱感觉有点累..." + elif disk > 80: + msg = "咱感觉身体要被塞满了..." + else: + log.info("运作正常") + return + + msg0 = ( + "Self status:\n" + f"* CPU: {cpu}%\n" + f"* MEM: {mem}%\n" + f"* DISK: {disk}%\n" + f"* netSENT: {inteSENT}MB\n" + f"* netRECV: {inteRECV}MB\n" + ) + msg + + for sup in nonebot_config["superusers"]: + await sv.NetworkPost.send_private_msg( + user_id=sup, + message=msg0 + ) diff --git a/ATRI/plugins/utils/__init__.py b/ATRI/plugins/utils/__init__.py index 47c3b47..10b3317 100644 --- a/ATRI/plugins/utils/__init__.py +++ b/ATRI/plugins/utils/__init__.py @@ -1,26 +1,9 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: __init__.py -Created Date: 2021-02-04 21:14:48 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:16 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import re - -from nonebot.plugin import on_command from nonebot.adapters.cqhttp import Bot, MessageEvent +from ATRI.service import Service as sv from ATRI.rule import ( - is_in_banlist, + is_block, is_in_dormant, is_in_service ) @@ -29,9 +12,10 @@ from .data_source import roll_dice __plugin_name__ = "roll" -roll = on_command( - "/roll", - rule=is_in_banlist() & is_in_dormant() +roll = sv.on_command( + name="roll一下", + cmd="/roll", + rule=is_block() & is_in_dormant() & is_in_service(__plugin_name__) ) @@ -50,18 +34,3 @@ async def _(bot: Bot, event: MessageEvent, state: dict) -> None: await roll.finish("请输入正确的参数!!\ndemo:1d10 或 2d10+2d10") await roll.finish(roll_dice(resu)) - - -# __plugin_name__ = "fakemsg" - -# fakemsg = on_command( -# "/fakemsg", -# rule=is_in_banlist() & is_in_dormant() -# & is_in_service(__plugin_name__) -# ) - -# @fakemsg.handle() -# async def _fakemsg(bot: Bot, event: MessageEvent, state: dict) -> None: -# ... - -# @fakemsg.got()
\ No newline at end of file diff --git a/ATRI/plugins/utils/data_source.py b/ATRI/plugins/utils/data_source.py index 6d018f1..f41a1d1 100644 --- a/ATRI/plugins/utils/data_source.py +++ b/ATRI/plugins/utils/data_source.py @@ -1,19 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: data_source.py -Created Date: 2021-02-04 21:14:59 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 3:14:22 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import re import random diff --git a/ATRI/rule.py b/ATRI/rule.py index 3b9c403..7cdeb0a 100644 --- a/ATRI/rule.py +++ b/ATRI/rule.py @@ -1,24 +1,7 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: rule.py -Created Date: 2021-02-03 15:33:57 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 2:58:18 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import datetime from random import choice from nonebot.rule import Rule -from nonebot.adapters.cqhttp.event import Event from nonebot.adapters.cqhttp import GroupMessageEvent, PokeNotifyEvent from .config import config @@ -37,7 +20,7 @@ def is_in_service(service: str) -> Rule: return Rule(_is_in_service) -def is_in_banlist() -> Rule: +def is_block() -> Rule: async def _is_in_banlist(bot, event, state) -> bool: return sv.BlockSystem.auth_user(int(event.get_user_id())) diff --git a/ATRI/service.py b/ATRI/service.py index 8ce3c22..ab870fd 100644 --- a/ATRI/service.py +++ b/ATRI/service.py @@ -1,19 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -''' -File: service.py -Created Date: 2021-02-27 11:01:39 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 2:56:28 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import os import json from pathlib import Path @@ -43,23 +27,48 @@ if TYPE_CHECKING: SERVICE_DIR = Path('.') / 'ATRI' / 'data' / 'service' +SERVICES_DIR = SERVICE_DIR / 'services' os.makedirs(SERVICE_DIR, exist_ok=True) +os.makedirs(SERVICES_DIR, exist_ok=True) matcher_list: list = [] is_sleep: bool = False +def _load_block_list() -> dict: + file_name = "ban.json" + file = SERVICE_DIR / file_name + try: + data = json.loads(file.read_bytes()) + except: + data = { + "user": [], + "group": [] + } + with open(file, "w") as r: + r.write(json.dumps(data, indent=4)) + return data + + +def _save_block_list(data: dict) -> None: + file_name = "ban.json" + file = SERVICE_DIR / file_name + with open(file, "w") as r: + r.write(json.dumps(data, indent=4)) + + def _load_service_config(service: str, docs: str = None) -> dict: file_name = service + ".json" - file = SERVICE_DIR / file_name + file = SERVICES_DIR / file_name try: data = json.loads(file.read_bytes()) except: service_info = { "name": service, "docs": docs, - "disable_group": [] + "disable_user": _load_block_list()['user'], + "disable_group": _load_block_list()['group'] } with open(file, "w") as r: r.write(json.dumps(service_info, indent=4)) @@ -69,7 +78,7 @@ def _load_service_config(service: str, docs: str = None) -> dict: def _save_service_config(service: str, data: dict) -> None: file_name = service + ".json" - file = SERVICE_DIR / file_name + file = SERVICES_DIR / file_name with open(file, "w") as r: r.write(json.dumps(data, indent=4)) @@ -82,11 +91,12 @@ class Service: @staticmethod def manual_reg_service(service: str): file_name = service + ".json" - file = SERVICE_DIR / file_name + file = SERVICES_DIR / file_name service_info = { "name": service, "docs": None, - "disable_group": [] + "disable_user": _load_block_list()['user'], + "disable_group": _load_block_list()['group'] } with open(file, "w") as r: r.write(json.dumps(service_info, indent=4)) @@ -130,7 +140,7 @@ class Service: @staticmethod def on_notice(name: str, - docs: str, + docs: Optional[str] = None, rule: Optional[Union[Rule, T_RuleChecker]] = None, *, handlers: Optional[List[T_Handler]] = None, @@ -152,7 +162,7 @@ class Service: @staticmethod def on_request(name: str, - docs: str, + docs: Optional[str] = None, rule: Optional[Union[Rule, T_RuleChecker]] = None, *, handlers: Optional[List[T_Handler]] = None, @@ -175,8 +185,8 @@ class Service: @classmethod def on_command(cls, name: str, - docs: str, cmd: Union[str, Tuple[str, ...]], + docs: Optional[str] = None, rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, **kwargs) -> Type[Matcher]: @@ -201,8 +211,8 @@ class Service: @classmethod def on_keyword(cls, name: str, - docs: str, keywords: Set[str], + docs: Optional[str] = None, rule: Optional[Union[Rule, T_RuleChecker]] = None, **kwargs) -> Type[Matcher]: _load_service_config(name, docs) @@ -429,27 +439,33 @@ class Service: path = SERVICE_DIR / file_name @classmethod - def get_list(cls) -> dict: - try: - return json.loads(cls.path.read_bytes()) - except: - with open(cls.path, "w") as r: - json.dump("{}", r) - return {} - - @classmethod def auth_user(cls, user: int) -> bool: - return False if user in cls.get_list() else True + return False if user in _load_block_list()['user'] else True + + @staticmethod + def auth_group(group: int) -> bool: + return False if group in _load_block_list()['group'] else True @classmethod - def control_list(cls, user: int, is_enable: bool) -> None: - data = cls.get_list() - if is_enable: - data[user] = datetime.now().__str__ - log.info(f"New blocked user: {user} | Time: {datetime.now()}") - else: - del data[user] - log.info(f"User {user} has been unblock.") - + def control_list(cls, + is_enable: bool, + user: Optional[int] = None, + group: Optional[int] = None) -> None: + data = _load_block_list() + if user: + if is_enable: + data['user'][user] = datetime.now().__str__ + log.info(f"New blocked user: {user} | Time: {datetime.now()}") + else: + del data[user] + log.info(f"User {user} has been unblock.") + elif group: + if is_enable: + data['group'][group] = datetime.now().__str__ + log.info(f"New blocked group: {group} | Time: {datetime.now()}") + else: + del data[user] + log.info(f"Group {group} has been unblock.") + with open(cls.path, "w") as r: - json.dump(data, r)
\ No newline at end of file + json.dump(data, r) @@ -1,8 +1,3 @@ -/* - * File: config.yml - * Project: https://github.com/Kyomotoi/ATRI - */ - BotSelfConfig: host: "127.0.0.1" port: 25565 @@ -11,7 +6,7 @@ BotSelfConfig: nickname: ["ATRI", "Atri", "atri", "亚托莉", "アトリ"] command_start: ["", "/"] command_sep: ["."] - session_expire_timeout: 3 + session_expire_timeout: 120 session_exciting_time: 3 NetworkPost: @@ -20,4 +15,4 @@ NetworkPost: AdminPage: host: "127.0.0.1" - port: 11451
\ No newline at end of file + port: 11451 @@ -1,19 +1,5 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- -''' -File: main.py -Created Date: 2021-02-02 15:51:30 -Author: Kyomotoi -Email: [email protected] -License: GPLv3 -Project: https://github.com/Kyomotoi/ATRI --------- -Last Modified: Sunday, 7th March 2021 12:25:07 pm -Modified By: Kyomotoi ([email protected]) --------- -Copyright (c) 2021 Kyomotoi -''' - import ATRI ATRI.init() |