From 2a9d77ba8b37386b6dd5020149928af4b132aaf4 Mon Sep 17 00:00:00 2001 From: dtlnor Date: Mon, 14 Nov 2022 16:58:57 +0900 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=20fix=20group=20list=20search?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/twitter/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ATRI') diff --git a/ATRI/plugins/twitter/__init__.py b/ATRI/plugins/twitter/__init__.py index a64e712..2cbdb1b 100644 --- a/ATRI/plugins/twitter/__init__.py +++ b/ATRI/plugins/twitter/__init__.py @@ -177,7 +177,7 @@ async def _check_td(): group_list = await _bot.get_group_list() gl = [f"{i['group_id']}" for i in group_list] - if m.group_id not in gl: + if str(m.group_id) not in gl: await sub.del_sub(m.tid, m.group_id) log.warning(f"群 {m.group_id} 不存在, 已删除订阅 {m.name}@{m.screen_name}") -- cgit v1.2.3 From 896f532261358a14e770f729fd48e03478383986 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Tue, 15 Nov 2022 21:49:02 +0800 Subject: =?UTF-8?q?=F0=9F=8E=A8=20=E4=BC=98=E5=8C=96=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/status/data_source.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/status/data_source.py b/ATRI/plugins/status/data_source.py index 5daea59..10093c4 100644 --- a/ATRI/plugins/status/data_source.py +++ b/ATRI/plugins/status/data_source.py @@ -3,13 +3,12 @@ import time import psutil from datetime import datetime -from ATRI.service import Service from ATRI.message import MessageBuilder from ATRI.exceptions import GetStatusError _STATUS_MSG = ( - MessageBuilder("> Status Overview") + MessageBuilder("[Status Overview]") .text("[CPU: {b_cpu}% of {p_cpu}%]") .text("[Memory: {b_mem} of {p_mem}%]") .text("[Disk usage: {p_disk}%]") @@ -17,8 +16,9 @@ _STATUS_MSG = ( .text("[Net sent: {inteSENT}MB]") .text("[Net recv: {inteRECV}MB]") .text("") - .text("[Bot runtime: {bot_time}]") - .text("[Platform runtime: {boot_time}]") + .text("[Run Duration]") + .text("[Bot: {bot_time}]") + .text("[Platform: {boot_time}]") .text("{msg}") .done() ) -- cgit v1.2.3 From c5e6377547dfa27fa4cd800f10c75ace52d31c90 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Wed, 16 Nov 2022 12:45:23 +0800 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=20=E4=BF=AE=E5=A4=8D=E6=BD=9C?= =?UTF-8?q?=E5=9C=A8=E7=9A=84=E6=B3=A8=E5=85=A5=E5=8F=AF=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/code_runner/__init__.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'ATRI') diff --git a/ATRI/plugins/code_runner/__init__.py b/ATRI/plugins/code_runner/__init__.py index 26fcce5..95d3b0c 100644 --- a/ATRI/plugins/code_runner/__init__.py +++ b/ATRI/plugins/code_runner/__init__.py @@ -6,6 +6,7 @@ from nonebot.adapters.onebot.v11 import MessageEvent, Message, MessageSegment, u from nonebot.adapters.onebot.v11.helpers import Cooldown from ATRI.service import Service +from ATRI.utils import MessageChecker from .data_source import CodeRunner @@ -26,7 +27,7 @@ async def _code_runner(matcher: Matcher, args: Message = CommandArg()): matcher.set_arg("opt", args) else: content = "请键入 /code.help 以获取帮助~!" - await code_runner.finish(Message(content)) + await code_runner.finish(content) @code_runner.got("opt", prompt="需要运行的语言及代码?\n获取帮助:/code.help") @@ -38,6 +39,9 @@ async def _(event: MessageEvent, opt: str = ArgPlainText("opt")): await code_runner.finish(CodeRunner().help()) content = MessageSegment.at(user_id) + str(await CodeRunner().runner(unescape(opt))) + is_save = MessageChecker(str(content)).check_cq_code + if not is_save: + await code_runner.finish("有潜在的风险, 不予发送") await code_runner.finish(Message(content)) -- cgit v1.2.3 From 05537a8e8a0d0362fcc79394c2da60281a9916ef Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Thu, 17 Nov 2022 08:15:59 +0800 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=F0=9F=8E=A8=20=E4=BF=AE=E5=A4=8Db?= =?UTF-8?q?ug,=20=E4=BC=98=E5=8C=96=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/thesaurus/data_source.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'ATRI') diff --git a/ATRI/plugins/thesaurus/data_source.py b/ATRI/plugins/thesaurus/data_source.py index 8098179..8c12b16 100644 --- a/ATRI/plugins/thesaurus/data_source.py +++ b/ATRI/plugins/thesaurus/data_source.py @@ -1,6 +1,7 @@ import pytz from datetime import datetime +from ATRI.message import MessageBuilder from ATRI.exceptions import ThesaurusError from .db import DBForTS, DBForTAL @@ -98,8 +99,14 @@ class ThesaurusManager: {"matcher": q, "group_id": group_id}, is_main ) if query_result: + await self.del_item(_id, group_id, is_main) item_info = query_result[0] - return f"""{"(需审核/投票)" if not is_main else str()}该词条已存在!! ID: {item_info._id}""" + return ( + MessageBuilder(f"{str() if is_main else '(需审核/投票)'}该词条已存在!!") + .text(f"ID: {item_info._id}") + .text("因此, 此新增词条将被删除") + .done() + ) if t == "全匹配": m_type = 0 -- cgit v1.2.3 From 0c37cada0a6329308f60b4032ea192fd6a378564 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Sat, 19 Nov 2022 23:48:35 +0800 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=20=E4=BF=AE=E5=A4=8Dbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/essential/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/essential/__init__.py b/ATRI/plugins/essential/__init__.py index 4635583..da59ef8 100644 --- a/ATRI/plugins/essential/__init__.py +++ b/ATRI/plugins/essential/__init__.py @@ -62,7 +62,7 @@ async def _(event: FriendRequestEvent): user_id=user_id, comment=apply_comment, time=now_time, - ) + ).dict() await file.write(json.dumps(data)) result = ( @@ -96,7 +96,7 @@ async def _(event: GroupRequestEvent): user_id=user_id, comment=apply_comment, time=now_time, - ) + ).dict() await file.write(json.dumps(data)) result = ( -- cgit v1.2.3 From 5520493edcc4542b326a4650f723daa1ea451973 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Sun, 20 Nov 2022 19:15:36 +0800 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=20bug=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/setu/__init__.py | 16 ++++++++++------ ATRI/plugins/setu/data_source.py | 5 ----- 2 files changed, 10 insertions(+), 11 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/setu/__init__.py b/ATRI/plugins/setu/__init__.py index 1dea9b4..b7dc5f4 100644 --- a/ATRI/plugins/setu/__init__.py +++ b/ATRI/plugins/setu/__init__.py @@ -37,9 +37,11 @@ async def _random_setu(bot: Bot, event: MessageEvent): except Exception: await random_setu.finish("hso(发不出") - event_id = msg_1["message_id"] - loop.create_task(Setu.async_recall(bot, event_id)) - loop.close() + msg_id = msg_1["message_id"] + loop.call_later( + 60, + lambda: loop.create_task(bot.delete_msg(message_id=msg_id)) + ) @random_setu.got("r_rush_after_think", prompt="看完不来点感想么-w-") @@ -72,9 +74,11 @@ async def _tag_setu(bot: Bot, event: MessageEvent): except Exception: await random_setu.finish("hso(发不出") - event_id = msg_1["message_id"] - loop.create_task(Setu.async_recall(bot, event_id)) - loop.close() + msg_id = msg_1["message_id"] + loop.call_later( + 60, + lambda: loop.create_task(bot.delete_msg(message_id=msg_id)) + ) @tag_setu.got("t_rush_after_think", prompt="看完不来点感想么-w-") diff --git a/ATRI/plugins/setu/data_source.py b/ATRI/plugins/setu/data_source.py index 79a36e0..40cddd1 100644 --- a/ATRI/plugins/setu/data_source.py +++ b/ATRI/plugins/setu/data_source.py @@ -72,11 +72,6 @@ class Setu: data = await detect_image(url, file_size) return data - @staticmethod - async def async_recall(bot: Bot, event_id): - await asyncio.sleep(30) - await bot.delete_msg(message_id=event_id) - from ATRI import driver -- cgit v1.2.3 From cf506e1463c5b7e6ac5b5eed6271978515494af9 Mon Sep 17 00:00:00 2001 From: Lint Action Date: Sun, 20 Nov 2022 11:16:56 +0000 Subject: =?UTF-8?q?:rotating=5Flight:=20=E8=87=AA=E5=8A=A8=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/setu/__init__.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/setu/__init__.py b/ATRI/plugins/setu/__init__.py index b7dc5f4..46675fc 100644 --- a/ATRI/plugins/setu/__init__.py +++ b/ATRI/plugins/setu/__init__.py @@ -38,10 +38,7 @@ async def _random_setu(bot: Bot, event: MessageEvent): await random_setu.finish("hso(发不出") msg_id = msg_1["message_id"] - loop.call_later( - 60, - lambda: loop.create_task(bot.delete_msg(message_id=msg_id)) - ) + loop.call_later(60, lambda: loop.create_task(bot.delete_msg(message_id=msg_id))) @random_setu.got("r_rush_after_think", prompt="看完不来点感想么-w-") @@ -75,10 +72,7 @@ async def _tag_setu(bot: Bot, event: MessageEvent): await random_setu.finish("hso(发不出") msg_id = msg_1["message_id"] - loop.call_later( - 60, - lambda: loop.create_task(bot.delete_msg(message_id=msg_id)) - ) + loop.call_later(60, lambda: loop.create_task(bot.delete_msg(message_id=msg_id))) @tag_setu.got("t_rush_after_think", prompt="看完不来点感想么-w-") -- cgit v1.2.3 From 513b10ef3a105ed6c900e41b0e23fac4cd02a749 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:47:28 +0800 Subject: =?UTF-8?q?=F0=9F=8E=A8=20=E9=87=8D=E6=9E=84=E6=8A=A5=E9=94=99?= =?UTF-8?q?=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/exceptions.py | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) (limited to 'ATRI') diff --git a/ATRI/exceptions.py b/ATRI/exceptions.py index 22f643f..457acc8 100644 --- a/ATRI/exceptions.py +++ b/ATRI/exceptions.py @@ -7,13 +7,12 @@ from pydantic.main import BaseModel from nonebot.matcher import Matcher from nonebot.adapters.onebot.v11 import ActionFailed -from nonebot.adapters.onebot.v11 import Bot, PrivateMessageEvent, GroupMessageEvent +from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent from nonebot.message import run_postprocessor -from ATRI import conf - from .log import log -from .utils import gen_random_str +from .message import MessageBuilder +from .utils import Limiter, gen_random_str ERROR_DIR = Path(".") / "data" / "errors" @@ -103,6 +102,9 @@ class RssError(BaseBotException): prompt = "RSS订阅错误" +limiter = Limiter(3, 600) + + @run_postprocessor async def _(bot: Bot, event, matcher: Matcher, exception: Optional[Exception]): if not exception: @@ -117,21 +119,23 @@ async def _(bot: Bot, event, matcher: Matcher, exception: Optional[Exception]): prompt = "请参考协议端输出" track_id = _save_error(prompt, format_exc()) except Exception as err: - prompt = "Unknown ERROR->" + err.__class__.__name__ + prompt = "UnkErr " + err.__class__.__name__ track_id = _save_error(prompt, format_exc()) - if isinstance(event, PrivateMessageEvent): - _id = "用户" + event.get_user_id() - elif isinstance(event, GroupMessageEvent): - _id = "群" + str(event.group_id) - else: - _id = "unknown" - log.error(f"Error Track ID: {track_id}") - msg = f"呜——出错了...追踪: {track_id}\n来自: {_id}" - for superusers in conf.BotConfig.superusers: - try: - await bot.send_private_msg(user_id=superusers, message=msg) - except BaseBotException: - return + msg = ( + MessageBuilder("呜——出错了...请反馈维护者") + .text(f"信息: {prompt}") + .text(f"追踪ID: {track_id}") + ) + if isinstance(event, GroupMessageEvent): + group_id = str(event.group_id) + if not limiter.check(group_id): + msg = MessageBuilder("该群报错提示已达限制, 将冷却10min").text("如需反馈请: 来杯红茶") + limiter.increase(group_id) + + try: + await matcher.finish(msg) + except Exception: + return -- cgit v1.2.3 From 497384f1bf15d75a97f7cd7a375cfc7f7b2f9a3c Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:47:59 +0800 Subject: =?UTF-8?q?=F0=9F=8E=A8=20=E9=87=8D=E6=9E=84=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/status.py | 127 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 ATRI/plugins/status.py (limited to 'ATRI') diff --git a/ATRI/plugins/status.py b/ATRI/plugins/status.py new file mode 100644 index 0000000..e7ed842 --- /dev/null +++ b/ATRI/plugins/status.py @@ -0,0 +1,127 @@ +import os +import time +import psutil +from typing import Tuple +from datetime import datetime + +from nonebot import get_bot +from nonebot.adapters.onebot.v11 import unescape + +from ATRI.log import log +from ATRI.service import Service +from ATRI.message import MessageBuilder +from ATRI.exceptions import GetStatusError +from ATRI.utils.apscheduler import scheduler + + +plugin = Service("状态").document("检查自身状态") + + +ping = plugin.on_command("/ping", "检测bot是否存活") + + +@ping.handle() +async def _(): + await ping.finish("I'm fine.") + + +status = plugin.on_command("/status", "检查bot运行资源占用") + + +@status.handle() +async def _(): + msg, _ = get_status() + print(msg) + await status.finish(msg) + + +@scheduler.scheduled_job("interval", name="状态检查", minutes=15, misfire_grace_time=15) +async def _(): + log.info("检查资源消耗中...") + msg, stat = get_status() + if not stat: + log.warning("资源消耗异常") + + try: + bot = get_bot() + except Exception: + bot = None + + if bot: await plugin.send_to_master(msg) + else: + log.info("资源消耗正常") + + +_STATUS_MSG = ( + MessageBuilder("[Status Overview]") + .text("[CPU: {b_cpu}% of {p_cpu}%]") + .text("[Memory: {b_mem} of {p_mem}%]") + .text("[Disk usage: {p_disk}%]") + .text("") + .text("[Net sent: {inteSENT}MB]") + .text("[Net recv: {inteRECV}MB]") + .text("") + .text("[Run Duration]") + .text("[Bot: {bot_time}]") + .text("[Platform: {boot_time}]") + .text("{msg}") + .done() +) + + +def get_status() -> Tuple[str, bool]: + try: + cpu = psutil.cpu_percent(interval=1) + mem = psutil.virtual_memory().percent + disk = psutil.disk_usage("/").percent + inte_send = psutil.net_io_counters().bytes_sent / 1000000 + inte_recv = psutil.net_io_counters().bytes_recv / 1000000 + + process = psutil.Process(os.getpid()) + b_cpu = process.cpu_percent(interval=1) + b_mem = process.memory_percent(memtype="rss") + + now = time.time() + boot = psutil.boot_time() + b = process.create_time() + boot_time = str( + datetime.utcfromtimestamp(now).replace(microsecond=0) + - datetime.utcfromtimestamp(boot).replace(microsecond=0) + ) + bot_time = str( + datetime.utcfromtimestamp(now).replace(microsecond=0) + - datetime.utcfromtimestamp(b).replace(microsecond=0) + ) + except Exception: + raise GetStatusError("Failed to get status.") + + msg = "アトリは、高性能ですから!" + if cpu > 90: + msg = "咱感觉有些头晕..." + is_ok = False + if mem > 90: + msg = "咱感觉有点头晕并且有点累..." + is_ok = False + elif mem > 90: + msg = "咱感觉有点累..." + is_ok = False + elif disk > 90: + msg = "咱感觉身体要被塞满了..." + is_ok = False + else: + is_ok = True + + msg0 = _STATUS_MSG.format( + p_cpu=cpu, + p_mem=mem, + p_disk=disk, + b_cpu=b_cpu, + b_mem="%.1f%%" % b_mem, + inteSENT=inte_send, + inteRECV=inte_recv, + bot_time=bot_time, + boot_time=boot_time, + msg=msg, + ) + + return unescape(msg0), is_ok \ No newline at end of file -- cgit v1.2.3 From 590bd2a2969b5ce7ca3fed8937b5247521441c49 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:49:00 +0800 Subject: =?UTF-8?q?=F0=9F=94=A5=20=E5=88=A0=E9=99=A4=E6=9C=AA=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E7=9A=84=E5=AF=BC=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/essential/models.py | 1 - 1 file changed, 1 deletion(-) (limited to 'ATRI') diff --git a/ATRI/plugins/essential/models.py b/ATRI/plugins/essential/models.py index 4aa5693..dd2a801 100644 --- a/ATRI/plugins/essential/models.py +++ b/ATRI/plugins/essential/models.py @@ -1,4 +1,3 @@ -from typing import List, Optional from pydantic import BaseModel -- cgit v1.2.3 From fbeb9bdb7409402da5549a65b4f468bab9a93bae Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:49:45 +0800 Subject: =?UTF-8?q?=F0=9F=94=A5=20=E5=88=A0=E9=99=A4=E5=8A=9F=E8=83=BD:=20?= =?UTF-8?q?=E4=BB=8A=E5=A4=A9=E5=90=83=E4=BB=80=E4=B9=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/funny/__init__.py | 11 -------- ATRI/plugins/funny/data_source.py | 53 --------------------------------------- 2 files changed, 64 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/funny/__init__.py b/ATRI/plugins/funny/__init__.py index 094e569..8b060cc 100644 --- a/ATRI/plugins/funny/__init__.py +++ b/ATRI/plugins/funny/__init__.py @@ -63,14 +63,3 @@ async def _deal_fake( await bot.send_group_forward_msg(group_id=group_id, messages=node) except Exception: await fake_msg.finish("构造失败惹...可能是被制裁了(") - - -eat_what = plugin.on_regex(r"大?[今明后]天(.*?)吃[什啥]么?", "我来决定你吃什么!") - - -@eat_what.handle([Cooldown(15, prompt="慢慢吃,不要贪心哦!")]) -async def _eat_what(event: MessageEvent): - msg = str(event.get_message()) - user_name = event.sender.nickname or "裙友" - eat = await Funny().eat_what(user_name, msg) - await eat_what.finish(Message(eat)) diff --git a/ATRI/plugins/funny/data_source.py b/ATRI/plugins/funny/data_source.py index d3f88cc..9437034 100644 --- a/ATRI/plugins/funny/data_source.py +++ b/ATRI/plugins/funny/data_source.py @@ -58,56 +58,3 @@ class Funny: 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/" - params = {"event": "ManualRun"} - pattern_0 = r"大?[今明后]天(.*?)吃[什啥]么?" - pattern_1 = r"[今|明|后|大后]天" - arg = re.findall(pattern_0, msg)[0] - day = re.findall(pattern_1, msg)[0] - - if arg == "中午": - a = f"LdS4K6/{randint(0, 1145141919810)}" - url = EAT_URL + a - try: - data = await request.post(url, params=params) - data = data.json() - except Exception: - 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 - try: - data = await request.post(url, params=params) - data = data.json() - except Exception: - raise RequestError("Request failed!") - - result = Translate(data["text"]).to_simple().replace("今天", day) - - else: - rd = randint(1, 10) - if rd == 5: - result = ["吃我吧 ❤", "(脸红)请...请享用咱吧......", "都可以哦~不能挑食呢~"] - return choice(result) - else: - a = f"JJr1hJ/{randint(0, 1145141919810)}" - url = EAT_URL + a - try: - data = await request.post(url, params=params) - data = data.json() - except Exception: - 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 -- cgit v1.2.3 From 6c43fc43b7c408bce13775f1a1024809c66c904e Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:49:59 +0800 Subject: =?UTF-8?q?=F0=9F=94=A5=20=E5=88=A0=E9=99=A4=E6=9C=AA=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E7=9A=84=E5=AF=BC=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/rss/rss_mikanan/__init__.py | 1 - 1 file changed, 1 deletion(-) (limited to 'ATRI') diff --git a/ATRI/plugins/rss/rss_mikanan/__init__.py b/ATRI/plugins/rss/rss_mikanan/__init__.py index ec8dd60..2c577ee 100644 --- a/ATRI/plugins/rss/rss_mikanan/__init__.py +++ b/ATRI/plugins/rss/rss_mikanan/__init__.py @@ -17,7 +17,6 @@ from ATRI.log import log from ATRI.service import Service from ATRI.permission import ADMIN from ATRI.message import MessageBuilder -from ATRI.plugins.rss.rss_rsshub.data_source import RssHubSubscriptor from ATRI.utils import timestamp2datetime from ATRI.utils.apscheduler import scheduler from ATRI.database import RssMikananiSubcription -- cgit v1.2.3 From 1ee2eae499b79bf0d22212184bffd57d873826cc Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:52:19 +0800 Subject: =?UTF-8?q?=F0=9F=8E=A8=20=E9=87=8D=E6=9E=84=E6=B6=A9=E5=9B=BE?= =?UTF-8?q?=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/setu/__init__.py | 27 +++++----- ATRI/plugins/setu/data_source.py | 110 ++++++++++++++++++-------------------- ATRI/plugins/setu/models.py | 6 +++ ATRI/plugins/setu/nsfw_checker.py | 4 +- 4 files changed, 74 insertions(+), 73 deletions(-) create mode 100644 ATRI/plugins/setu/models.py (limited to 'ATRI') diff --git a/ATRI/plugins/setu/__init__.py b/ATRI/plugins/setu/__init__.py index b7dc5f4..4a9c6a6 100644 --- a/ATRI/plugins/setu/__init__.py +++ b/ATRI/plugins/setu/__init__.py @@ -29,13 +29,14 @@ async def _(): async def _random_setu(bot: Bot, event: MessageEvent): loop = asyncio.get_running_loop() - repo, se = await Setu.random_setu() - await bot.send(event, repo) + setu, setu_data = await Setu.new() + setu_info = f"Title: {setu_data.title}\nPid: {setu_data.pid}" + await bot.send(event, setu_info) try: - msg_1 = await bot.send(event, Message(se)) + msg_1 = await bot.send(event, setu) except Exception: - await random_setu.finish("hso(发不出") + await random_setu.finish("hso (发不出") msg_id = msg_1["message_id"] loop.call_later( @@ -56,23 +57,21 @@ async def _(think: str = ArgPlainText("r_rush_after_think")): tag_setu = plugin.on_regex(r"来[张点丶份](.*?)的[涩色🐍]图", "根据提供的tag查找涩图,冷却2分钟") -@tag_setu.handle([Cooldown(120, prompt="慢...慢一..点❤")]) +@tag_setu.handle([Cooldown(120, prompt="")]) async def _tag_setu(bot: Bot, event: MessageEvent): loop = asyncio.get_running_loop() msg = str(event.get_message()).strip() pattern = r"来[张点丶份](.*?)的[涩色🐍]图" tag = re.findall(pattern, msg)[0] - repo, se = await Setu.tag_setu(tag) - if not plugin: - await tag_setu.finish(repo) - - await bot.send(event, repo) + setu, setu_data = await Setu.new(tag) + setu_info = f"Title: {setu_data.title}\nPid: {setu_data.pid}" + await bot.send(event, setu_info) try: - msg_1 = await bot.send(event, Message(se)) + msg_1 = await bot.send(event, setu) except Exception: - await random_setu.finish("hso(发不出") + await random_setu.finish("hso (发不出") msg_id = msg_1["message_id"] loop.call_later( @@ -105,7 +104,7 @@ async def _setu_catcher(bot: Bot, event: MessageEvent): hso = list() for i in args: try: - data = await Setu.detecter(i, _catcher_max_file_size) + data = await Setu(i).detecter(_catcher_max_file_size) except Exception: return if data > 0.7: @@ -144,7 +143,7 @@ async def _deal_check(bot: Bot, event: MessageEvent): if not args: await nsfw_checker.reject("请发送图片而不是其他东西!!") - hso = await Setu.detecter(args[0], _catcher_max_file_size) + hso = await Setu(args[0]).detecter(_catcher_max_file_size) if not hso: await nsfw_checker.finish("图太小了!不测!") diff --git a/ATRI/plugins/setu/data_source.py b/ATRI/plugins/setu/data_source.py index 40cddd1..8a1a26d 100644 --- a/ATRI/plugins/setu/data_source.py +++ b/ATRI/plugins/setu/data_source.py @@ -1,76 +1,72 @@ -import asyncio -from nonebot.adapters.onebot.v11 import Bot, MessageSegment +from typing import Tuple +from nonebot.adapters.onebot.v11 import MessageSegment from ATRI import conf from ATRI.utils import request +from ATRI.exceptions import RequestError + +from .models import SetuInfo from .nsfw_checker import detect_image, init_model -LOLICON_URL = "https://api.lolicon.app/setu/v2" -DEFAULT_SETU = ( - "https://i.pixiv.cat/img-original/img/2021/02/28/22/44/49/88124144_p0.jpg" -) +__LOLICON_URL = "https://api.lolicon.app/setu/v2" class Setu: - @staticmethod - def _use_proxy(url: str) -> str: - if conf.Setu.reverse_proxy: - return url.replace("i.pixiv.cat", conf.Setu.reverse_proxy_domain) - else: - return url + def __init__(self, url: str): + self.url = url @classmethod - async def random_setu(cls) -> tuple: - """ - 随机涩图. - """ - res = await request.get(LOLICON_URL) - data: dict = res.json() - temp_data: dict = data.get("data", list()) - if not temp_data: - return "涩批爬", None + async def new(cls, tag: str = str()) -> Tuple[MessageSegment, SetuInfo]: + """new 一个涩图 - data: dict = temp_data[0] - title = data.get("title", "木陰のねこ") - p_id = data.get("pid", 88124144) - url: str = data["urls"].get("original", "ignore") + Args: + tag (str, optional): 附加 tag, 默认无 - setu = MessageSegment.image(cls._use_proxy(url), timeout=114514) - repo = f"Title: {title}\nPid: {p_id}" - return repo, setu + Raises: + RequestError: 涩图请求失败 - @classmethod - async def tag_setu(cls, tag: str) -> tuple: - """ - 指定tag涩图. + Returns: + Tuple[MessageSegment, dict]: 涩图本体, 涩图信息 """ - url = LOLICON_URL + f"?tag={tag}" - res = await request.get(url) - data: dict = res.json() - - temp_data: dict = data.get("data", list()) - if not temp_data: - return f"没有 {tag} 的涩图呢...", None - - data = temp_data[0] - title = data.get("title", "木陰のねこ") - p_id = data.get("pid", 88124144) - url = data["urls"].get( - "original", - cls._use_proxy(DEFAULT_SETU), - ) - setu = MessageSegment.image(url, timeout=114514) - repo = f"Title: {title}\nPid: {p_id}" - return repo, setu - - @staticmethod - async def detecter(url: str, file_size: int) -> float: - """ - 涩值检测. + url = __LOLICON_URL + if tag: + url = __LOLICON_URL + f"?tag={tag}" + try: + req = await request.get(url) + except Exception: + raise RequestError("setu: 请求失败") + + data = req.json() + cache_data = data.get("data") + if not cache_data: + raise RequestError("今天不可以涩") + + data = cache_data[0] + title = data["title"] + pid = data["pid"] + setu = data["urls"].get("original", "ignore") + + if conf.Setu.reverse_proxy: + setu = MessageSegment.image( + file=setu.replace("i.pixiv.cat", conf.Setu.reverse_proxy_domain), + timeout=114514, + ) + + setu_data = SetuInfo(title=title, pid=pid) + + return setu, setu_data + + async def detecter(self, max_size: int) -> float: + """图片涩值检测 + + Args: + max_size (int): 检测文件大小限制 + + Returns: + float: 百分比涩值 """ - data = await detect_image(url, file_size) - return data + return await detect_image(self.url, max_size) from ATRI import driver diff --git a/ATRI/plugins/setu/models.py b/ATRI/plugins/setu/models.py new file mode 100644 index 0000000..7144f27 --- /dev/null +++ b/ATRI/plugins/setu/models.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel + + +class SetuInfo(BaseModel): + title: str + pid: str diff --git a/ATRI/plugins/setu/nsfw_checker.py b/ATRI/plugins/setu/nsfw_checker.py index c0bd2ba..53546f6 100644 --- a/ATRI/plugins/setu/nsfw_checker.py +++ b/ATRI/plugins/setu/nsfw_checker.py @@ -40,14 +40,14 @@ def prepare_image(img): return image -async def detect_image(url: str, file_size: int) -> float: +async def detect_image(url: str, max_size: int) -> float: try: req = await request.get(url) except Exception: raise RequestError("Get info from download image failed!") img_byte = getsizeof(req.read()) // 1024 - if img_byte < file_size: + if img_byte < max_size: return 0 try: -- cgit v1.2.3 From 4436fa3b6ea4bb54198c0fcc247e48d75942f829 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:53:23 +0800 Subject: =?UTF-8?q?=F0=9F=94=A5=20=E5=88=A0=E9=99=A4=E5=BC=83=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/status/__init__.py | 45 ------------------- ATRI/plugins/status/data_source.py | 88 -------------------------------------- 2 files changed, 133 deletions(-) delete mode 100644 ATRI/plugins/status/__init__.py delete mode 100644 ATRI/plugins/status/data_source.py (limited to 'ATRI') diff --git a/ATRI/plugins/status/__init__.py b/ATRI/plugins/status/__init__.py deleted file mode 100644 index 08e099c..0000000 --- a/ATRI/plugins/status/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -from nonebot import get_bot - -from ATRI import conf -from ATRI.log import log -from ATRI.service import Service -from ATRI.utils.apscheduler import scheduler - -from .data_source import Status - - -plugin = Service("状态").document("检查自身状态") - - -ping = plugin.on_command("/ping", "检测bot简单信息处理速度") - - -@ping.handle() -async def _(): - await ping.finish(Status.ping()) - - -status = plugin.on_command("/status", "查看运行资源占用") - - -@status.handle() -async def _(): - msg, _ = Status.get_status() - await status.finish(msg) - - -info_msg = "アトリは高性能ですから!" - - -@scheduler.scheduled_job("interval", name="状态检查", minutes=10, misfire_grace_time=15) # type: ignore -async def _(): - log.info("开始检查资源消耗...") - msg, stat = Status.get_status() - if not stat: - log.warning(msg) - - bot = get_bot() - for super in conf.BotConfig.superusers: - await bot.send_private_msg(user_id=super, message=msg) - - log.info("资源消耗正常") diff --git a/ATRI/plugins/status/data_source.py b/ATRI/plugins/status/data_source.py deleted file mode 100644 index 10093c4..0000000 --- a/ATRI/plugins/status/data_source.py +++ /dev/null @@ -1,88 +0,0 @@ -import os -import time -import psutil -from datetime import datetime - -from ATRI.message import MessageBuilder -from ATRI.exceptions import GetStatusError - - -_STATUS_MSG = ( - MessageBuilder("[Status Overview]") - .text("[CPU: {b_cpu}% of {p_cpu}%]") - .text("[Memory: {b_mem} of {p_mem}%]") - .text("[Disk usage: {p_disk}%]") - .text("") - .text("[Net sent: {inteSENT}MB]") - .text("[Net recv: {inteRECV}MB]") - .text("") - .text("[Run Duration]") - .text("[Bot: {bot_time}]") - .text("[Platform: {boot_time}]") - .text("{msg}") - .done() -) - - -class Status: - @staticmethod - def ping() -> str: - return "I'm fine." - - @staticmethod - def get_status() -> tuple: - try: - cpu = psutil.cpu_percent(interval=1) - mem = psutil.virtual_memory().percent - disk = psutil.disk_usage("/").percent - inte_send = psutil.net_io_counters().bytes_sent / 1000000 # type: ignore - inte_recv = psutil.net_io_counters().bytes_recv / 1000000 # type: ignore - - process = psutil.Process(os.getpid()) - b_cpu = process.cpu_percent(interval=1) - b_mem = process.memory_percent(memtype="rss") - - now = time.time() - boot = psutil.boot_time() - b = process.create_time() - boot_time = str( - datetime.utcfromtimestamp(now).replace(microsecond=0) - - datetime.utcfromtimestamp(boot).replace(microsecond=0) - ) - bot_time = str( - datetime.utcfromtimestamp(now).replace(microsecond=0) - - datetime.utcfromtimestamp(b).replace(microsecond=0) - ) - except Exception: - raise GetStatusError("Failed to get status.") - - msg = "アトリは、高性能ですから!" - if cpu > 90: # type: ignore - msg = "咱感觉有些头晕..." - is_ok = False - if mem > 90: - msg = "咱感觉有点头晕并且有点累..." - is_ok = False - elif mem > 90: - msg = "咱感觉有点累..." - is_ok = False - elif disk > 90: - msg = "咱感觉身体要被塞满了..." - is_ok = False - else: - is_ok = True - - msg0 = _STATUS_MSG.format( - p_cpu=cpu, - p_mem=mem, - p_disk=disk, - b_cpu=b_cpu, - b_mem="%.1f%%" % b_mem, - inteSENT=inte_send, - inteRECV=inte_recv, - bot_time=bot_time, - boot_time=boot_time, - msg=msg, - ) - - return msg0, is_ok -- cgit v1.2.3 From fef46d6fb71df12e35068cad5d83da5e070629aa Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 08:54:23 +0800 Subject: =?UTF-8?q?=F0=9F=8E=A8=20=E6=96=B0=E5=A2=9E=E5=86=B7=E5=8D=B4?= =?UTF-8?q?=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/utils/__init__.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'ATRI') diff --git a/ATRI/utils/__init__.py b/ATRI/utils/__init__.py index aeeb9db..a1a7f3b 100644 --- a/ATRI/utils/__init__.py +++ b/ATRI/utils/__init__.py @@ -5,11 +5,13 @@ import pytz import yaml import time import string +import asyncio import aiofiles from pathlib import Path from random import sample from datetime import datetime from PIL import Image, ImageFile +from collections import defaultdict from aiofiles.threadpool.text import AsyncTextIOWrapper @@ -220,3 +222,33 @@ class Translate: output_str_list.append(self.text[i]) return "".join(output_str_list) + + +class Limiter: + def __init__(self, max_count: int, down_time: float): + """冷却设置 + + Args: + max_count (int): 最大次数 + down_time (float): 到达次数后的冷却时间 + """ + self.max_count = max_count + self.down_time = down_time + self.count = defaultdict(int) + + def check(self, key: str) -> bool: + if self.count[key] >= self.max_count: + loop = asyncio.get_running_loop() + loop.call_later(self.down_time, self.reset) + return False + + return True + + def increase(self, key: str, times: int = 1) -> None: + self.count[key] += times + + def reset(self, key: str) -> None: + self.count[key] = 0 + + def get_times(self, key: str) -> int: + return self.count[key] -- cgit v1.2.3 From b5584e0c8536c818a8073b3b856a9ac8c11adfab Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Fri, 2 Dec 2022 21:53:03 +0800 Subject: =?UTF-8?q?=F0=9F=8E=A8=20=E9=87=8D=E6=9E=84=E9=83=A8=E5=88=86?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/utils/__init__.py | 67 ++++++++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 29 deletions(-) (limited to 'ATRI') diff --git a/ATRI/utils/__init__.py b/ATRI/utils/__init__.py index a1a7f3b..9ce3735 100644 --- a/ATRI/utils/__init__.py +++ b/ATRI/utils/__init__.py @@ -2,8 +2,6 @@ import os import re import json import pytz -import yaml -import time import string import asyncio import aiofiles @@ -15,42 +13,53 @@ from collections import defaultdict from aiofiles.threadpool.text import AsyncTextIOWrapper -def timestamp2datetimestr(timestamp: int) -> str: - format = "%Y-%m-%d %H:%M:%S" - tt = time.localtime(timestamp) - dt = time.strftime(format, tt) - return dt +def gen_random_str(k: int) -> str: + return str().join(sample(string.ascii_letters + string.digits, k)) -def timestamp2datetime(value: float) -> datetime: - tz = pytz.timezone("Asia/Shanghai") - return datetime.fromtimestamp(value, tz=tz) +class TimeDealer: + def __init__(self, timestamp: float): + """对时间进行处理 + Args: + timestamp (int): _description_ + """ + self.timestamp = timestamp -def now_time() -> float: - """获取当前时间的整数.""" - now_ = datetime.now() - hour = now_.hour - minute = now_.minute - now = hour + minute / 60 - return now + def to_str( + self, tz=pytz.timezone("Asia/Shanghai"), format: str = "%Y-%m-%d %H:%M:%S" + ) -> str: + """将时间戳转换为格式化形式 + Args: + tz: 时区. 默认: `pytz.timezone("Asia/Shanghai")`. + format: 时间格式. 默认: `"%Y-%m-%d %H:%M:%S"`. -def load_yml(file: Path, encoding="utf-8") -> dict: - """打开 yaml 格式的文件.""" - with open(file, "r", encoding=encoding) as f: - data = yaml.safe_load(f) - return data + Returns: + str: 格式化后的时间戳 + """ + return datetime.fromtimestamp(self.timestamp, tz).strftime(format) + def to_datetime(self, tz=pytz.timezone("Asia/Shanghai")) -> datetime: + """将时间戳转化成 datetime 类型 -def safe_string(value): - if isinstance(value, bytes): - return value.decode() - return str(value) + Args: + tz: 时区. 默认: `pytz.timezone("Asia/Shanghai")`. + Returns: + datetime: 转换后的 datetime 类型 + """ + return datetime.fromtimestamp(self.timestamp, tz) -def gen_random_str(k: int) -> str: - return str().join(sample(string.ascii_letters + string.digits, k)) + def int_now(self) -> float: + """将时间戳转换为一天中整数的时间. + e.g. 9:30 > 9.50 + + Returns: + float: 转换后的整数时间 + """ + time = datetime.fromtimestamp(self.timestamp) + return time.hour + time.minute / 60 class ListDealer: @@ -241,7 +250,7 @@ class Limiter: loop = asyncio.get_running_loop() loop.call_later(self.down_time, self.reset) return False - + return True def increase(self, key: str, times: int = 1) -> None: -- cgit v1.2.3 From bab91c7d65e5ba459bf24097125663c598ee99de Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Mon, 12 Dec 2022 16:11:20 +0800 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=20=E4=BF=AE=E5=A4=8D=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/setu/data_source.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/setu/data_source.py b/ATRI/plugins/setu/data_source.py index 8a1a26d..59f511a 100644 --- a/ATRI/plugins/setu/data_source.py +++ b/ATRI/plugins/setu/data_source.py @@ -9,7 +9,7 @@ from .models import SetuInfo from .nsfw_checker import detect_image, init_model -__LOLICON_URL = "https://api.lolicon.app/setu/v2" +_LOLICON_URL = "https://api.lolicon.app/setu/v2" class Setu: @@ -29,9 +29,9 @@ class Setu: Returns: Tuple[MessageSegment, dict]: 涩图本体, 涩图信息 """ - url = __LOLICON_URL + url = _LOLICON_URL if tag: - url = __LOLICON_URL + f"?tag={tag}" + url = _LOLICON_URL + f"?tag={tag}" try: req = await request.get(url) except Exception: -- cgit v1.2.3 From de5cf242b98888baf9b12522542b4fac4851e6a4 Mon Sep 17 00:00:00 2001 From: XHLin-gamer <73104227+XHLin-gamer@users.noreply.github.com> Date: Fri, 16 Dec 2022 23:51:07 +0900 Subject: =?UTF-8?q?=E4=BF=AE=E6=AD=A3go=5Fcqhttp=E7=9A=84=E4=B8=8B?= =?UTF-8?q?=E8=BD=BD=E5=9F=9F=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 当前的下载域名误填写为了下载版本,在config.py中进行了修正 --- ATRI/configs/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ATRI') diff --git a/ATRI/configs/config.py b/ATRI/configs/config.py index 3ea0bf7..23cd1bb 100644 --- a/ATRI/configs/config.py +++ b/ATRI/configs/config.py @@ -61,7 +61,7 @@ class Config: command_sep=bot_conf.command_sep, session_expire_timeout=bot_conf.session_expire_timeout, gocq_accounts=gocq_conf.accounts, - gocq_download_domain=gocq_conf.download_version, + gocq_download_domain=gocq_conf.download_domain, gocq_version=gocq_conf.download_version, gocq_webui_username=gocq_conf.gocq_webui_username, gocq_webui_password=gocq_conf.gocq_webui_password, -- cgit v1.2.3 From 1b5b6f91cb61367b86d5f145cc5a865faceaecfe Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Wed, 28 Dec 2022 15:43:44 +0800 Subject: =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20=E8=B7=9F=E9=9A=8F=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E7=B1=BB=E6=94=B9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/bilibili_dynamic/__init__.py | 4 ++-- ATRI/plugins/bilibili_dynamic/data_source.py | 4 ++-- ATRI/plugins/rss/rss_mikanan/__init__.py | 4 ++-- ATRI/plugins/rss/rss_rsshub/__init__.py | 4 ++-- ATRI/plugins/twitter/__init__.py | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/bilibili_dynamic/__init__.py b/ATRI/plugins/bilibili_dynamic/__init__.py index 7459a15..c47feed 100644 --- a/ATRI/plugins/bilibili_dynamic/__init__.py +++ b/ATRI/plugins/bilibili_dynamic/__init__.py @@ -16,8 +16,8 @@ from nonebot.adapters.onebot.v11 import Message, MessageSegment, GroupMessageEve from ATRI.log import log from ATRI.service import Service +from ATRI.utils import TimeDealer from ATRI.permission import MASTER, ADMIN -from ATRI.utils import timestamp2datetime from ATRI.utils.apscheduler import scheduler from ATRI.database import BilibiliSubscription @@ -192,7 +192,7 @@ async def _(): m.uid, m.group_id, { - "last_update": timestamp2datetime(i["timestamp"]), + "last_update": TimeDealer(float(i["timestamp"])).to_datetime(), }, ) if _pic: diff --git a/ATRI/plugins/bilibili_dynamic/data_source.py b/ATRI/plugins/bilibili_dynamic/data_source.py index 26ebf50..2bdfee9 100644 --- a/ATRI/plugins/bilibili_dynamic/data_source.py +++ b/ATRI/plugins/bilibili_dynamic/data_source.py @@ -3,7 +3,7 @@ from datetime import datetime from operator import itemgetter from ATRI.message import MessageBuilder -from ATRI.utils import timestamp2datetime +from ATRI.utils import TimeDealer from ATRI.exceptions import BilibiliDynamicError from .db import DB @@ -95,7 +95,7 @@ class BilibiliDynamicSubscriptor: pattern["like"] = desc["like"] pattern["dynamic_id"] = desc["dynamic_id"] pattern["timestamp"] = desc["timestamp"] - pattern["time"] = timestamp2datetime(desc["timestamp"]) + pattern["time"] = TimeDealer(float(desc["timestamp"])).to_datetime() pattern["type_zh"] = str() # alternative 部分 diff --git a/ATRI/plugins/rss/rss_mikanan/__init__.py b/ATRI/plugins/rss/rss_mikanan/__init__.py index 2c577ee..fb4b23c 100644 --- a/ATRI/plugins/rss/rss_mikanan/__init__.py +++ b/ATRI/plugins/rss/rss_mikanan/__init__.py @@ -17,7 +17,7 @@ from ATRI.log import log from ATRI.service import Service from ATRI.permission import ADMIN from ATRI.message import MessageBuilder -from ATRI.utils import timestamp2datetime +from ATRI.utils import TimeDealer from ATRI.utils.apscheduler import scheduler from ATRI.database import RssMikananiSubcription @@ -167,5 +167,5 @@ async def _(): bot = get_bot() await bot.send_group_msg(group_id=data.group_id, message=repo) await sub.update_sub( - data._id, data.group_id, {"update_time": timestamp2datetime(m_t)} + data._id, data.group_id, {"update_time": TimeDealer(m_t).to_datetime()} ) diff --git a/ATRI/plugins/rss/rss_rsshub/__init__.py b/ATRI/plugins/rss/rss_rsshub/__init__.py index 969fe0a..137ec88 100644 --- a/ATRI/plugins/rss/rss_rsshub/__init__.py +++ b/ATRI/plugins/rss/rss_rsshub/__init__.py @@ -16,7 +16,7 @@ from nonebot.adapters.onebot.v11 import Message, GroupMessageEvent from ATRI.log import log from ATRI.service import Service from ATRI.permission import ADMIN -from ATRI.utils import timestamp2datetime +from ATRI.utils import TimeDealer from ATRI.utils.apscheduler import scheduler from ATRI.database import RssRsshubSubcription @@ -164,5 +164,5 @@ async def _(): bot = get_bot() await bot.send_group_msg(group_id=m.group_id, message=repo) await sub.update_sub( - m._id, m.group_id, {"update_time": timestamp2datetime(ts_t)} + m._id, m.group_id, {"update_time": TimeDealer(ts_t).to_datetime()} ) diff --git a/ATRI/plugins/twitter/__init__.py b/ATRI/plugins/twitter/__init__.py index 2cbdb1b..6e69cc1 100644 --- a/ATRI/plugins/twitter/__init__.py +++ b/ATRI/plugins/twitter/__init__.py @@ -17,7 +17,7 @@ from nonebot.adapters.onebot.v11 import Message, MessageSegment, GroupMessageEve from ATRI.log import log from ATRI.service import Service from ATRI.permission import ADMIN -from ATRI.utils import timestamp2datetime +from ATRI.utils import TimeDealer from ATRI.utils.apscheduler import scheduler from ATRI.permission import MASTER from ATRI.database import TwitterSubscription @@ -215,7 +215,7 @@ async def _check_td(): log.warning("推信息发送失败") await sub.update_sub( - m.tid, m.group_id, {"last_update": timestamp2datetime(ts_t)} + m.tid, m.group_id, {"last_update": TimeDealer(ts_t).to_datetime()} ) if _pic: pic = Message(MessageSegment.image(_pic)) -- cgit v1.2.3 From f197f55e4dadbb99b5ae60584af75e05c96725b2 Mon Sep 17 00:00:00 2001 From: Kyomotoi <0w0@imki.moe> Date: Wed, 28 Dec 2022 15:43:51 +0800 Subject: =?UTF-8?q?=F0=9F=9A=91=EF=B8=8F=20=E5=BB=B6=E9=95=BF=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=8D=A0=E7=94=A8=E6=8F=90=E7=A4=BA=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E5=8F=8A=E9=99=90=E5=88=B6=E6=8F=90=E9=86=92=E6=AC=A1=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/plugins/status.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'ATRI') diff --git a/ATRI/plugins/status.py b/ATRI/plugins/status.py index e7ed842..d6a5682 100644 --- a/ATRI/plugins/status.py +++ b/ATRI/plugins/status.py @@ -11,6 +11,7 @@ from ATRI.log import log from ATRI.service import Service from ATRI.message import MessageBuilder from ATRI.exceptions import GetStatusError +from ATRI.utils import Limiter from ATRI.utils.apscheduler import scheduler @@ -35,7 +36,10 @@ async def _(): await status.finish(msg) -@scheduler.scheduled_job("interval", name="状态检查", minutes=15, misfire_grace_time=15) +limiter = Limiter(5, 21600) + + +@scheduler.scheduled_job("interval", name="状态检查", minutes=30, misfire_grace_time=15) async def _(): log.info("检查资源消耗中...") msg, stat = get_status() @@ -46,8 +50,12 @@ async def _(): bot = get_bot() except Exception: bot = None - - if bot: await plugin.send_to_master(msg) + if not limiter.check("114514"): + try: + if bot: await plugin.send_to_master(msg) + limiter.increase("114514") + except Exception: + return else: log.info("资源消耗正常") -- cgit v1.2.3