summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLint Action <[email protected]>2021-07-08 14:09:51 +0000
committerLint Action <[email protected]>2021-07-08 14:09:51 +0000
commit951dcdf4ec224b31433c5ab5c170b76fd3087910 (patch)
treefe0ee2b5c219bd8f9796917ac3ee6286d4181146
parentbe2747e4d4b820ca0f1f988d3b77a628da26fe7b (diff)
downloadATRI-951dcdf4ec224b31433c5ab5c170b76fd3087910.tar.gz
ATRI-951dcdf4ec224b31433c5ab5c170b76fd3087910.tar.bz2
ATRI-951dcdf4ec224b31433c5ab5c170b76fd3087910.zip
:rotating_light: 自动进行代码格式化
-rw-r--r--ATRI/exceptions.py4
-rw-r--r--ATRI/plugins/anime_search.py18
-rw-r--r--ATRI/plugins/chat/__init__.py38
-rw-r--r--ATRI/plugins/chat/data_source.py37
-rw-r--r--ATRI/plugins/code_runner/__init__.py7
-rw-r--r--ATRI/plugins/code_runner/data_source.py25
-rw-r--r--ATRI/plugins/curse.py13
-rw-r--r--ATRI/plugins/essential.py61
-rw-r--r--ATRI/plugins/funny/__init__.py18
-rw-r--r--ATRI/plugins/funny/data_source.py37
-rw-r--r--ATRI/plugins/help/__init__.py12
-rw-r--r--ATRI/plugins/help/data_source.py30
-rw-r--r--ATRI/plugins/manege/__init__.py104
-rw-r--r--ATRI/plugins/manege/data_source.py65
-rw-r--r--ATRI/plugins/repo.py17
-rw-r--r--ATRI/plugins/rich/__init__.py3
-rw-r--r--ATRI/plugins/rich/data_source.py18
-rw-r--r--ATRI/plugins/saucenao/__init__.py7
-rw-r--r--ATRI/plugins/saucenao/data_source.py25
-rw-r--r--ATRI/plugins/setu/__init__.py24
-rw-r--r--ATRI/plugins/setu/data_source.py41
-rw-r--r--ATRI/plugins/status/__init__.py2
-rw-r--r--ATRI/plugins/status/data_source.py11
-rw-r--r--ATRI/plugins/util/__init__.py20
-rw-r--r--ATRI/plugins/util/data_source.py12
-rw-r--r--ATRI/rule.py2
-rw-r--r--ATRI/service.py143
-rw-r--r--ATRI/utils/__init__.py46
-rw-r--r--ATRI/utils/limit.py28
-rw-r--r--ATRI/utils/request.py21
30 files changed, 466 insertions, 423 deletions
diff --git a/ATRI/exceptions.py b/ATRI/exceptions.py
index bbf6c51..4ce0b17 100644
--- a/ATRI/exceptions.py
+++ b/ATRI/exceptions.py
@@ -34,7 +34,7 @@ def _save_error(prompt: str, content: str) -> str:
track_id=track_id,
prompt=prompt,
time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
- content=content
+ content=content,
)
path = ERROR_DIR / f"{track_id}.json"
with open(path, "w", encoding="utf-8") as r:
@@ -110,7 +110,7 @@ async def _track_error(
logger.debug(f"A bug has been cumming!!! Track ID: {track_id}")
msg = f"呜——出错了...追踪: {track_id}"
-
+
for superusers in BotSelfConfig.superusers:
try:
await bot.send_private_msg(user_id=superusers, message=msg)
diff --git a/ATRI/plugins/anime_search.py b/ATRI/plugins/anime_search.py
index de64501..80d8a94 100644
--- a/ATRI/plugins/anime_search.py
+++ b/ATRI/plugins/anime_search.py
@@ -24,10 +24,9 @@ __doc__ = """
class Anime(Service):
-
def __init__(self):
Service.__init__(self, "以图搜番", __doc__, rule=is_in_service("以图搜番"))
-
+
@staticmethod
async def _request(url: str) -> dict:
aim = URL + url
@@ -37,12 +36,12 @@ class Anime(Service):
raise RequestError("Request failed!")
result = await res.json()
return result
-
+
@classmethod
async def search(cls, url: str) -> str:
data = await cls._request(url)
data = data["docs"]
-
+
d = dict()
for i in range(len(data)):
if data[i]["title_chinese"] in d.keys():
@@ -61,7 +60,7 @@ class Anime(Service):
f"第{n}集",
f"{int(m)}分{int(s)}秒处",
]
-
+
result = sorted(d.items(), key=lambda x: x[1], reverse=True)
t = 0
msg0 = str()
@@ -74,7 +73,7 @@ class Anime(Service):
f"Name: {i[0]}\n"
f"Time: {i[1][1]} {i[1][2]}"
)
-
+
if len(result) == 2:
return msg0
else:
@@ -90,6 +89,7 @@ class Anime(Service):
anime_search = Anime().on_command("以图搜番", "发送一张图以搜索可能的番剧")
+
@anime_search.args_parser # type: ignore
async def _get_anime(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -101,16 +101,18 @@ async def _get_anime(bot: Bot, event: MessageEvent, state: T_State):
else:
state["anime"] = msg
+
@anime_search.handle()
async def _ready_sear(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
if not _anime_flmt.check(user_id):
await anime_search.finish(_anime_flmt_notice)
-
+
msg = str(event.message).strip()
if msg:
state["anime"] = msg
+
@anime_search.got("anime", "图呢?")
async def _deal_sear(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
@@ -118,7 +120,7 @@ async def _deal_sear(bot: Bot, event: MessageEvent, state: T_State):
img = re.findall(r"url=(.*?)]", msg)
if not img:
await anime_search.reject("请发送图片而不是其它东西!!")
-
+
a = await Anime().search(img[0])
result = f"> {MessageSegment.at(user_id)}\n" + a
_anime_flmt.start_cd(user_id)
diff --git a/ATRI/plugins/chat/__init__.py b/ATRI/plugins/chat/__init__.py
index 4864be5..7b33a6b 100644
--- a/ATRI/plugins/chat/__init__.py
+++ b/ATRI/plugins/chat/__init__.py
@@ -15,19 +15,22 @@ _chat_flmt_notice = choice(["慢...慢一..点❤", "冷静1下", "歇会歇会~
chat = Chat().on_message("闲聊(文爱")
+
@chat.handle()
async def _chat(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
if not _chat_flmt.check(user_id):
await chat.finish(_chat_flmt_notice)
-
+
msg = str(event.message)
repo = await Chat().deal(msg, user_id)
_chat_flmt.start_cd(user_id)
await chat.finish(repo)
+
my_name_is = Chat().on_command("叫我", "更改闲聊(划掉 文爱)时的称呼", aliases={"我是"}, priority=1)
+
@my_name_is.args_parser # type: ignore
async def _get_name(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -39,32 +42,38 @@ async def _get_name(bot: Bot, event: MessageEvent, state: T_State):
else:
state["name"] = msg
+
@my_name_is.handle()
async def _name(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
if not _chat_flmt.check(user_id):
await my_name_is.finish(_chat_flmt_notice)
-
+
msg = str(event.message).strip()
if msg:
state["name"] = msg
+
@my_name_is.got("name")
async def _deal_name(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
new_name = state["name"]
- repo = choice([
- f"好~w 那咱以后就称呼你为{new_name}!",
- f"噢噢噢!原来你叫{new_name}阿~",
- f"好欸!{new_name}ちゃん~~~",
- "很不错的称呼呢w"
- ])
+ repo = choice(
+ [
+ f"好~w 那咱以后就称呼你为{new_name}!",
+ f"噢噢噢!原来你叫{new_name}阿~",
+ f"好欸!{new_name}ちゃん~~~",
+ "很不错的称呼呢w",
+ ]
+ )
Chat().name_is(user_id, new_name)
_chat_flmt.start_cd(user_id)
await my_name_is.finish(repo)
+
say = Chat().on_command("说", "别人让我说啥就说啥(", priority=1)
+
@say.args_parser # type: ignore
async def _get_say(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -76,29 +85,26 @@ async def _get_say(bot: Bot, event: MessageEvent, state: T_State):
else:
state["say"] = msg
+
@say.handle()
async def _ready_say(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
if not _chat_flmt.check(user_id):
await say.finish(_chat_flmt_notice)
-
+
msg = str(event.message)
if msg:
state["say"] = msg
+
@say.got("say")
async def _deal_say(bot: Bot, event: MessageEvent, state: T_State):
msg = state["say"]
check = CoolqCodeChecker(msg).check
if not check:
- repo = choice([
- "不要...",
- "这个咱不想复读!",
- "不可以",
- "不好!"
- ])
+ repo = choice(["不要...", "这个咱不想复读!", "不可以", "不好!"])
await say.finish(repo)
-
+
user_id = event.get_user_id()
_chat_flmt.start_cd(user_id)
await say.finish(msg)
diff --git a/ATRI/plugins/chat/data_source.py b/ATRI/plugins/chat/data_source.py
index 1b0eec9..74dde96 100644
--- a/ATRI/plugins/chat/data_source.py
+++ b/ATRI/plugins/chat/data_source.py
@@ -21,16 +21,17 @@ KIMO_URL = "https://cdn.jsdelivr.net/gh/Kyomotoi/AnimeThesaurus/data.json"
class Chat(Service):
-
def __init__(self):
- Service.__init__(self, "闲聊", __doc__, rule=to_bot() & is_in_service("闲聊"), priority=5)
-
+ Service.__init__(
+ self, "闲聊", __doc__, rule=to_bot() & is_in_service("闲聊"), priority=5
+ )
+
@staticmethod
async def _request(url: str) -> dict:
res = await request.get(url)
data = await res.json()
return data
-
+
@classmethod
async def _generate_data(cls) -> None:
file_name = "kimo.json"
@@ -44,18 +45,18 @@ class Chat(Service):
log.info("生成完成")
except WriteError:
raise WriteError("Writing kimo words failed!")
-
+
@classmethod
async def _load_data(cls) -> dict:
file_name = "kimo.json"
path = CHAT_PATH / file_name
if not path.is_file():
await cls._generate_data()
-
+
with open(path, "r", encoding="utf-8") as r:
data = json.loads(r.read())
return data
-
+
@classmethod
async def update_data(cls) -> None:
log.info("更新闲聊词库ing...")
@@ -63,17 +64,17 @@ class Chat(Service):
path = CHAT_PATH / file_name
if not path.is_file():
await cls._generate_data()
-
+
updata_data = await cls._request(KIMO_URL)
data = json.loads(path.read_bytes())
for i in updata_data:
if i not in data:
data[i] = updata_data[i]
-
+
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data, indent=4))
log.info("闲聊词库更新完成")
-
+
@staticmethod
def name_is(user_id: str, new_name: str):
file_name = "users.json"
@@ -82,7 +83,7 @@ class Chat(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = {}
-
+
data = json.loads(path.read_bytes())
data[user_id] = new_name
try:
@@ -90,7 +91,7 @@ class Chat(Service):
w.write(json.dumps(data, indent=4))
except ReadFileError:
raise ReadFileError("Update user name failed!")
-
+
@staticmethod
def load_name(user_id: str) -> str:
file_name = "users.json"
@@ -99,21 +100,21 @@ class Chat(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
return "你"
-
+
data = json.loads(path.read_bytes())
try:
result = data[user_id]
except BaseException:
result = "你"
return result
-
+
@classmethod
async def deal(cls, msg: str, user_id: str) -> str:
keywords = posseg.lcut(msg)
shuffle(keywords)
-
+
data = await cls._load_data()
-
+
repo = str()
for i in keywords:
a = i.word
@@ -125,14 +126,14 @@ class Chat(Service):
pass
if a in data:
repo = data.get(a, str())
-
+
if not repo:
temp_data = list(data)
shuffle(temp_data)
for i in temp_data:
if i in msg:
repo = data.get(i, str())
-
+
a = choice(repo) if type(repo) is list else repo
user_name = cls.load_name(user_id)
repo = a.replace("你", user_name)
diff --git a/ATRI/plugins/code_runner/__init__.py b/ATRI/plugins/code_runner/__init__.py
index dfe6162..3f5697b 100644
--- a/ATRI/plugins/code_runner/__init__.py
+++ b/ATRI/plugins/code_runner/__init__.py
@@ -13,15 +13,16 @@ _flmt_notice = choice(["慢...慢一..点❤", "冷静1下", "歇会歇会~~"])
code_runner = CodeRunner().on_command("/code", "在线运行一段代码,帮助:/code help")
+
@code_runner.handle()
async def _code_runner(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
if not _flmt.check(user_id):
await code_runner.finish(_flmt_notice)
-
+
msg = str(event.get_message())
args = msg.split("\n")
-
+
if not args:
content = f"> {MessageSegment.at(user_id)}\n" + "请键入 /code help 以获取帮助~!"
elif args[0] == "help":
@@ -30,6 +31,6 @@ async def _code_runner(bot: Bot, event: MessageEvent):
content = f"> {MessageSegment.at(user_id)}\n" + CodeRunner().list_supp_lang()
else:
content = MessageSegment.at(user_id) + await CodeRunner().runner(msg)
-
+
_flmt.start_cd(user_id)
await code_runner.finish(Message(content))
diff --git a/ATRI/plugins/code_runner/data_source.py b/ATRI/plugins/code_runner/data_source.py
index bbe0d2e..4338697 100644
--- a/ATRI/plugins/code_runner/data_source.py
+++ b/ATRI/plugins/code_runner/data_source.py
@@ -40,10 +40,9 @@ __doc__ = """
class CodeRunner(Service):
-
def __init__(self):
Service.__init__(self, "在线跑代码", __doc__, rule=is_in_service("在线跑代码"))
-
+
@staticmethod
def help() -> str:
return (
@@ -53,23 +52,23 @@ class CodeRunner(Service):
"/code python\n"
"print('hello world')"
)
-
+
@staticmethod
def list_supp_lang() -> str:
msg0 = "咱现在支持的语言如下:\n"
msg0 += ", ".join(map(str, SUPPORTED_LANGUAGES.keys()))
return msg0
-
+
@staticmethod
async def runner(msg: str):
args = msg.split("\n")
if not args:
return "请检查键入内容..."
-
+
lang = args[0].replace("\r", "")
if lang not in SUPPORTED_LANGUAGES:
return "该语言暂不支持..."
-
+
del args[0]
code = "\n".join(map(str, args))
url = RUN_API_URL_FORMAT.format(lang)
@@ -84,14 +83,14 @@ class CodeRunner(Service):
}
],
"stdin": "",
- "command": ""
+ "command": "",
}
-
+
try:
res = await request.post(url, json=js)
except RequestError:
raise RequestError("Request failed!")
-
+
payload = await res.json()
sent = False
for k in ["stdout", "stderr", "error"]:
@@ -100,12 +99,12 @@ class CodeRunner(Service):
lines, remained_lines = lines[:10], lines[10:]
out = "\n".join(lines)
out, remained_out = out[: 60 * 10], out[60 * 10 :]
-
+
if remained_lines or remained_out:
out += f"\n(太多了太多了...)"
-
+
if out:
return f"\n{k}:\n{out}"
-
+
if not sent:
- return "\n运行完成,没任何输出呢..." \ No newline at end of file
+ return "\n运行完成,没任何输出呢..."
diff --git a/ATRI/plugins/curse.py b/ATRI/plugins/curse.py
index b2dbc05..edd6249 100644
--- a/ATRI/plugins/curse.py
+++ b/ATRI/plugins/curse.py
@@ -20,10 +20,9 @@ __doc__ = """
class Curse(Service):
-
def __init__(self):
Service.__init__(self, "口臭", __doc__, rule=is_in_service("口臭"))
-
+
@staticmethod
async def now() -> str:
res = await request.get(URL)
@@ -31,14 +30,17 @@ class Curse(Service):
return result
-normal_curse = Curse().on_command("口臭一下", "主命令,骂你一下", aliases={"骂我", "口臭"}, rule=to_bot())
+normal_curse = Curse().on_command(
+ "口臭一下", "主命令,骂你一下", aliases={"骂我", "口臭"}, rule=to_bot()
+)
+
@normal_curse.handle()
async def _deal_n_curse(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
if not _curse_flmt.check(user_id):
await normal_curse.finish(_curse_flmt_notice)
-
+
result = await Curse().now()
_curse_flmt.start_cd(user_id)
await normal_curse.finish(result)
@@ -46,12 +48,13 @@ async def _deal_n_curse(bot: Bot, event: MessageEvent):
super_curse = Curse().on_regex(r"[来求有](.*?)骂我吗?", "有求必应")
+
@super_curse.handle()
async def _deal_s_curse(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
if not _curse_flmt.check(user_id):
await normal_curse.finish(_curse_flmt_notice)
-
+
result = await Curse().now()
_curse_flmt.start_cd(user_id)
await normal_curse.finish(result)
diff --git a/ATRI/plugins/essential.py b/ATRI/plugins/essential.py
index 5369c9b..80e5734 100644
--- a/ATRI/plugins/essential.py
+++ b/ATRI/plugins/essential.py
@@ -62,9 +62,9 @@ async def _check_block(
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
data = json.loads(path.read_bytes())
-
+
user_id = event.get_user_id()
if user_id in data:
raise IgnoredException(f"Block user: {user_id}")
@@ -76,9 +76,9 @@ async def _check_block(
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
data = json.loads(path.read_bytes())
-
+
group_id = str(event.group_id)
if group_id in data:
raise IgnoredException(f"Block group: {user_id}")
@@ -104,13 +104,13 @@ __doc__ = """
class Essential(Service):
-
def __init__(self):
Service.__init__(self, "基础部件", __doc__)
friend_add_event = Essential().on_request("好友添加")
+
@friend_add_event.handle()
async def _friend_add(bot: Bot, event: FriendRequestEvent):
"""
@@ -130,22 +130,19 @@ async def _friend_add(bot: Bot, event: FriendRequestEvent):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
apply_code = event.flag
apply_comment = event.comment
user_id = event.get_user_id()
now_time = datetime.now()
-
+
data = json.loads(path.read_bytes())
data[apply_code] = FriendRequestInfo(
- user_id=user_id,
- comment=apply_comment,
- time=now_time,
- is_approve=False
+ user_id=user_id, comment=apply_comment, time=now_time, is_approve=False
)
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data.dict(), indent=4))
-
+
repo = (
"咱收到一条好友请求...\n"
f"请求人:{user_id}\n"
@@ -159,6 +156,7 @@ async def _friend_add(bot: Bot, event: FriendRequestEvent):
group_invite_event = Essential().on_request("邀请入群")
+
@group_invite_event.handle()
async def _group_invite(bot: Bot, event: GroupRequestEvent):
"""
@@ -178,22 +176,19 @@ async def _group_invite(bot: Bot, event: GroupRequestEvent):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
apply_code = event.flag
apply_comment = event.comment
user_id = event.get_user_id()
now_time = datetime.now()
-
+
data = json.loads(path.read_bytes())
data[apply_code] = GroupRequestInfo(
- user_id=user_id,
- comment=apply_comment,
- time=now_time,
- is_approve=False
+ user_id=user_id, comment=apply_comment, time=now_time, is_approve=False
)
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data.dict(), indent=4))
-
+
repo = (
"咱收到一条群聊邀请请求...\n"
f"请求人:{user_id}\n"
@@ -207,15 +202,14 @@ async def _group_invite(bot: Bot, event: GroupRequestEvent):
group_member_event = Essential().on_notice("群成员变动")
+
@group_member_event.handle()
async def _group_member_join(bot: Bot, event: GroupIncreaseNoticeEvent):
await asyncio.sleep(randint(1, 6))
- msg = (
- "好欸!事新人!\n"
- f"在下 {choice(list(BotSelfConfig.nickname))} 哒!w!"
- )
+ msg = "好欸!事新人!\n" f"在下 {choice(list(BotSelfConfig.nickname))} 哒!w!"
await group_member_event.finish(msg)
+
@group_member_event.handle()
async def _group_member_left(bot: Bot, event: GroupDecreaseNoticeEvent):
await asyncio.sleep(randint(1, 6))
@@ -224,6 +218,7 @@ async def _group_member_left(bot: Bot, event: GroupDecreaseNoticeEvent):
group_admin_event = Essential().on_notice("群管理变动")
+
@group_admin_event.handle()
async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent):
if not event.is_tome():
@@ -237,6 +232,7 @@ async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent):
group_ban_event = Essential().on_notice("群禁言变动")
+
@group_ban_event.handle()
async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent):
if not event.is_tome():
@@ -258,11 +254,12 @@ async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent):
recall_event = Essential().on_notice("撤回事件")
+
@recall_event.handle()
async def _recall_group_event(bot: Bot, event: GroupRecallNoticeEvent):
if event.is_tome():
return
-
+
try:
repo = await bot.get_msg(message_id=event.message_id)
except BaseException:
@@ -275,12 +272,7 @@ async def _recall_group_event(bot: Bot, event: GroupRecallNoticeEvent):
if not check:
repo = repo.replace("CQ", "QC")
- msg = (
- "主人,咱拿到了一条撤回信息!\n"
- f"{user}@[群:{group}]\n"
- "撤回了\n"
- f"{repo}"
- )
+ msg = "主人,咱拿到了一条撤回信息!\n" f"{user}@[群:{group}]\n" "撤回了\n" f"{repo}"
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=int(superuser), message=msg)
@@ -289,7 +281,7 @@ async def _recall_group_event(bot: Bot, event: GroupRecallNoticeEvent):
async def _recall_private_event(bot: Bot, event: FriendRecallNoticeEvent):
if event.is_tome():
return
-
+
try:
repo = await bot.get_msg(message_id=event.message_id)
except BaseException:
@@ -301,11 +293,6 @@ async def _recall_private_event(bot: Bot, event: FriendRecallNoticeEvent):
if not check:
repo = repo.replace("CQ", "QC")
- msg = (
- "主人,咱拿到了一条撤回信息!\n"
- f"{user}@[私聊]"
- "撤回了\n"
- f"{repo}"
- )
+ msg = "主人,咱拿到了一条撤回信息!\n" f"{user}@[私聊]" "撤回了\n" f"{repo}"
for superuser in BotSelfConfig.superusers:
await bot.send_private_msg(user_id=int(superuser), message=msg)
diff --git a/ATRI/plugins/funny/__init__.py b/ATRI/plugins/funny/__init__.py
index de98381..a22e2d5 100644
--- a/ATRI/plugins/funny/__init__.py
+++ b/ATRI/plugins/funny/__init__.py
@@ -5,11 +5,12 @@ from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.adapters.cqhttp.message import Message
from ATRI.utils.limit import FreqLimiter, DailyLimiter
-from.data_source import Funny
+from .data_source import Funny
get_laugh = Funny().on_command("来句笑话", "隐晦的笑话...")
+
@get_laugh.handle()
async def _get_laugh(bot: Bot, event: MessageEvent):
user_name = event.sender.nickname or "该裙友"
@@ -18,6 +19,7 @@ async def _get_laugh(bot: Bot, event: MessageEvent):
me_re_you = Funny().on_regex(r"我", "我也不懂咋解释", block=False)
+
@me_re_you.handle()
async def _me_re_you(bot: Bot, event: MessageEvent):
if randint(0, 15) == 5:
@@ -27,13 +29,16 @@ async def _me_re_you(bot: Bot, event: MessageEvent):
await me_re_you.finish(content)
-fake_msg = Funny().on_command("/fakemsg", "伪造假转发内容,格式:qq-name-content\n可构造多条,使用空格隔开,仅限群聊")
+fake_msg = Funny().on_command(
+ "/fakemsg", "伪造假转发内容,格式:qq-name-content\n可构造多条,使用空格隔开,仅限群聊"
+)
_fake_daliy_max = DailyLimiter(3)
_fake_max_notice = "不能继续下去了!明早再来"
_fake_flmt = FreqLimiter(60)
_fake_flmt_notice = choice(["慢...慢一..点❤", "冷静1下", "歇会歇会~~"])
+
@fake_msg.args_parser # type: ignore
async def _perp_fake(bot: Bot, event: GroupMessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -45,6 +50,7 @@ async def _perp_fake(bot: Bot, event: GroupMessageEvent, state: T_State):
else:
state["content"] = msg
+
@fake_msg.handle()
async def _ready_fake(bot: Bot, event: GroupMessageEvent, state: T_State):
user_id = event.get_user_id()
@@ -52,11 +58,12 @@ async def _ready_fake(bot: Bot, event: GroupMessageEvent, state: T_State):
await fake_msg.finish(_fake_max_notice)
if not _fake_flmt.check(user_id):
await fake_msg.finish(_fake_flmt_notice)
-
+
msg = str(event.message).strip()
if msg:
state["content"] = msg
+
@fake_msg.got("content", "内容呢?格式:qq-name-content\n可构造多条,以上仅为一条,使用空格隔开")
async def _deal_fake(bot: Bot, event: GroupMessageEvent, state: T_State):
content = state["content"]
@@ -64,7 +71,7 @@ async def _deal_fake(bot: Bot, event: GroupMessageEvent, state: T_State):
user_id = event.get_user_id()
node = Funny().fake_msg(content)
await bot.send_group_forward_msg(group_id=group_id, messages=node)
-
+
_fake_flmt.start_cd(user_id)
_fake_daliy_max.increase(user_id)
@@ -73,12 +80,13 @@ eat_what = Funny().on_regex(r"大?[今明后]天(.*?)吃[什啥]么?", "我来�
_eat_flmt = FreqLimiter(15)
+
@eat_what.handle()
async def _eat_what(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
if not _eat_flmt.check(user_id):
return
-
+
msg = str(event.get_message())
user_name = event.sender.nickname or "裙友"
eat = await Funny().eat_what(user_name, msg)
diff --git a/ATRI/plugins/funny/data_source.py b/ATRI/plugins/funny/data_source.py
index a27cdb5..f298683 100644
--- a/ATRI/plugins/funny/data_source.py
+++ b/ATRI/plugins/funny/data_source.py
@@ -17,35 +17,34 @@ __doc__ = """
class Funny(Service):
-
def __init__(self):
Service.__init__(self, "乐", __doc__, rule=is_in_service("乐"))
-
+
@staticmethod
def idk_laugh(name: str) -> str:
laugh_list = list()
-
+
file_path = Path(".") / "ATRI" / "data" / "database" / "funny" / "laugh.txt"
with open(file_path, encoding="utf-8") as r:
for line in r:
laugh_list.append(line.strip("\n"))
-
+
rd: str = choice(laugh_list)
result = rd.replace("%name", name)
return result
-
+
@staticmethod
def me_re_you(msg: str) -> tuple:
if "我" in msg and "[CQ" not in msg:
return msg.replace("我", "你"), True
else:
return msg, False
-
+
@staticmethod
def fake_msg(text: str) -> list:
arg = text.split(" ")
node = list()
-
+
for i in arg:
args = i.split("-")
qq = args[0]
@@ -54,7 +53,7 @@ class Funny(Service):
dic = {"type": "node", "data": {"name": name, "uin": qq, "content": repo}}
node.append(dic)
return node
-
+
@staticmethod
async def eat_what(name: str, msg: str) -> str:
EAT_URL = "https://wtf.hiigara.net/api/run/"
@@ -63,7 +62,7 @@ class Funny(Service):
pattern_1 = r"(今|明|后|大后)天"
arg = re.findall(pattern_0, msg)[0]
day = re.match(pattern_1, msg).group(0) # type: ignore
-
+
if arg == "中午":
a = f"LdS4K6/{randint(0, 1145141919810)}"
url = EAT_URL + a
@@ -72,11 +71,11 @@ class Funny(Service):
data = await data.json()
except RequestError:
raise RequestError("Request failed!")
-
+
text = Translate(data["text"]).to_simple().replace("今天", day)
get_a = re.search(r"非常(.*?)的", text).group(0) # type: ignore
result = text.replace(get_a, "")
-
+
elif arg == "晚上":
a = f"KaTMS/{randint(0, 1145141919810)}"
url = EAT_URL + a
@@ -85,17 +84,13 @@ class Funny(Service):
data = await data.json()
except RequestError:
raise RequestError("Request failed!")
-
+
result = Translate(data["text"]).to_simple().replace("今天", day)
-
+
else:
rd = randint(1, 10)
if rd == 5:
- result = [
- "吃我吧 ❤",
- "(脸红)请...请享用咱吧......",
- "都可以哦~不能挑食呢~"
- ]
+ result = ["吃我吧 ❤", "(脸红)请...请享用咱吧......", "都可以哦~不能挑食呢~"]
return choice(result)
else:
a = f"JJr1hJ/{randint(0, 1145141919810)}"
@@ -105,9 +100,9 @@ class Funny(Service):
data = await data.json()
except RequestError:
raise RequestError("Request failed!")
-
+
text = Translate(data["text"]).to_simple().replace("今天", day)
get_a = re.match(r"(.*?)的智商", text).group(0) # type: ignore
result = text.replace(get_a, f"{name}的智商")
-
- return result \ No newline at end of file
+
+ return result
diff --git a/ATRI/plugins/help/__init__.py b/ATRI/plugins/help/__init__.py
index 1d9af19..efdd985 100644
--- a/ATRI/plugins/help/__init__.py
+++ b/ATRI/plugins/help/__init__.py
@@ -5,7 +5,10 @@ from ATRI.rule import to_bot
from .data_source import Helper
-main_help = Helper().on_command("菜单", "获取食用bot的方法", rule=to_bot(), aliases={"/help", "menu"})
+main_help = Helper().on_command(
+ "菜单", "获取食用bot的方法", rule=to_bot(), aliases={"/help", "menu"}
+)
+
@main_help.handle()
async def _main_help(bot: Bot, event: MessageEvent):
@@ -15,6 +18,7 @@ async def _main_help(bot: Bot, event: MessageEvent):
about_me = Helper().on_command("关于", "获取关于bot的信息", rule=to_bot(), aliases={"about"})
+
@about_me.handle()
async def _about_me(bot: Bot, event: MessageEvent):
repo = Helper().about()
@@ -23,6 +27,7 @@ async def _about_me(bot: Bot, event: MessageEvent):
service_list = Helper().on_command("服务列表", "查看所有可用服务", rule=to_bot(), aliases={"功能列表"})
+
@service_list.handle()
async def _service_list(bot: Bot, event: MessageEvent):
repo = Helper().service_list()
@@ -31,6 +36,7 @@ async def _service_list(bot: Bot, event: MessageEvent):
service_info = Helper().on_command("帮助", "获取服务详细帮助")
+
@service_info.handle()
async def _ready_service_info(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).split(" ")
@@ -39,10 +45,10 @@ async def _ready_service_info(bot: Bot, event: MessageEvent, state: T_State):
cmd = msg[1]
except BaseException:
cmd = str()
-
+
if not cmd:
repo = Helper().service_info(service)
await service_info.finish(repo)
-
+
repo = Helper().cmd_info(service, cmd)
await service_info.finish(repo)
diff --git a/ATRI/plugins/help/data_source.py b/ATRI/plugins/help/data_source.py
index 930f4bb..831d1e0 100644
--- a/ATRI/plugins/help/data_source.py
+++ b/ATRI/plugins/help/data_source.py
@@ -24,10 +24,9 @@ COMMAND_INFO_FORMAT = """
class Helper(Service):
-
def __init__(self):
Service.__init__(self, "帮助", "bot的食用指南~")
-
+
@staticmethod
def menu() -> str:
return (
@@ -37,7 +36,7 @@ class Helper(Service):
"帮助 [服务] -以查看对应服务帮助\n"
"Tip: 均需要at触发。菜单 打开此页面"
)
-
+
@staticmethod
def about() -> str:
temp_list = list()
@@ -51,7 +50,7 @@ class Helper(Service):
"想进一步了解:\n"
"https://github.com/Kyomotoi/ATRI"
)
-
+
@staticmethod
def service_list() -> str:
files = os.listdir(SERVICES_DIR)
@@ -59,42 +58,42 @@ class Helper(Service):
for i in files:
service = i.replace(".json", "")
temp_list.append(service)
-
+
msg0 = "咱搭载了以下服务~\n"
services = " | ".join(map(str, temp_list))
msg0 = msg0 + services
repo = msg0 + "\n帮助 [服务] -以查看对应服务帮助"
return repo
-
+
@staticmethod
def service_info(service: str) -> str:
try:
data = ServiceTools().load_service(service)
except ReadFileError:
return "请检查是否输入错误呢..."
-
+
service_name = data.get("service", "error")
service_docs = data.get("docs", "error")
service_enabled = data.get("enabled", True)
-
+
_service_cmd_list = list(data.get("cmd_list", {"error"}))
service_cmd_list = "\n".join(map(str, _service_cmd_list))
-
+
repo = SERVICE_INFO_FORMAT.format(
service=service_name,
docs=service_docs,
cmd_list=service_cmd_list,
- enabled=service_enabled
+ enabled=service_enabled,
)
return repo
-
+
@staticmethod
def cmd_info(service: str, cmd: str) -> str:
try:
data = ServiceTools().load_service(service)
except ReadFileError:
return "请检查是否输入错误..."
-
+
cmd_list: dict = data["cmd_list"]
cmd_info = cmd_list.get(cmd, dict())
if not cmd_info:
@@ -102,11 +101,8 @@ class Helper(Service):
cmd_type = cmd_info.get("type", "ignore")
docs = cmd_info.get("docs", "ignore")
aliases = cmd_info.get("aliases", "ignore")
-
+
repo = COMMAND_INFO_FORMAT.format(
- cmd=cmd,
- cmd_type=cmd_type,
- docs=docs,
- aliases=aliases
+ cmd=cmd, cmd_type=cmd_type, docs=docs, aliases=aliases
)
return repo
diff --git a/ATRI/plugins/manege/__init__.py b/ATRI/plugins/manege/__init__.py
index d0337e9..305cdc5 100644
--- a/ATRI/plugins/manege/__init__.py
+++ b/ATRI/plugins/manege/__init__.py
@@ -13,6 +13,7 @@ from .data_source import Manege
block_user = Manege().on_command("封禁用户", "对目标用户进行封禁", permission=SUPERUSER)
+
@block_user.args_parser # type: ignore
async def _get_block_user(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -24,24 +25,27 @@ async def _get_block_user(bot: Bot, event: MessageEvent, state: T_State):
else:
state["block_user"] = msg
+
@block_user.handle()
async def _ready_block_user(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["block_user"] = msg
+
@block_user.got("block_user", "哪位?GKD!")
async def _deal_block_user(bot: Bot, event: MessageEvent, state: T_State):
user_id = state["block_user"]
is_ok = Manege().block_user(user_id)
if not is_ok:
await block_user.finish("kuso!封禁失败了...")
-
+
await block_user.finish(f"用户 {user_id} 危!")
unblock_user = Manege().on_command("解封用户", "对目标用户进行解封", permission=SUPERUSER)
+
@unblock_user.args_parser # type: ignore
async def _get_unblock_user(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -53,24 +57,27 @@ async def _get_unblock_user(bot: Bot, event: MessageEvent, state: T_State):
else:
state["unblock_user"] = msg
+
@unblock_user.handle()
async def _ready_unblock_user(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["unblock_user"] = msg
+
@unblock_user.got("unblock_user", "哪位?GKD!")
async def _deal_unblock_user(bot: Bot, event: MessageEvent, state: T_State):
user_id = state["unblock_user"]
is_ok = Manege().unblock_user(user_id)
if not is_ok:
await unblock_user.finish("kuso!解封失败了...")
-
+
await unblock_user.finish(f"好欸!{user_id} 重获新生!")
block_group = Manege().on_command("封禁群", "对目标群进行封禁", permission=SUPERUSER)
+
@block_group.args_parser # type: ignore
async def _get_block_group(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -82,24 +89,27 @@ async def _get_block_group(bot: Bot, event: MessageEvent, state: T_State):
else:
state["block_group"] = msg
+
@block_group.handle()
async def _ready_block_group(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["block_group"] = msg
+
@block_group.got("block_group", "哪个群?GKD!")
async def _deal_block_group(bot: Bot, event: MessageEvent, state: T_State):
group_id = state["block_group"]
is_ok = Manege().block_group(group_id)
if not is_ok:
await block_group.finish("kuso!封禁失败了...")
-
+
await block_group.finish(f"群 {group_id} 危!")
unblock_group = Manege().on_command("解封群", "对目标群进行解封", permission=SUPERUSER)
+
@unblock_group.args_parser # type: ignore
async def _get_unblock_group(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -111,24 +121,27 @@ async def _get_unblock_group(bot: Bot, event: MessageEvent, state: T_State):
else:
state["unblock_group"] = msg
+
@unblock_group.handle()
async def _ready_unblock_group(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["unblock_group"] = msg
+
@unblock_group.got("unblock_group", "哪个群?GKD!")
async def _deal_unblock_group(bot: Bot, event: MessageEvent, state: T_State):
group_id = state["unblock_group"]
is_ok = Manege().unblock_group(group_id)
if not is_ok:
await unblock_group.finish("kuso!解封失败了...")
-
+
await unblock_group.finish(f"好欸!群 {group_id} 重获新生!")
global_block_service = Manege().on_command("全局禁用", "全局禁用某服务", permission=SUPERUSER)
+
@global_block_service.args_parser # type: ignore
async def _get_global_block_service(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -140,24 +153,27 @@ async def _get_global_block_service(bot: Bot, event: MessageEvent, state: T_Stat
else:
state["global_block_service"] = msg
+
@global_block_service.handle()
async def _ready_block_service(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["global_block_service"] = msg
+
@global_block_service.got("global_block_service", "阿...是哪个服务呢")
async def _deal_global_block_service(bot: Bot, event: MessageEvent, state: T_State):
block_service = state["global_block_service"]
is_ok = Manege().control_global_service(block_service, False)
if not is_ok:
await global_block_service.finish("kuso!禁用失败了...")
-
+
await global_block_service.finish(f"服务 {block_service} 已被禁用")
global_unblock_service = Manege().on_command("全局启用", "全局启用某服务", permission=SUPERUSER)
+
@global_unblock_service.args_parser # type: ignore
async def _get_global_unblock_service(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -169,23 +185,28 @@ async def _get_global_unblock_service(bot: Bot, event: MessageEvent, state: T_St
else:
state["global_unblock_service"] = msg
+
@global_unblock_service.handle()
async def _ready_unblock_service(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["global_unblock_service"] = msg
+
@global_unblock_service.got("global_unblock_service", "阿...是哪个服务呢")
async def _deal_global_unblock_service(bot: Bot, event: MessageEvent, state: T_State):
block_service = state["global_unblock_service"]
is_ok = Manege().control_global_service(block_service, True)
if not is_ok:
await global_unblock_service.finish("kuso!启用服务失败了...")
-
+
await global_unblock_service.finish(f"服务 {block_service} 已启用")
-user_block_service = Manege().on_regex(r"对用户(.*?)禁用(.*)", "针对某一用户禁用服务", permission=SUPERUSER)
+user_block_service = Manege().on_regex(
+ r"对用户(.*?)禁用(.*)", "针对某一用户禁用服务", permission=SUPERUSER
+)
+
@user_block_service.handle()
async def _user_block_service(bot: Bot, event: MessageEvent):
@@ -194,15 +215,17 @@ async def _user_block_service(bot: Bot, event: MessageEvent):
reg = re.findall(pattern, msg)
aim_user = reg[0]
aim_service = reg[1]
-
+
is_ok = Manege().control_user_service(aim_service, aim_user, False)
if not is_ok:
await user_block_service.finish("禁用失败...请检查服务名是否正确")
await user_block_service.finish(f"完成~已禁止用户 {aim_user} 使用 {aim_service}")
-
-user_unblock_service = Manege().on_regex(r"对用户(.*?)启用(.*)", "针对某一用户启用服务", permission=SUPERUSER)
+user_unblock_service = Manege().on_regex(
+ r"对用户(.*?)启用(.*)", "针对某一用户启用服务", permission=SUPERUSER
+)
+
@user_unblock_service.handle()
async def _user_unblock_service(bot: Bot, event: MessageEvent):
@@ -211,14 +234,17 @@ async def _user_unblock_service(bot: Bot, event: MessageEvent):
reg = re.findall(pattern, msg)
aim_user = reg[0]
aim_service = reg[1]
-
+
is_ok = Manege().control_user_service(aim_service, aim_user, True)
if not is_ok:
await user_unblock_service.finish("启用失败...请检查服务名是否正确,或者此人并不存在于名单中")
await user_unblock_service.finish(f"完成~已允许用户 {aim_user} 使用 {aim_service}")
-group_block_service = Manege().on_command("禁用", "针对所在群禁用某服务", permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN)
+group_block_service = Manege().on_command(
+ "禁用", "针对所在群禁用某服务", permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN
+)
+
@group_block_service.args_parser # type: ignore
async def _get_group_block_service(bot: Bot, event: GroupMessageEvent, state: T_State):
@@ -231,27 +257,36 @@ async def _get_group_block_service(bot: Bot, event: GroupMessageEvent, state: T_
else:
state["group_block_service"] = msg
+
@group_block_service.handle()
-async def _ready_group_block_service(bot: Bot, event: GroupMessageEvent, state: T_State):
+async def _ready_group_block_service(
+ bot: Bot, event: GroupMessageEvent, state: T_State
+):
msg = str(event.message).strip()
if msg:
state["group_block_service"] = msg
+
@group_block_service.got("group_block_service", "阿...是哪个服务呢")
async def _deal_group_block_service(bot: Bot, event: GroupMessageEvent, state: T_State):
aim_service = state["group_block_service"]
group_id = str(event.group_id)
-
+
is_ok = Manege().control_group_service(aim_service, group_id, False)
if not is_ok:
await group_block_service.finish("禁用失败...请检查服务名是否输入正确")
await group_block_service.finish(f"完成!~已禁止本群使用服务:{aim_service}")
-group_unblock_service = Manege().on_command("启用", "针对所在群启用某服务", permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN)
+group_unblock_service = Manege().on_command(
+ "启用", "针对所在群启用某服务", permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN
+)
+
@group_unblock_service.args_parser # type: ignore
-async def _get_group_unblock_service(bot: Bot, event: GroupMessageEvent, state: T_State):
+async def _get_group_unblock_service(
+ bot: Bot, event: GroupMessageEvent, state: T_State
+):
msg = str(event.message).strip()
quit_list = ["算了", "罢了"]
if msg in quit_list:
@@ -261,17 +296,23 @@ async def _get_group_unblock_service(bot: Bot, event: GroupMessageEvent, state:
else:
state["group_unblock_service"] = msg
+
@group_unblock_service.handle()
-async def _ready_group_unblock_service(bot: Bot, event: GroupMessageEvent, state: T_State):
+async def _ready_group_unblock_service(
+ bot: Bot, event: GroupMessageEvent, state: T_State
+):
msg = str(event.message).strip()
if msg:
state["group_unblock_service"] = msg
+
@group_unblock_service.got("group_unblock_service", "阿...是哪个服务呢")
-async def _deal_group_unblock_service(bot: Bot, event: GroupMessageEvent, state: T_State):
+async def _deal_group_unblock_service(
+ bot: Bot, event: GroupMessageEvent, state: T_State
+):
aim_service = state["group_unblock_service"]
group_id = str(event.group_id)
-
+
is_ok = Manege().control_group_service(aim_service, group_id, True)
if not is_ok:
await group_unblock_service.finish("启用失败...请检查服务名是否输入正确,或群不存在于名单中")
@@ -280,6 +321,7 @@ async def _deal_group_unblock_service(bot: Bot, event: GroupMessageEvent, state:
get_friend_add_list = Manege().on_command("获取好友申请", "获取好友申请列表", permission=SUPERUSER)
+
@get_friend_add_list.handle()
async def _get_friend_add_list(bot: Bot, event: MessageEvent):
data = Manege().load_friend_apply_list()
@@ -294,10 +336,11 @@ async def _get_friend_add_list(bot: Bot, event: MessageEvent):
msg0 = "申请人ID | 申请信息 | 申请码\n" + "\n".join(map(str, temp_list))
msg1 = msg0 + "\nTip: 使用 同意/拒绝好友 [申请码] 以决定"
await get_friend_add_list.finish(msg1)
-
+
approve_friend_add = Manege().on_command("同意好友", "同意好友申请", permission=SUPERUSER)
+
@approve_friend_add.args_parser # type: ignore
async def _get_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -309,12 +352,14 @@ async def _get_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State)
else:
state["approve_friend_add"] = msg
+
@approve_friend_add.handle()
async def _ready_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["approve_friend_add"]
+
@approve_friend_add.got("approve_friend_add", "申请码GKD!")
async def _deal_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State):
apply_code = state["approve_friend_add"]
@@ -330,6 +375,7 @@ async def _deal_approve_friend_add(bot: Bot, event: MessageEvent, state: T_State
refuse_friend_add = Manege().on_command("拒绝好友", "拒绝好友申请", permission=SUPERUSER)
+
@refuse_friend_add.args_parser # type: ignore
async def _get_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -341,12 +387,14 @@ async def _get_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State):
else:
state["refuse_friend_add"] = msg
+
@refuse_friend_add.handle()
async def _ready_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["refuse_friend_add"]
+
@refuse_friend_add.got("refuse_friend_add", "申请码GKD!")
async def _deal_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State):
apply_code = state["refuse_friend_add"]
@@ -362,6 +410,7 @@ async def _deal_refuse_friend_add(bot: Bot, event: MessageEvent, state: T_State)
get_group_invite_list = Manege().on_command("获取邀请列表", "获取群邀请列表", permission=SUPERUSER)
+
@get_group_invite_list.handle()
async def _get_group_invite_list(bot: Bot, event: MessageEvent):
data = Manege().load_invite_apply_list()
@@ -380,6 +429,7 @@ async def _get_group_invite_list(bot: Bot, event: MessageEvent):
approve_group_invite = Manege().on_command("同意邀请", "同意群聊邀请", permission=SUPERUSER)
+
@approve_group_invite.args_parser # type: ignore
async def _get_approve_group_invite(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -391,17 +441,21 @@ async def _get_approve_group_invite(bot: Bot, event: MessageEvent, state: T_Stat
else:
state["approve_group_invite"] = msg
+
@approve_group_invite.handle()
async def _ready_approve_group_invite(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["approve_group_invite"]
+
@approve_group_invite.got("approve_group_invite", "申请码GKD!")
async def _deal_approve_group_invite(bot: Bot, event: MessageEvent, state: T_State):
apply_code = state["approve_group_invite"]
try:
- await bot.set_group_add_request(flag=apply_code, sub_type="invite", approve=True)
+ await bot.set_group_add_request(
+ flag=apply_code, sub_type="invite", approve=True
+ )
except BaseException:
await approve_group_invite.finish("同意失败...尝试下手动?")
data = Manege().load_invite_apply_list()
@@ -412,6 +466,7 @@ async def _deal_approve_group_invite(bot: Bot, event: MessageEvent, state: T_Sta
refuse_group_invite = Manege().on_command("拒绝邀请", "拒绝群聊邀请", permission=SUPERUSER)
+
@refuse_group_invite.args_parser # type: ignore
async def _get_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -423,17 +478,21 @@ async def _get_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_State
else:
state["refuse_group_invite"] = msg
+
@refuse_group_invite.handle()
async def _ready_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["refuse_group_invite"]
+
@refuse_group_invite.got("refuse_group_invite", "申请码GKD!")
async def _deal_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_State):
apply_code = state["refuse_group_invite"]
try:
- await bot.set_group_add_request(flag=apply_code, sub_type="invite", approve=False)
+ await bot.set_group_add_request(
+ flag=apply_code, sub_type="invite", approve=False
+ )
except BaseException:
await refuse_group_invite.finish("拒绝失败...尝试下手动?")
data = Manege().load_invite_apply_list()
@@ -444,6 +503,7 @@ async def _deal_refuse_group_invite(bot: Bot, event: MessageEvent, state: T_Stat
track_error = Manege().on_command("追踪", "获取报错信息,传入追踪码", aliases={"/track"})
+
@track_error.handle()
async def _track_error(bot: Bot, event: MessageEvent):
track_id = str(event.message).strip()
diff --git a/ATRI/plugins/manege/data_source.py b/ATRI/plugins/manege/data_source.py
index 933f6c6..6717f6d 100644
--- a/ATRI/plugins/manege/data_source.py
+++ b/ATRI/plugins/manege/data_source.py
@@ -9,7 +9,7 @@ from ATRI.utils import UbuntuPaste
from ATRI.exceptions import ReadFileError, load_error
-MANEGE_DIR = Path(".") / "ATRI" / "data"/ "database" / "manege"
+MANEGE_DIR = Path(".") / "ATRI" / "data" / "database" / "manege"
ESSENTIAL_DIR = Path(".") / "ATRI" / "data" / "database" / "essential"
os.makedirs(MANEGE_DIR, exist_ok=True)
os.makedirs(ESSENTIAL_DIR, exist_ok=True)
@@ -29,7 +29,6 @@ __doc__ = """
class Manege(Service):
-
def __init__(self):
Service.__init__(self, "管理", __doc__, True)
@@ -49,11 +48,10 @@ class Manege(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
data = json.loads(path.read_bytes())
return data
-
-
+
@staticmethod
def _save_block_user_list(data: dict) -> None:
file_name = "block_user.json"
@@ -62,10 +60,10 @@ class Manege(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data, indent=4))
-
+
@staticmethod
def _load_block_group_list() -> dict:
"""
@@ -82,10 +80,10 @@ class Manege(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
data = json.loads(path.read_bytes())
return data
-
+
@staticmethod
def _save_block_group_list(data: dict) -> None:
file_name = "block_group.json"
@@ -94,55 +92,51 @@ class Manege(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps({}))
data = dict()
-
+
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data, indent=4))
-
+
@classmethod
def block_user(cls, user_id: str) -> bool:
data = cls._load_block_user_list()
now_time = datetime.now()
- data[user_id] = {
- "time": now_time
- }
+ data[user_id] = {"time": now_time}
try:
cls._save_block_user_list(data)
return True
except BaseException:
return False
-
+
@classmethod
def unblock_user(cls, user_id: str) -> bool:
data: dict = cls._load_block_user_list()
if user_id not in data:
return False
-
+
try:
data.pop(user_id)
cls._save_block_user_list(data)
return True
except BaseException:
return False
-
+
@classmethod
def block_group(cls, group_id: str) -> bool:
data = cls._load_block_group_list()
now_time = datetime.now()
- data[group_id] = {
- "time": now_time
- }
+ data[group_id] = {"time": now_time}
try:
cls._save_block_group_list(data)
return True
except BaseException:
return False
-
+
@classmethod
def unblock_group(cls, group_id: str) -> bool:
data: dict = cls._load_block_group_list()
if group_id not in data:
return False
-
+
try:
data.pop(group_id)
cls._save_block_group_list(data)
@@ -162,7 +156,7 @@ class Manege(Service):
data["enabled"] = is_enabled
ServiceTools().save_service(data, service)
return True
-
+
@staticmethod
def control_user_service(service: str, user_id: str, is_enabled: bool) -> bool:
"""
@@ -173,7 +167,7 @@ class Manege(Service):
except BaseException:
return False
temp_list: list = data.get("disable_user", list())
-
+
if is_enabled:
try:
temp_list.remove(user_id)
@@ -184,7 +178,7 @@ class Manege(Service):
data["disable_user"] = temp_list
ServiceTools().save_service(data, service)
return True
-
+
@staticmethod
def control_group_service(service: str, group_id: str, is_enabled: bool) -> bool:
"""
@@ -196,7 +190,7 @@ class Manege(Service):
except BaseException:
return False
temp_list: list = data.get("disable_group", list())
-
+
if is_enabled:
try:
temp_list.remove(group_id)
@@ -219,7 +213,7 @@ class Manege(Service):
data = json.loads(path.read_bytes())
return data
-
+
@staticmethod
def save_friend_apply_list(data: dict) -> None:
file_name = "friend_add.json"
@@ -230,7 +224,7 @@ class Manege(Service):
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data, indent=4))
-
+
@staticmethod
def load_invite_apply_list() -> dict:
file_name = "group_invite.json"
@@ -242,7 +236,7 @@ class Manege(Service):
data = json.loads(path.read_bytes())
return data
-
+
@staticmethod
def save_invite_apply_list(data: dict) -> None:
file_name = "group_invite.json"
@@ -260,22 +254,19 @@ class Manege(Service):
data = load_error(track_id)
except ReadFileError:
return "请检查ID是否正确..."
-
+
prompt = data.get("prompt", "ignore")
time = data.get("time", "ignore")
content = data.get("content", "ignore")
-
+
msg0 = TRACK_BACK_FORMAT.format(
- track_id=track_id,
- prompt=prompt,
- time=time,
- content=content
+ track_id=track_id, prompt=prompt, time=time, content=content
)
f_data = FormData()
f_data.add_field("poster", "ATRI running log")
f_data.add_field("syntax", "text")
f_data.add_field("expiration", "day")
f_data.add_field("content", msg0)
-
+
repo = f"详细请移步此处~\n{await UbuntuPaste(data).paste()}"
- return repo \ No newline at end of file
+ return repo
diff --git a/ATRI/plugins/repo.py b/ATRI/plugins/repo.py
index db68721..b49b869 100644
--- a/ATRI/plugins/repo.py
+++ b/ATRI/plugins/repo.py
@@ -21,13 +21,13 @@ REPO_FORMAT = """
class Repo(Service):
-
def __init__(self):
Service.__init__(self, "反馈", "向维护者发送消息")
-
+
repo = Repo().on_command("来杯红茶", "向维护者发送消息", aliases={"反馈", "报告"})
+
@repo.args_parser # type: ignore
async def _get_repo(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -39,6 +39,7 @@ async def _get_repo(bot: Bot, event: MessageEvent, state: T_State):
else:
state["repo"] = msg
+
@repo.handle()
async def _ready_repo(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
@@ -46,26 +47,24 @@ async def _ready_repo(bot: Bot, event: MessageEvent, state: T_State):
await repo.finish(_repo_flmt_notice)
if not _repo_dlmt.check(user_id):
await repo.finish(_repo_dlmt_notice)
-
+
msg = str(event.message).strip()
if msg:
state["repo"] = msg
+
@repo.got("repo", "需要反馈的内容呢?~")
async def _deal_repo(bot: Bot, event: MessageEvent, state: T_State):
msg = state["repo"]
user_id = event.get_user_id()
- repo_0 = REPO_FORMAT.format(
- user=user_id,
- msg=msg
- )
-
+ repo_0 = REPO_FORMAT.format(user=user_id, msg=msg)
+
for superuser in BotSelfConfig.superusers:
try:
await bot.send_private_msg(user_id=superuser, message=repo_0)
except BaseException:
await repo.finish("发送失败了呢...")
-
+
_repo_flmt.start_cd(user_id)
_repo_dlmt.increase(user_id)
await repo.finish("吾辈的心愿已由咱转告维护者!")
diff --git a/ATRI/plugins/rich/__init__.py b/ATRI/plugins/rich/__init__.py
index 87a2b02..4c5b624 100644
--- a/ATRI/plugins/rich/__init__.py
+++ b/ATRI/plugins/rich/__init__.py
@@ -9,12 +9,13 @@ _rich_flmt = FreqLimiter(2)
bili_rich = Rich().on_message("小程序爪巴", block=False)
+
@bili_rich.handle()
async def _fk_bili(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
if not _rich_flmt.check(user_id):
return
-
+
msg = str(event.message)
try:
result, is_ok = await Rich().fk_bili(msg)
diff --git a/ATRI/plugins/rich/data_source.py b/ATRI/plugins/rich/data_source.py
index 3277a58..9e59bf5 100644
--- a/ATRI/plugins/rich/data_source.py
+++ b/ATRI/plugins/rich/data_source.py
@@ -24,10 +24,9 @@ __doc__ = """
class Rich(Service):
-
def __init__(self):
Service.__init__(self, "小程序处理", __doc__, rule=is_in_service("小程序处理"))
-
+
@staticmethod
def _bv_dec(x) -> str:
r = 0
@@ -35,7 +34,7 @@ class Rich(Service):
r += tr[x[s[i]]] * 58 ** i
result = "av" + str((r - add) ^ xor)
return result
-
+
@staticmethod
def _bv_enc(x) -> str:
x = (x ^ xor) + add
@@ -43,7 +42,7 @@ class Rich(Service):
for i in range(6):
r[s[i]] = table[x // 58 ** i % 58]
return "".join(r)
-
+
@classmethod
async def fk_bili(cls, text: str) -> tuple:
"""
@@ -52,7 +51,7 @@ class Rich(Service):
"""
msg = text.replace("\\", "")
bv = False
-
+
if "qqdocurl" not in msg:
if "av" in msg:
av = re.findall(r"(av\d+)", msg)
@@ -70,7 +69,7 @@ class Rich(Service):
if not bv_url:
return "Get value (bv url) failed!", False
bv_url = bv_url[3]
-
+
try:
res = await request.get(bv_url)
except RequestError:
@@ -79,7 +78,7 @@ class Rich(Service):
if not bv:
return "Get value (bv) failed!", False
av = cls._bv_dec(bv[0])
-
+
if not bv:
if "av" in msg:
av = re.findall(r"(av\d+)", msg)
@@ -88,7 +87,7 @@ class Rich(Service):
av = av[0].replace("av", "")
else:
return "Not found av", False
-
+
url = URL + av
try:
res = await request.get(url)
@@ -96,11 +95,10 @@ class Rich(Service):
return "Request failed!", False
res_data = await res.json()
data = res_data["data"]
-
+
result = (
f"{data['bvid']} INFO:\n"
f"Title: {data['title']}\n"
f"Link: {data['short_link']}"
)
return result, True
- \ No newline at end of file
diff --git a/ATRI/plugins/saucenao/__init__.py b/ATRI/plugins/saucenao/__init__.py
index 9e52d66..fddf0eb 100644
--- a/ATRI/plugins/saucenao/__init__.py
+++ b/ATRI/plugins/saucenao/__init__.py
@@ -16,6 +16,7 @@ _search_flmt_notice = choice(["慢...慢一..点❤", "冷静1下", "歇会歇�
saucenao = SaouceNao().on_command("以图搜图", "透过一张图搜索可能的来源")
+
@saucenao.args_parser # type: ignore
async def _get_img(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -27,16 +28,18 @@ async def _get_img(bot: Bot, event: MessageEvent, state: T_State):
else:
state["img"] = msg
+
@saucenao.handle()
async def _ready_search(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
if not _search_flmt.check(user_id):
await saucenao.finish(_search_flmt_notice)
-
+
msg = str(event.message).strip()
if msg:
state["img"] = msg
+
@saucenao.got("img", "图呢?")
async def _deal_search(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
@@ -44,7 +47,7 @@ async def _deal_search(bot: Bot, event: MessageEvent, state: T_State):
img = findall(r"url=(.*?)]", msg)
if not img:
await saucenao.reject("请发送图片而不是其他东西!!")
-
+
a = SaouceNao(SauceNAO.key)
result = f"> {MessageSegment.at(user_id)}" + await a.search(img[0])
_search_flmt.start_cd(user_id)
diff --git a/ATRI/plugins/saucenao/data_source.py b/ATRI/plugins/saucenao/data_source.py
index d948f91..6e72c98 100644
--- a/ATRI/plugins/saucenao/data_source.py
+++ b/ATRI/plugins/saucenao/data_source.py
@@ -16,8 +16,15 @@ __doc__ = """
class SaouceNao(Service):
-
- def __init__(self, api_key: str = None, output_type=2, testmode=1, dbmaski=32768, db=5, numres=5):
+ def __init__(
+ self,
+ api_key: str = None,
+ output_type=2,
+ testmode=1,
+ dbmaski=32768,
+ db=5,
+ numres=5,
+ ):
Service.__init__(self, "以图搜图", __doc__, rule=is_in_service("以图搜图"))
params = dict()
@@ -28,31 +35,31 @@ class SaouceNao(Service):
params["db"] = db
params["numres"] = numres
self.params = params
-
+
async def _request(self, url: str):
self.params["url"] = url
-
+
try:
res = await request.post(URL, params=self.params)
except RequestError:
raise RequestError("Request failed!")
data = await res.json()
return data
-
+
async def search(self, url: str) -> str:
data = await self._request(url)
res = data["results"]
-
+
result = list()
for i in range(len(res)):
data = res[i]
-
+
_result = dict()
_result["similarity"] = data["header"]["similarity"]
_result["index_name"] = data["header"]["index_name"]
_result["url"] = choice(data["data"].get("ext_urls", ["None"]))
result.append(_result)
-
+
msg0 = str()
for i in result:
msg0 += (
@@ -61,7 +68,7 @@ class SaouceNao(Service):
f"Name: {i['index_name']}\n"
f"URL: {i['url'].replace('https://', '')}"
)
-
+
if len(res) <= 3:
return msg0
else:
diff --git a/ATRI/plugins/setu/__init__.py b/ATRI/plugins/setu/__init__.py
index 7eb2c61..d67d75b 100644
--- a/ATRI/plugins/setu/__init__.py
+++ b/ATRI/plugins/setu/__init__.py
@@ -12,7 +12,10 @@ _setu_flmt = FreqLimiter(120)
_setu_dlmt = DailyLimiter(5)
-random_setu = Setu().on_command("来张涩图", "来张随机涩图,冷却2分钟,每天限5张", aliases={"涩图来", "来点涩图", "来份涩图"})
+random_setu = Setu().on_command(
+ "来张涩图", "来张随机涩图,冷却2分钟,每天限5张", aliases={"涩图来", "来点涩图", "来份涩图"}
+)
+
@random_setu.handle()
async def _random_setu(bot: Bot, event: MessageEvent):
@@ -21,12 +24,9 @@ async def _random_setu(bot: Bot, event: MessageEvent):
await random_setu.finish()
if not _setu_dlmt.check(user_id):
await random_setu.finish()
-
+
setu, title, p_id = await Setu().random_setu()
- repo = (
- f"Title: {title}\n"
- f"Pid: {p_id}"
- )
+ repo = f"Title: {title}\n" f"Pid: {p_id}"
await bot.send(event, repo)
msg_1 = await bot.send(event, Message(setu))
event_id = msg_1["message_id"]
@@ -38,6 +38,7 @@ async def _random_setu(bot: Bot, event: MessageEvent):
tag_setu = Setu().on_regex(r"来[张点丶份](.*?)的[涩色🐍]图", "根据提供的tag查找涩图")
+
@tag_setu.handle()
async def _tag_setu(bot: Bot, event: MessageEvent):
user_id = event.get_user_id()
@@ -45,18 +46,15 @@ async def _tag_setu(bot: Bot, event: MessageEvent):
await random_setu.finish()
if not _setu_dlmt.check(user_id):
await random_setu.finish()
-
+
msg = str(event.message).strip()
pattern = r"来[张点丶份](.*?)的[涩色🐍]图"
tag = re.findall(pattern, msg)[0]
setu, title, p_id, is_ok = await Setu().tag_setu(tag)
if not is_ok:
await tag_setu.finish(f"没有 {tag} 的涩图呢...")
- repo_0 = (
- f"Title: {title}\n"
- f"Pid: {p_id}"
- )
-
+ repo_0 = f"Title: {title}\n" f"Pid: {p_id}"
+
await bot.send(event, repo_0)
msg_1 = await bot.send(event, Message(setu))
event_id = msg_1["message_id"]
@@ -77,6 +75,6 @@ async def _scheduler_setu(bot):
message_id = msg_0["message_id"]
await asyncio.sleep(60)
await bot.delete_msg(message_id=message_id)
-
+
except BaseException:
pass
diff --git a/ATRI/plugins/setu/data_source.py b/ATRI/plugins/setu/data_source.py
index 4070fd5..ba714b2 100644
--- a/ATRI/plugins/setu/data_source.py
+++ b/ATRI/plugins/setu/data_source.py
@@ -15,10 +15,9 @@ SCHEDULER_FORMAT = """
class Setu(Service):
-
def __init__(self):
Service.__init__(self, "涩图", "hso!", rule=is_in_service("涩图"))
-
+
@staticmethod
async def random_setu() -> tuple:
"""
@@ -27,17 +26,14 @@ class Setu(Service):
res = await request.get(LOLICON_URL)
data: dict = await res.json()
temp_data: dict = data.get("data", list())[0]
-
- title = temp_data.get("title", "木陰のねこ")
+
+ title = temp_data.get("title", "木陰のねこ")
p_id = temp_data.get("pid", 88124144)
ext = temp_data.get("ext", "jpg")
- url = SETU_TEMP_FORMAT.format(
- p_id=p_id,
- ext=ext
- )
+ url = SETU_TEMP_FORMAT.format(p_id=p_id, ext=ext)
setu = MessageSegment.image(url)
return setu, title, p_id
-
+
@staticmethod
async def tag_setu(tag: str) -> tuple:
"""
@@ -46,22 +42,19 @@ class Setu(Service):
url = LOLICON_URL + f"?tag={tag}"
res = await request.get(url)
data: dict = await res.json()
-
+
temp_data: dict = data.get("data", list())[0]
if not temp_data:
is_ok = False
is_ok = True
-
- title = temp_data.get("title", "木陰のねこ")
+
+ title = temp_data.get("title", "木陰のねこ")
p_id = temp_data.get("pid", 88124144)
ext = temp_data.get("ext", "jpg")
- url = SETU_TEMP_FORMAT.format(
- p_id=p_id,
- ext=ext
- )
+ url = SETU_TEMP_FORMAT.format(p_id=p_id, ext=ext)
setu = MessageSegment.image(url)
return setu, title, p_id, is_ok
-
+
@staticmethod
async def scheduler() -> str:
"""
@@ -73,18 +66,12 @@ class Setu(Service):
res = await request.get(LOLICON_URL)
data: dict = await res.json()
temp_data: dict = data.get("data", list())[0]
-
+
p_id = temp_data.get("pid", 88124144)
tag = choice(temp_data.get("tags", ["女孩子"]))
ext = temp_data.get("ext", "jpg")
-
- url = SETU_TEMP_FORMAT.format(
- p_id=p_id,
- ext=ext
- )
+
+ url = SETU_TEMP_FORMAT.format(p_id=p_id, ext=ext)
setu = MessageSegment.image(url)
- repo = SCHEDULER_FORMAT.format(
- tag=tag,
- setu=setu
- )
+ repo = SCHEDULER_FORMAT.format(tag=tag, setu=setu)
return repo
diff --git a/ATRI/plugins/status/__init__.py b/ATRI/plugins/status/__init__.py
index 8955cb1..888a0a7 100644
--- a/ATRI/plugins/status/__init__.py
+++ b/ATRI/plugins/status/__init__.py
@@ -6,6 +6,7 @@ from .data_source import IsSurvive
ping = IsSurvive().on_command("/ping", "检测bot简单信息处理速度")
+
@ping.handle()
async def _ping(bot: Bot, event: MessageEvent):
await ping.finish(IsSurvive.ping())
@@ -13,6 +14,7 @@ async def _ping(bot: Bot, event: MessageEvent):
status = IsSurvive().on_command("/status", "查看运行资源占用")
+
@status.handle()
async def _status(bot: Bot, event: MessageEvent):
msg, _ = IsSurvive.get_status()
diff --git a/ATRI/plugins/status/data_source.py b/ATRI/plugins/status/data_source.py
index c353313..189f568 100644
--- a/ATRI/plugins/status/data_source.py
+++ b/ATRI/plugins/status/data_source.py
@@ -14,14 +14,13 @@ __doc__ = """
class IsSurvive(Service):
-
def __init__(self):
Service.__init__(self, "状态", __doc__, rule=is_in_service("状态"))
@staticmethod
def ping() -> str:
return "I'm fine."
-
+
@staticmethod
def get_status():
log.info("开始检查资源消耗...")
@@ -31,7 +30,7 @@ class IsSurvive(Service):
disk = psutil.disk_usage("/").percent
inteSENT = psutil.net_io_counters().bytes_sent / 1000000 # type: ignore
inteRECV = psutil.net_io_counters().bytes_recv / 1000000 # type: ignore
-
+
now = time.time()
boot = psutil.boot_time()
up_time = str(
@@ -40,7 +39,7 @@ class IsSurvive(Service):
)
except GetStatusError:
raise GetStatusError("Failed to get status.")
-
+
msg = "アトリは、高性能ですから!"
if cpu > 90: # type: ignore
msg = "咱感觉有些头晕..."
@@ -57,7 +56,7 @@ class IsSurvive(Service):
else:
log.info("资源占用正常")
is_ok = True
-
+
msg0 = (
"Self status:\n"
f"* CPU: {cpu}%\n"
@@ -67,5 +66,5 @@ class IsSurvive(Service):
f"* netRECV: {inteRECV}MB\n"
f"* Runtime: {up_time}\n"
) + msg
-
+
return msg0, is_ok
diff --git a/ATRI/plugins/util/__init__.py b/ATRI/plugins/util/__init__.py
index 1e31bff..541ca1b 100644
--- a/ATRI/plugins/util/__init__.py
+++ b/ATRI/plugins/util/__init__.py
@@ -10,6 +10,7 @@ from .data_source import Encrypt, Utils, Yinglish
roll = Utils().on_command("/roll", "骰子~用法:1d10 或 2d10+2d10+more")
+
@roll.args_parser # type: ignore
async def _get_roll(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -21,26 +22,29 @@ async def _get_roll(bot: Bot, event: MessageEvent, state: T_State):
else:
state["roll"] = msg
+
@roll.handle()
async def _ready_roll(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["roll"] = msg
+
@roll.got("roll", "参数呢?!格式:1d10 或 2d10+2d10+more")
async def _deal_roll(bot: Bot, event: MessageEvent, state: T_State):
text = state["roll"]
match = re.match(r"^([\dd+\s]+?)$", text)
-
+
if not match:
await roll.finish("阿——!参数不对!格式:1d10 或 2d10+2d10+more")
-
+
msg = Utils().roll_dice(text)
await roll.finish(msg)
encrypt_en = Utils().on_command("加密", "我们之前的秘密❤")
+
@encrypt_en.args_parser # type: ignore
async def _get_encr_en_text(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -52,12 +56,14 @@ async def _get_encr_en_text(bot: Bot, event: MessageEvent, state: T_State):
else:
state["encr_en_text"] = msg
+
@encrypt_en.handle()
async def _ready_en(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["encr_en_text"] = msg
+
@encrypt_en.got("encr_en_text", "内容呢?!")
async def _deal_en(bot: Bot, event: MessageEvent, state: T_State):
text = state["encr_en_text"]
@@ -71,6 +77,7 @@ async def _deal_en(bot: Bot, event: MessageEvent, state: T_State):
encrypt_de = Utils().on_command("解密", "解开我们的秘密❤")
+
@encrypt_de.args_parser # type: ignore
async def _get_encr_de_text(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -82,12 +89,14 @@ async def _get_encr_de_text(bot: Bot, event: MessageEvent, state: T_State):
else:
state["encr_de_text"] = msg
+
@encrypt_de.handle()
async def _ready_de(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
if msg:
state["encr_de_text"] = msg
+
@encrypt_de.got("encr_de_text", "内容呢?!")
async def _deal_de(bot: Bot, event: MessageEvent, state: T_State):
text = state["encr_de_text"]
@@ -101,6 +110,7 @@ sepi = Utils().on_command("涩批一下", "将正常的句子涩一涩~")
_sepi_flmt = FreqLimiter(3)
_sepi_flmt_notice = ["涩批爬", "✌🥵✌"]
+
@sepi.args_parser # type: ignore
async def _get_sepi(bot: Bot, event: MessageEvent, state: T_State):
msg = str(event.message).strip()
@@ -112,23 +122,25 @@ async def _get_sepi(bot: Bot, event: MessageEvent, state: T_State):
else:
state["sepi_text"] = msg
+
@sepi.handle()
async def _ready_sepi(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
if not _sepi_flmt.check(user_id):
await sepi.finish(choice(_sepi_flmt_notice))
-
+
msg = str(event.message).strip()
if msg:
state["sepi_text"] = msg
+
@sepi.got("sepi_text", "内容呢?!")
async def _deal_sepi(bot: Bot, event: MessageEvent, state: T_State):
user_id = event.get_user_id()
msg = state["sepi_text"]
if len(msg) < 4:
await sepi.finish("这么短?涩不起来!")
-
+
result = Yinglish.deal(msg, random())
_sepi_flmt.start_cd(user_id)
await sepi.finish(result)
diff --git a/ATRI/plugins/util/data_source.py b/ATRI/plugins/util/data_source.py
index a6afdf3..7b36ebe 100644
--- a/ATRI/plugins/util/data_source.py
+++ b/ATRI/plugins/util/data_source.py
@@ -14,10 +14,9 @@ __doc__ = """
class Utils(Service):
-
def __init__(self):
Service.__init__(self, "小工具", __doc__, rule=is_in_service("小工具"))
-
+
@staticmethod
def roll_dice(par: str) -> str:
result = 0
@@ -49,13 +48,14 @@ class Utils(Service):
result = f"{par}=({proc})={result}"
return result
-
+
+
class Encrypt(Utils):
"""
某nb改的(逃
总之就是非常nb
"""
-
+
cr = "ĀāĂ㥹ÀÁÂÃÄÅ"
cc = "ŢţŤťŦŧṪṫṬṭṮṯṰṱ"
cn = "ŔŕŘřṘṙŖŗȐȑȒȓṚṛṜṝṞṟɌɍⱤɽᵲᶉɼɾᵳʀRr"
@@ -186,9 +186,9 @@ class Encrypt(Utils):
return self._decodeBytes(s).decode(encoding)
except UnicodeDecodeError:
raise ValueError("Decoding failed")
-
+
+
class Yinglish(Utils):
-
@staticmethod
def _to_ying(x, y, ying) -> str:
if random() > ying:
diff --git a/ATRI/rule.py b/ATRI/rule.py
index 3d75f84..6f90be4 100644
--- a/ATRI/rule.py
+++ b/ATRI/rule.py
@@ -18,7 +18,7 @@ def is_in_service(service: str) -> Rule:
return result
else:
return True
-
+
return Rule(_is_in_service)
diff --git a/ATRI/service.py b/ATRI/service.py
index 4798fd5..378f2ca 100644
--- a/ATRI/service.py
+++ b/ATRI/service.py
@@ -58,17 +58,19 @@ class Service:
"disable_group": []
}
"""
-
- def __init__(self,
- service: str,
- docs: str = None,
- only_admin: bool = False,
- rule: Optional[Union[Rule, T_RuleChecker]] = None,
- permission: Optional[Permission] = None,
- handlers: Optional[List[T_Handler]] = None,
- temp: bool = False,
- priority: int = 1,
- state: Optional[T_State] = None):
+
+ def __init__(
+ self,
+ service: str,
+ docs: str = None,
+ only_admin: bool = False,
+ rule: Optional[Union[Rule, T_RuleChecker]] = None,
+ permission: Optional[Permission] = None,
+ handlers: Optional[List[T_Handler]] = None,
+ temp: bool = False,
+ priority: int = 1,
+ state: Optional[T_State] = None,
+ ):
self.service = service
self.docs = docs
self.only_admin = only_admin
@@ -84,7 +86,7 @@ class Service:
service = self.service
if not docs:
docs = self.docs or str()
-
+
path = SERVICES_DIR / f"{service}.json"
data = ServiceInfo(
service=service,
@@ -93,33 +95,33 @@ class Service:
enabled=True,
only_admin=self.only_admin,
disable_user=list(),
- disable_group=list()
+ disable_group=list(),
)
try:
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(data.dict(), indent=4))
except WriteError:
raise WriteError("Write service info failed!")
-
+
def save_service(self, service_data: dict, service: str = None) -> None:
if not service:
service = self.service
-
+
path = SERVICES_DIR / f"{service}.json"
if not path.is_file():
self._generate_service_config()
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(service_data, indent=4))
-
+
def load_service(self, service: str = None) -> dict:
if not service:
service = self.service
-
+
path = SERVICES_DIR / f"{service}.json"
if not path.is_file():
self._generate_service_config()
-
+
try:
data = json.loads(path.read_bytes())
except ReadFileError:
@@ -128,29 +130,31 @@ class Service:
self._generate_service_config()
data = json.loads(path.read_bytes())
return data
-
+
def _save_cmds(self, cmds: dict) -> None:
data = self.load_service(self.service)
temp_data: dict = data["cmd_list"]
temp_data.update(cmds)
self.save_service(data)
-
+
def _load_cmds(self) -> dict:
path = SERVICES_DIR / f"{self.service}.json"
if not path.is_file():
self._generate_service_config()
-
+
data = json.loads(path.read_bytes())
return data["cmd_list"]
- def on_message(self,
- docs: str = None,
- rule: Optional[Union[Rule, T_RuleChecker]] = None,
- permission: Optional[Permission] = None,
- handlers: Optional[List[T_Handler]] = None,
- block: bool = True,
- priority: int = None,
- state: Optional[T_State] = None) -> Type[Matcher]:
+ def on_message(
+ self,
+ docs: str = None,
+ rule: Optional[Union[Rule, T_RuleChecker]] = None,
+ permission: Optional[Permission] = None,
+ handlers: Optional[List[T_Handler]] = None,
+ block: bool = True,
+ priority: int = None,
+ state: Optional[T_State] = None,
+ ) -> Type[Matcher]:
if not rule:
rule = self.rule
if not permission:
@@ -161,7 +165,7 @@ class Service:
priority = self.priority
if not state:
state = self.state
-
+
if docs:
a = 0
cmd_list = self._load_cmds()
@@ -171,14 +175,10 @@ class Service:
break
else:
a += 1
-
- cmd_list[_type] = CommandInfo(
- type=_type,
- docs=docs,
- aliases=list()
- ).dict()
+
+ cmd_list[_type] = CommandInfo(type=_type, docs=docs, aliases=list()).dict()
self._save_cmds(cmd_list)
-
+
matcher = Matcher.new(
"message",
Rule() & rule,
@@ -200,14 +200,10 @@ class Service:
break
else:
a += 1
-
- cmd_list[_type] = CommandInfo(
- type=_type,
- docs=docs,
- aliases=list()
- ).dict()
+
+ cmd_list[_type] = CommandInfo(type=_type, docs=docs, aliases=list()).dict()
self._save_cmds(cmd_list)
-
+
matcher = Matcher.new(
"notice",
Rule() & self.rule,
@@ -229,14 +225,10 @@ class Service:
break
else:
a += 1
-
- cmd_list[_type] =CommandInfo(
- type=_type,
- docs=docs,
- aliases=list()
- ).dict()
+
+ cmd_list[_type] = CommandInfo(type=_type, docs=docs, aliases=list()).dict()
self._save_cmds(cmd_list)
-
+
matcher = Matcher.new(
"request",
Rule() & self.rule,
@@ -263,14 +255,10 @@ class Service:
rule = self.rule
if not aliases:
aliases = set()
-
- cmd_list[cmd] = CommandInfo(
- type=_type,
- docs=docs,
- aliases=list(aliases)
- ).dict()
+
+ cmd_list[cmd] = CommandInfo(type=_type, docs=docs, aliases=list(aliases)).dict()
self._save_cmds(cmd_list)
-
+
async def _strip_cmd(bot: "Bot", event: "Event", state: T_State):
message = event.get_message()
segment = message.pop(0)
@@ -284,7 +272,9 @@ class Service:
handlers.insert(0, _strip_cmd)
commands = set([cmd]) | (aliases or set())
- return self.on_message(rule=command(*commands) & rule, handlers=handlers, **kwargs)
+ return self.on_message(
+ rule=command(*commands) & rule, handlers=handlers, **kwargs
+ )
def on_keyword(
self,
@@ -295,7 +285,7 @@ class Service:
) -> Type[Matcher]:
if not rule:
rule = self.rule
-
+
a = 0
cmd_list = self._load_cmds()
while True:
@@ -304,14 +294,10 @@ class Service:
break
else:
a += 1
-
- cmd_list[_type] = CommandInfo(
- type=_type,
- docs=docs,
- aliases=list()
- ).dict()
+
+ cmd_list[_type] = CommandInfo(type=_type, docs=docs, aliases=list()).dict()
self._save_cmds(cmd_list)
-
+
return self.on_message(rule=keyword(*keywords) & rule, **kwargs)
def on_regex(
@@ -325,20 +311,15 @@ class Service:
_type = "regex"
if not rule:
rule = self.rule
-
+
cmd_list = self._load_cmds()
- cmd_list[pattern] = CommandInfo(
- type=_type,
- docs=docs,
- aliases=list()
- ).dict()
+ cmd_list[pattern] = CommandInfo(type=_type, docs=docs, aliases=list()).dict()
self._save_cmds(cmd_list)
-
+
return self.on_message(rule=regex(pattern, flags) & rule, **kwargs)
class ServiceTools(object):
-
@staticmethod
def save_service(service_data: dict, service: str) -> None:
path = SERVICES_DIR / f"{service}.json"
@@ -348,10 +329,10 @@ class ServiceTools(object):
"Please delete all file in data/service/services.\n"
"Next reboot bot."
)
-
+
with open(path, "w", encoding="utf-8") as w:
w.write(json.dumps(service_data, indent=4))
-
+
@staticmethod
def load_service(service: str) -> dict:
path = SERVICES_DIR / f"{service}.json"
@@ -361,7 +342,7 @@ class ServiceTools(object):
"Please delete all file in data/service/services.\n"
"Next reboot bot."
)
-
+
with open(path, "r", encoding="utf-8") as r:
data = json.loads(r.read())
return data
@@ -369,11 +350,11 @@ class ServiceTools(object):
@classmethod
def auth_service(cls, service, user_id: str = None, group_id: str = None) -> bool:
data = cls.load_service(service)
-
+
auth_global = data.get("enabled", True)
auth_user = data.get("disable_user", list())
auth_group = data.get("disable_group", list())
-
+
if user_id:
if user_id in auth_user:
return False
@@ -383,7 +364,7 @@ class ServiceTools(object):
return False
else:
return True
-
+
if not auth_global:
return False
else:
diff --git a/ATRI/utils/__init__.py b/ATRI/utils/__init__.py
index 35f5aad..c1c42e1 100644
--- a/ATRI/utils/__init__.py
+++ b/ATRI/utils/__init__.py
@@ -36,11 +36,11 @@ class ListDealer:
"""
对列表进行处理
"""
-
+
def __init__(self, lst: list, aim):
self.lst = lst
self.aim = aim
-
+
def count(self) -> int:
count = 0
for ele in self.lst:
@@ -58,12 +58,13 @@ class CoolqCodeChecker:
"""
检查所传回的cq码是否存在被注入可能
"""
- tenc_gchat_url: str = "gchat.qpic.cn"
+
+ tenc_gchat_url: str = "gchat.qpic.cn"
may_inject_keys: list = ["record", "video", "music", "xml", "json"]
-
+
def __init__(self, text: str):
self.text = text
-
+
@property
def check(self) -> bool:
_type = re.findall(r"CQ:(.*?),", self.text)
@@ -87,18 +88,18 @@ class FileDealer:
"""
打开文件
"""
-
+
def __init__(self, path: Path, encoding: str = "utf-8"):
self.path = path
self.encoding = encoding
-
+
async def write(self, path: Path, content):
try:
async with aiofiles.open(path, "w", encoding=self.encoding) as target:
await target.write(content)
except Exception:
raise Exception(f"Writing file({path}) failed!")
-
+
async def _reader(self) -> AsyncTextIOWrapper:
try:
tar = await aiofiles.open(self.path, "r", encoding=self.encoding)
@@ -109,15 +110,15 @@ class FileDealer:
async def read(self):
tar = await self._reader()
return tar.read()
-
+
async def readline(self):
tar = await self._reader()
return tar.readline()
-
+
async def readlines(self):
tar = await self._reader()
return tar.readlines()
-
+
async def readtable(self):
tar = await self._reader()
return tar.readable()
@@ -127,18 +128,18 @@ class ImageDealer:
"""
对图片进行压缩处理
"""
-
+
def __init__(self, out_path, kb: int = 300, quality: int = 85, k: float = 0.9):
self.out_path = out_path
self.kb = kb
self.quality = quality
self.k = k
-
+
def deal(self) -> str:
o_size = os.path.getsize(self.out_path) // 1024
if o_size <= self.kb:
return self.out_path
-
+
ImageFile.LOAD_TRUNCATED_IMAGES = True # type: ignore
while o_size > self.kb:
img = Image.open(self.out_path)
@@ -156,13 +157,13 @@ class Translate:
"""
繁 <=> 中
"""
-
+
SIMPLE = "万与丑专业丛东丝丢两严丧个丬丰临为丽举么义乌乐乔习乡书买乱争于亏云亘亚产亩亲亵亸亿仅从仑仓仪们价众优伙会伛伞伟传伤伥伦伧伪伫体余佣佥侠侣侥侦侧侨侩侪侬俣俦俨俩俪俭债倾偬偻偾偿傥傧储傩儿兑兖党兰关兴兹养兽冁内冈册写军农冢冯冲决况冻净凄凉凌减凑凛几凤凫凭凯击凼凿刍划刘则刚创删别刬刭刽刿剀剂剐剑剥剧劝办务劢动励劲劳势勋勐勚匀匦匮区医华协单卖卢卤卧卫却卺厂厅历厉压厌厍厕厢厣厦厨厩厮县参叆叇双发变叙叠叶号叹叽吁后吓吕吗吣吨听启吴呒呓呕呖呗员呙呛呜咏咔咙咛咝咤咴咸哌响哑哒哓哔哕哗哙哜哝哟唛唝唠唡唢唣唤唿啧啬啭啮啰啴啸喷喽喾嗫呵嗳嘘嘤嘱噜噼嚣嚯团园囱围囵国图圆圣圹场坂坏块坚坛坜坝坞坟坠垄垅垆垒垦垧垩垫垭垯垱垲垴埘埙埚埝埯堑堕塆墙壮声壳壶壸处备复够头夸夹夺奁奂奋奖奥妆妇妈妩妪妫姗姜娄娅娆娇娈娱娲娴婳婴婵婶媪嫒嫔嫱嬷孙学孪宁宝实宠审宪宫宽宾寝对寻导寿将尔尘尧尴尸尽层屃屉届属屡屦屿岁岂岖岗岘岙岚岛岭岳岽岿峃峄峡峣峤峥峦崂崃崄崭嵘嵚嵛嵝嵴巅巩巯币帅师帏帐帘帜带帧帮帱帻帼幂幞干并广庄庆庐庑库应庙庞废庼廪开异弃张弥弪弯弹强归当录彟彦彻径徕御忆忏忧忾怀态怂怃怄怅怆怜总怼怿恋恳恶恸恹恺恻恼恽悦悫悬悭悯惊惧惨惩惫惬惭惮惯愍愠愤愦愿慑慭憷懑懒懔戆戋戏戗战戬户扎扑扦执扩扪扫扬扰抚抛抟抠抡抢护报担拟拢拣拥拦拧拨择挂挚挛挜挝挞挟挠挡挢挣挤挥挦捞损捡换捣据捻掳掴掷掸掺掼揸揽揿搀搁搂搅携摄摅摆摇摈摊撄撑撵撷撸撺擞攒敌敛数斋斓斗斩断无旧时旷旸昙昼昽显晋晒晓晔晕晖暂暧札术朴机杀杂权条来杨杩杰极构枞枢枣枥枧枨枪枫枭柜柠柽栀栅标栈栉栊栋栌栎栏树栖样栾桊桠桡桢档桤桥桦桧桨桩梦梼梾检棂椁椟椠椤椭楼榄榇榈榉槚槛槟槠横樯樱橥橱橹橼檐檩欢欤欧歼殁殇残殒殓殚殡殴毁毂毕毙毡毵氇气氢氩氲汇汉污汤汹沓沟没沣沤沥沦沧沨沩沪沵泞泪泶泷泸泺泻泼泽泾洁洒洼浃浅浆浇浈浉浊测浍济浏浐浑浒浓浔浕涂涌涛涝涞涟涠涡涢涣涤润涧涨涩淀渊渌渍渎渐渑渔渖渗温游湾湿溃溅溆溇滗滚滞滟滠满滢滤滥滦滨滩滪漤潆潇潋潍潜潴澜濑濒灏灭灯灵灾灿炀炉炖炜炝点炼炽烁烂烃烛烟烦烧烨烩烫烬热焕焖焘煅煳熘爱爷牍牦牵牺犊犟状犷犸犹狈狍狝狞独狭狮狯狰狱狲猃猎猕猡猪猫猬献獭玑玙玚玛玮环现玱玺珉珏珐珑珰珲琎琏琐琼瑶瑷璇璎瓒瓮瓯电画畅畲畴疖疗疟疠疡疬疮疯疱疴痈痉痒痖痨痪痫痴瘅瘆瘗瘘瘪瘫瘾瘿癞癣癫癯皑皱皲盏盐监盖盗盘眍眦眬着睁睐睑瞒瞩矫矶矾矿砀码砖砗砚砜砺砻砾础硁硅硕硖硗硙硚确硷碍碛碜碱碹磙礼祎祢祯祷祸禀禄禅离秃秆种积称秽秾稆税稣稳穑穷窃窍窑窜窝窥窦窭竖竞笃笋笔笕笺笼笾筑筚筛筜筝筹签简箓箦箧箨箩箪箫篑篓篮篱簖籁籴类籼粜粝粤粪粮糁糇紧絷纟纠纡红纣纤纥约级纨纩纪纫纬纭纮纯纰纱纲纳纴纵纶纷纸纹纺纻纼纽纾线绀绁绂练组绅细织终绉绊绋绌绍绎经绐绑绒结绔绕绖绗绘给绚绛络绝绞统绠绡绢绣绤绥绦继绨绩绪绫绬续绮绯绰绱绲绳维绵绶绷绸绹绺绻综绽绾绿缀缁缂缃缄缅缆缇缈缉缊缋缌缍缎缏缐缑缒缓缔缕编缗缘缙缚缛缜缝缞缟缠缡缢缣缤缥缦缧缨缩缪缫缬缭缮缯缰缱缲缳缴缵罂网罗罚罢罴羁羟羡翘翙翚耢耧耸耻聂聋职聍联聩聪肃肠肤肷肾肿胀胁胆胜胧胨胪胫胶脉脍脏脐脑脓脔脚脱脶脸腊腌腘腭腻腼腽腾膑臜舆舣舰舱舻艰艳艹艺节芈芗芜芦苁苇苈苋苌苍苎苏苘苹茎茏茑茔茕茧荆荐荙荚荛荜荞荟荠荡荣荤荥荦荧荨荩荪荫荬荭荮药莅莜莱莲莳莴莶获莸莹莺莼萚萝萤营萦萧萨葱蒇蒉蒋蒌蓝蓟蓠蓣蓥蓦蔷蔹蔺蔼蕲蕴薮藁藓虏虑虚虫虬虮虽虾虿蚀蚁蚂蚕蚝蚬蛊蛎蛏蛮蛰蛱蛲蛳蛴蜕蜗蜡蝇蝈蝉蝎蝼蝾螀螨蟏衅衔补衬衮袄袅袆袜袭袯装裆裈裢裣裤裥褛褴襁襕见观觃规觅视觇览觉觊觋觌觍觎觏觐觑觞触觯詟誉誊讠计订讣认讥讦讧讨让讪讫训议讯记讱讲讳讴讵讶讷许讹论讻讼讽设访诀证诂诃评诅识诇诈诉诊诋诌词诎诏诐译诒诓诔试诖诗诘诙诚诛诜话诞诟诠诡询诣诤该详诧诨诩诪诫诬语诮误诰诱诲诳说诵诶请诸诹诺读诼诽课诿谀谁谂调谄谅谆谇谈谊谋谌谍谎谏谐谑谒谓谔谕谖谗谘谙谚谛谜谝谞谟谠谡谢谣谤谥谦谧谨谩谪谫谬谭谮谯谰谱谲谳谴谵谶谷豮贝贞负贠贡财责贤败账货质贩贪贫贬购贮贯贰贱贲贳贴贵贶贷贸费贺贻贼贽贾贿赀赁赂赃资赅赆赇赈赉赊赋赌赍赎赏赐赑赒赓赔赕赖赗赘赙赚赛赜赝赞赟赠赡赢赣赪赵赶趋趱趸跃跄跖跞践跶跷跸跹跻踊踌踪踬踯蹑蹒蹰蹿躏躜躯车轧轨轩轪轫转轭轮软轰轱轲轳轴轵轶轷轸轹轺轻轼载轾轿辀辁辂较辄辅辆辇辈辉辊辋辌辍辎辏辐辑辒输辔辕辖辗辘辙辚辞辩辫边辽达迁过迈运还这进远违连迟迩迳迹适选逊递逦逻遗遥邓邝邬邮邹邺邻郁郄郏郐郑郓郦郧郸酝酦酱酽酾酿释里鉅鉴銮錾钆钇针钉钊钋钌钍钎钏钐钑钒钓钔钕钖钗钘钙钚钛钝钞钟钠钡钢钣钤钥钦钧钨钩钪钫钬钭钮钯钰钱钲钳钴钵钶钷钸钹钺钻钼钽钾钿铀铁铂铃铄铅铆铈铉铊铋铍铎铏铐铑铒铕铗铘铙铚铛铜铝铞铟铠铡铢铣铤铥铦铧铨铪铫铬铭铮铯铰铱铲铳铴铵银铷铸铹铺铻铼铽链铿销锁锂锃锄锅锆锇锈锉锊锋锌锍锎锏锐锑锒锓锔锕锖锗错锚锜锞锟锠锡锢锣锤锥锦锨锩锫锬锭键锯锰锱锲锳锴锵锶锷锸锹锺锻锼锽锾锿镀镁镂镃镆镇镈镉镊镌镍镎镏镐镑镒镕镖镗镙镚镛镜镝镞镟镠镡镢镣镤镥镦镧镨镩镪镫镬镭镮镯镰镱镲镳镴镶长门闩闪闫闬闭问闯闰闱闲闳间闵闶闷闸闹闺闻闼闽闾闿阀阁阂阃阄阅阆阇阈阉阊阋阌阍阎阏阐阑阒阓阔阕阖阗阘阙阚阛队阳阴阵阶际陆陇陈陉陕陧陨险随隐隶隽难雏雠雳雾霁霉霭靓静靥鞑鞒鞯鞴韦韧韨韩韪韫韬韵页顶顷顸项顺须顼顽顾顿颀颁颂颃预颅领颇颈颉颊颋颌颍颎颏颐频颒颓颔颕颖颗题颙颚颛颜额颞颟颠颡颢颣颤颥颦颧风飏飐飑飒飓飔飕飖飗飘飙飚飞飨餍饤饥饦饧饨饩饪饫饬饭饮饯饰饱饲饳饴饵饶饷饸饹饺饻饼饽饾饿馀馁馂馃馄馅馆馇馈馉馊馋馌馍馎馏馐馑馒馓馔馕马驭驮驯驰驱驲驳驴驵驶驷驸驹驺驻驼驽驾驿骀骁骂骃骄骅骆骇骈骉骊骋验骍骎骏骐骑骒骓骔骕骖骗骘骙骚骛骜骝骞骟骠骡骢骣骤骥骦骧髅髋髌鬓魇魉鱼鱽鱾鱿鲀鲁鲂鲄鲅鲆鲇鲈鲉鲊鲋鲌鲍鲎鲏鲐鲑鲒鲓鲔鲕鲖鲗鲘鲙鲚鲛鲜鲝鲞鲟鲠鲡鲢鲣鲤鲥鲦鲧鲨鲩鲪鲫鲬鲭鲮鲯鲰鲱鲲鲳鲴鲵鲶鲷鲸鲹鲺鲻鲼鲽鲾鲿鳀鳁鳂鳃鳄鳅鳆鳇鳈鳉鳊鳋鳌鳍鳎鳏鳐鳑鳒鳓鳔鳕鳖鳗鳘鳙鳛鳜鳝鳞鳟鳠鳡鳢鳣鸟鸠鸡鸢鸣鸤鸥鸦鸧鸨鸩鸪鸫鸬鸭鸮鸯鸰鸱鸲鸳鸴鸵鸶鸷鸸鸹鸺鸻鸼鸽鸾鸿鹀鹁鹂鹃鹄鹅鹆鹇鹈鹉鹊鹋鹌鹍鹎鹏鹐鹑鹒鹓鹔鹕鹖鹗鹘鹚鹛鹜鹝鹞鹟鹠鹡鹢鹣鹤鹥鹦鹧鹨鹩鹪鹫鹬鹭鹯鹰鹱鹲鹳鹴鹾麦麸黄黉黡黩黪黾鼋鼌鼍鼗鼹齄齐齑齿龀龁龂龃龄龅龆龇龈龉龊龋龌龙龚龛龟志制咨只里系范松没尝尝闹面准钟别闲干尽脏拼"
TRADITION = "萬與醜專業叢東絲丟兩嚴喪個爿豐臨為麗舉麼義烏樂喬習鄉書買亂爭於虧雲亙亞產畝親褻嚲億僅從侖倉儀們價眾優夥會傴傘偉傳傷倀倫傖偽佇體餘傭僉俠侶僥偵側僑儈儕儂俁儔儼倆儷儉債傾傯僂僨償儻儐儲儺兒兌兗黨蘭關興茲養獸囅內岡冊寫軍農塚馮衝決況凍淨淒涼淩減湊凜幾鳳鳧憑凱擊氹鑿芻劃劉則剛創刪別剗剄劊劌剴劑剮劍剝劇勸辦務勱動勵勁勞勢勳猛勩勻匭匱區醫華協單賣盧鹵臥衛卻巹廠廳曆厲壓厭厙廁廂厴廈廚廄廝縣參靉靆雙發變敘疊葉號歎嘰籲後嚇呂嗎唚噸聽啟吳嘸囈嘔嚦唄員咼嗆嗚詠哢嚨嚀噝吒噅鹹呱響啞噠嘵嗶噦嘩噲嚌噥喲嘜嗊嘮啢嗩唕喚呼嘖嗇囀齧囉嘽嘯噴嘍嚳囁嗬噯噓嚶囑嚕劈囂謔團園囪圍圇國圖圓聖壙場阪壞塊堅壇壢壩塢墳墜壟壟壚壘墾坰堊墊埡墶壋塏堖塒塤堝墊垵塹墮壪牆壯聲殼壺壼處備復夠頭誇夾奪奩奐奮獎奧妝婦媽嫵嫗媯姍薑婁婭嬈嬌孌娛媧嫻嫿嬰嬋嬸媼嬡嬪嬙嬤孫學孿寧寶實寵審憲宮寬賓寢對尋導壽將爾塵堯尷屍盡層屭屜屆屬屢屨嶼歲豈嶇崗峴嶴嵐島嶺嶽崠巋嶨嶧峽嶢嶠崢巒嶗崍嶮嶄嶸嶔崳嶁脊巔鞏巰幣帥師幃帳簾幟帶幀幫幬幘幗冪襆幹並廣莊慶廬廡庫應廟龐廢廎廩開異棄張彌弳彎彈強歸當錄彠彥徹徑徠禦憶懺憂愾懷態慫憮慪悵愴憐總懟懌戀懇惡慟懨愷惻惱惲悅愨懸慳憫驚懼慘懲憊愜慚憚慣湣慍憤憒願懾憖怵懣懶懍戇戔戲戧戰戩戶紮撲扡執擴捫掃揚擾撫拋摶摳掄搶護報擔擬攏揀擁攔擰撥擇掛摯攣掗撾撻挾撓擋撟掙擠揮撏撈損撿換搗據撚擄摑擲撣摻摜摣攬撳攙擱摟攪攜攝攄擺搖擯攤攖撐攆擷擼攛擻攢敵斂數齋斕鬥斬斷無舊時曠暘曇晝曨顯晉曬曉曄暈暉暫曖劄術樸機殺雜權條來楊榪傑極構樅樞棗櫪梘棖槍楓梟櫃檸檉梔柵標棧櫛櫳棟櫨櫟欄樹棲樣欒棬椏橈楨檔榿橋樺檜槳樁夢檮棶檢欞槨櫝槧欏橢樓欖櫬櫚櫸檟檻檳櫧橫檣櫻櫫櫥櫓櫞簷檁歡歟歐殲歿殤殘殞殮殫殯毆毀轂畢斃氈毿氌氣氫氬氳彙漢汙湯洶遝溝沒灃漚瀝淪滄渢溈滬濔濘淚澩瀧瀘濼瀉潑澤涇潔灑窪浹淺漿澆湞溮濁測澮濟瀏滻渾滸濃潯濜塗湧濤澇淶漣潿渦溳渙滌潤澗漲澀澱淵淥漬瀆漸澠漁瀋滲溫遊灣濕潰濺漵漊潷滾滯灩灄滿瀅濾濫灤濱灘澦濫瀠瀟瀲濰潛瀦瀾瀨瀕灝滅燈靈災燦煬爐燉煒熗點煉熾爍爛烴燭煙煩燒燁燴燙燼熱煥燜燾煆糊溜愛爺牘犛牽犧犢強狀獷獁猶狽麅獮獰獨狹獅獪猙獄猻獫獵獼玀豬貓蝟獻獺璣璵瑒瑪瑋環現瑲璽瑉玨琺瓏璫琿璡璉瑣瓊瑤璦璿瓔瓚甕甌電畫暢佘疇癤療瘧癘瘍鬁瘡瘋皰屙癰痙癢瘂癆瘓癇癡癉瘮瘞瘺癟癱癮癭癩癬癲臒皚皺皸盞鹽監蓋盜盤瞘眥矓著睜睞瞼瞞矚矯磯礬礦碭碼磚硨硯碸礪礱礫礎硜矽碩硤磽磑礄確鹼礙磧磣堿镟滾禮禕禰禎禱禍稟祿禪離禿稈種積稱穢穠穭稅穌穩穡窮竊竅窯竄窩窺竇窶豎競篤筍筆筧箋籠籩築篳篩簹箏籌簽簡籙簀篋籜籮簞簫簣簍籃籬籪籟糴類秈糶糲粵糞糧糝餱緊縶糸糾紆紅紂纖紇約級紈纊紀紉緯紜紘純紕紗綱納紝縱綸紛紙紋紡紵紖紐紓線紺絏紱練組紳細織終縐絆紼絀紹繹經紿綁絨結絝繞絰絎繪給絢絳絡絕絞統綆綃絹繡綌綏絛繼綈績緒綾緓續綺緋綽緔緄繩維綿綬繃綢綯綹綣綜綻綰綠綴緇緙緗緘緬纜緹緲緝縕繢緦綞緞緶線緱縋緩締縷編緡緣縉縛縟縝縫縗縞纏縭縊縑繽縹縵縲纓縮繆繅纈繚繕繒韁繾繰繯繳纘罌網羅罰罷羆羈羥羨翹翽翬耮耬聳恥聶聾職聹聯聵聰肅腸膚膁腎腫脹脅膽勝朧腖臚脛膠脈膾髒臍腦膿臠腳脫腡臉臘醃膕齶膩靦膃騰臏臢輿艤艦艙艫艱豔艸藝節羋薌蕪蘆蓯葦藶莧萇蒼苧蘇檾蘋莖蘢蔦塋煢繭荊薦薘莢蕘蓽蕎薈薺蕩榮葷滎犖熒蕁藎蓀蔭蕒葒葤藥蒞蓧萊蓮蒔萵薟獲蕕瑩鶯蓴蘀蘿螢營縈蕭薩蔥蕆蕢蔣蔞藍薊蘺蕷鎣驀薔蘞藺藹蘄蘊藪槁蘚虜慮虛蟲虯蟣雖蝦蠆蝕蟻螞蠶蠔蜆蠱蠣蟶蠻蟄蛺蟯螄蠐蛻蝸蠟蠅蟈蟬蠍螻蠑螿蟎蠨釁銜補襯袞襖嫋褘襪襲襏裝襠褌褳襝褲襇褸襤繈襴見觀覎規覓視覘覽覺覬覡覿覥覦覯覲覷觴觸觶讋譽謄訁計訂訃認譏訐訌討讓訕訖訓議訊記訒講諱謳詎訝訥許訛論訩訟諷設訪訣證詁訶評詛識詗詐訴診詆謅詞詘詔詖譯詒誆誄試詿詩詰詼誠誅詵話誕詬詮詭詢詣諍該詳詫諢詡譸誡誣語誚誤誥誘誨誑說誦誒請諸諏諾讀諑誹課諉諛誰諗調諂諒諄誶談誼謀諶諜謊諫諧謔謁謂諤諭諼讒諮諳諺諦謎諞諝謨讜謖謝謠謗諡謙謐謹謾謫譾謬譚譖譙讕譜譎讞譴譫讖穀豶貝貞負貟貢財責賢敗賬貨質販貪貧貶購貯貫貳賤賁貰貼貴貺貸貿費賀貽賊贄賈賄貲賃賂贓資賅贐賕賑賚賒賦賭齎贖賞賜贔賙賡賠賧賴賵贅賻賺賽賾贗讚贇贈贍贏贛赬趙趕趨趲躉躍蹌蹠躒踐躂蹺蹕躚躋踴躊蹤躓躑躡蹣躕躥躪躦軀車軋軌軒軑軔轉軛輪軟轟軲軻轤軸軹軼軤軫轢軺輕軾載輊轎輈輇輅較輒輔輛輦輩輝輥輞輬輟輜輳輻輯轀輸轡轅轄輾轆轍轔辭辯辮邊遼達遷過邁運還這進遠違連遲邇逕跡適選遜遞邐邏遺遙鄧鄺鄔郵鄒鄴鄰鬱郤郟鄶鄭鄆酈鄖鄲醞醱醬釅釃釀釋裏钜鑒鑾鏨釓釔針釘釗釙釕釷釺釧釤鈒釩釣鍆釹鍚釵鈃鈣鈈鈦鈍鈔鍾鈉鋇鋼鈑鈐鑰欽鈞鎢鉤鈧鈁鈥鈄鈕鈀鈺錢鉦鉗鈷缽鈳鉕鈽鈸鉞鑽鉬鉭鉀鈿鈾鐵鉑鈴鑠鉛鉚鈰鉉鉈鉍鈹鐸鉶銬銠鉺銪鋏鋣鐃銍鐺銅鋁銱銦鎧鍘銖銑鋌銩銛鏵銓鉿銚鉻銘錚銫鉸銥鏟銃鐋銨銀銣鑄鐒鋪鋙錸鋱鏈鏗銷鎖鋰鋥鋤鍋鋯鋨鏽銼鋝鋒鋅鋶鐦鐧銳銻鋃鋟鋦錒錆鍺錯錨錡錁錕錩錫錮鑼錘錐錦鍁錈錇錟錠鍵鋸錳錙鍥鍈鍇鏘鍶鍔鍤鍬鍾鍛鎪鍠鍰鎄鍍鎂鏤鎡鏌鎮鎛鎘鑷鐫鎳鎿鎦鎬鎊鎰鎔鏢鏜鏍鏰鏞鏡鏑鏃鏇鏐鐔钁鐐鏷鑥鐓鑭鐠鑹鏹鐙鑊鐳鐶鐲鐮鐿鑔鑣鑞鑲長門閂閃閆閈閉問闖閏闈閑閎間閔閌悶閘鬧閨聞闥閩閭闓閥閣閡閫鬮閱閬闍閾閹閶鬩閿閽閻閼闡闌闃闠闊闋闔闐闒闕闞闤隊陽陰陣階際陸隴陳陘陝隉隕險隨隱隸雋難雛讎靂霧霽黴靄靚靜靨韃鞽韉韝韋韌韍韓韙韞韜韻頁頂頃頇項順須頊頑顧頓頎頒頌頏預顱領頗頸頡頰頲頜潁熲頦頤頻頮頹頷頴穎顆題顒顎顓顏額顳顢顛顙顥纇顫顬顰顴風颺颭颮颯颶颸颼颻飀飄飆飆飛饗饜飣饑飥餳飩餼飪飫飭飯飲餞飾飽飼飿飴餌饒餉餄餎餃餏餅餑餖餓餘餒餕餜餛餡館餷饋餶餿饞饁饃餺餾饈饉饅饊饌饢馬馭馱馴馳驅馹駁驢駔駛駟駙駒騶駐駝駑駕驛駘驍罵駰驕驊駱駭駢驫驪騁驗騂駸駿騏騎騍騅騌驌驂騙騭騤騷騖驁騮騫騸驃騾驄驏驟驥驦驤髏髖髕鬢魘魎魚魛魢魷魨魯魴魺鮁鮃鯰鱸鮋鮓鮒鮊鮑鱟鮍鮐鮭鮚鮳鮪鮞鮦鰂鮜鱠鱭鮫鮮鮺鯗鱘鯁鱺鰱鰹鯉鰣鰷鯀鯊鯇鮶鯽鯒鯖鯪鯕鯫鯡鯤鯧鯝鯢鯰鯛鯨鯵鯴鯔鱝鰈鰏鱨鯷鰮鰃鰓鱷鰍鰒鰉鰁鱂鯿鰠鼇鰭鰨鰥鰩鰟鰜鰳鰾鱈鱉鰻鰵鱅鰼鱖鱔鱗鱒鱯鱤鱧鱣鳥鳩雞鳶鳴鳲鷗鴉鶬鴇鴆鴣鶇鸕鴨鴞鴦鴒鴟鴝鴛鴬鴕鷥鷙鴯鴰鵂鴴鵃鴿鸞鴻鵐鵓鸝鵑鵠鵝鵒鷳鵜鵡鵲鶓鵪鶤鵯鵬鵮鶉鶊鵷鷫鶘鶡鶚鶻鶿鶥鶩鷊鷂鶲鶹鶺鷁鶼鶴鷖鸚鷓鷚鷯鷦鷲鷸鷺鸇鷹鸌鸏鸛鸘鹺麥麩黃黌黶黷黲黽黿鼂鼉鞀鼴齇齊齏齒齔齕齗齟齡齙齠齜齦齬齪齲齷龍龔龕龜誌製谘隻裡係範鬆冇嚐嘗鬨麵準鐘彆閒乾儘臟拚"
-
+
def __init__(self, text: str):
self.text = text
-
+
def to_tradition(self) -> str:
output_str_list = []
str_len = len(self.text)
@@ -176,7 +177,7 @@ class Translate:
output_str_list.append(self.text[i])
return "".join(output_str_list)
-
+
def to_simple(self) -> str:
output_str_list = []
str_len = len(self.text)
@@ -196,12 +197,12 @@ class UbuntuPaste:
"""
将信息粘贴至 ubuntu pastebin
"""
-
+
URL = "https://paste.ubuntu.com/"
-
+
def __init__(self, form_data):
self.form_data = form_data
-
+
async def paste(self) -> str:
try:
res = await request.post(self.URL, self.form_data)
@@ -209,6 +210,3 @@ class UbuntuPaste:
raise BaseException("Request failed!")
result = res.url
return result
-
-
-
diff --git a/ATRI/utils/limit.py b/ATRI/utils/limit.py
index 4b3caef..905d744 100644
--- a/ATRI/utils/limit.py
+++ b/ATRI/utils/limit.py
@@ -10,7 +10,7 @@ class LimitBucket:
"""
限制某功能运行中某段在一定速率下
"""
-
+
def __init__(self, capacity, fill_rate, is_lock: bool = False) -> None:
"""
:param capacity: 容量总数
@@ -22,7 +22,7 @@ class LimitBucket:
self._last_time = time()
self._is_lock = is_lock
self._lock = RLock()
-
+
def _get_cur_tokens(self):
if self._tokens < self._capacity:
now = time()
@@ -30,20 +30,20 @@ class LimitBucket:
self._tokens = min(self._capacity, self._tokens + delta)
self._last_time = now
return self._tokens
-
+
def get_cur_tokens(self):
if self._is_lock:
with self._lock:
return self._get_cur_tokens()
else:
return self._get_cur_tokens()
-
+
def _consume(self, tokens) -> bool:
if tokens <= self.get_cur_tokens():
self._tokens -= tokens
return True
return False
-
+
def consume(self, tokens):
if self._is_lock:
with self._lock:
@@ -56,12 +56,12 @@ class RateLimiting:
"""
限制该功能全体速率
"""
-
+
def __init__(self, max_calls, period=1.0):
if period <= 0:
- raise ValueError('Rate limiting period should be > 0')
+ raise ValueError("Rate limiting period should be > 0")
if max_calls <= 0:
- raise ValueError('Rate limiting number of calls should be > 0')
+ raise ValueError("Rate limiting number of calls should be > 0")
self.calls = deque()
@@ -73,6 +73,7 @@ class RateLimiting:
def wrapped(*args, **kwargs):
with self:
return func(*args, **kwargs)
+
return wrapped
def __enter__(self):
@@ -94,7 +95,7 @@ class FreqLimiter:
"""
Copy from: https://github.com/Ice-Cirno/HoshinoBot/blob/master/hoshino/util/__init__.py
"""
-
+
def __init__(self, default_cd_seconds):
self.next_time = defaultdict(float)
self.default_cd = default_cd_seconds
@@ -103,7 +104,9 @@ class FreqLimiter:
return bool(time.time() >= self.next_time[key])
def start_cd(self, key, cd_time=0):
- self.next_time[key] = time.time() + (cd_time if cd_time > 0 else self.default_cd)
+ self.next_time[key] = time.time() + (
+ cd_time if cd_time > 0 else self.default_cd
+ )
def left_time(self, key) -> float:
return self.next_time[key] - time.time()
@@ -113,8 +116,9 @@ class DailyLimiter:
"""
Copy from: https://github.com/Ice-Cirno/HoshinoBot/blob/master/hoshino/util/__init__.py
"""
- tz = pytz.timezone('Asia/Shanghai')
-
+
+ tz = pytz.timezone("Asia/Shanghai")
+
def __init__(self, max_num):
self.today = -1
self.count = defaultdict(int)
diff --git a/ATRI/utils/request.py b/ATRI/utils/request.py
index c638d63..6a7e3ba 100644
--- a/ATRI/utils/request.py
+++ b/ATRI/utils/request.py
@@ -2,46 +2,45 @@ from aiohttp import ClientSession, ClientResponse
class Response:
-
def __init__(self, response: ClientResponse) -> None:
self.raw_response = response
-
+
@property
def status(self) -> int:
return self.raw_response.status
-
+
@property
def url(self):
return self.raw_response.url
-
+
@property
def real_url(self):
return self.raw_response.real_url
-
+
@property
def host(self):
return self.raw_response.host
-
+
@property
def headers(self):
return self.raw_response.headers
-
+
@property
def raw_headers(self):
return self.raw_response.raw_headers
-
+
@property
def request_info(self):
return self.raw_response.request_info
-
+
@property
async def read(self):
return await self.raw_response.read()
-
+
@property
async def text(self):
return await self.raw_response.text()
-
+
async def json(self):
return await self.raw_response.json()