diff --git a/.gitignore b/.gitignore index 7dd67d4..c7c9e90 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ __pycache__ resources/font/* resources/search_char/private/* .pdm.toml +.pdm-python diff --git a/.pdm-python b/.pdm-python deleted file mode 100644 index bd81f41..0000000 --- a/.pdm-python +++ /dev/null @@ -1 +0,0 @@ -D:/shitlime's folder/Python/Projcet Grbl/Grbl2/.venv/Scripts/python.exe \ No newline at end of file diff --git a/bot.py b/bot.py index d8ae322..d4c9eb3 100644 --- a/bot.py +++ b/bot.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- from asyncio.events import AbstractEventLoop +from loguru import logger from bot_init import BOT from modules.base.check import check_friend @@ -31,7 +32,7 @@ @app.broadcast.receiver("FriendMessage", decorators=[check_friend(BOT.admin)]) async def friend_message_listener(app: Ariadne, friend: Friend, message: MessageChain): friendMsg = message.display # type:str - #print(friend.id) # 打印QQ号码 + #logger.info(friend.id) # 打印QQ号码 if friendMsg == "|say h": await app.send_message( friend, @@ -79,7 +80,7 @@ async def stop_background(): try: saya.require(m) except (Exception, RuntimeError) as e: - print(f"加载[{m}]模块时发生错误:{e}") + logger.error(f"加载[{m}]模块时发生错误:{e}") # 阻塞式启动 app.launch_blocking() diff --git a/bot_init.py b/bot_init.py index c05774c..d01f50b 100644 --- a/bot_init.py +++ b/bot_init.py @@ -2,6 +2,8 @@ import yaml import platform +from loguru import logger + class BotData(yaml.YAMLObject): yaml_tag = '!BotData' yaml_loader = yaml.SafeLoader @@ -46,8 +48,8 @@ def save_config(self, file_path) -> None: yaml.dump(self, f) def print_config(self) -> None: - print("Bot config:") - print(self) + logger.info("Bot config:") + logger.info(self) def get_modules_config(self, module_name: str) -> dict: return self.modules_config[module_name] diff --git a/modules/ACGimg/ACGimg.py b/modules/ACGimg/ACGimg.py index 698cc1e..a011356 100644 --- a/modules/ACGimg/ACGimg.py +++ b/modules/ACGimg/ACGimg.py @@ -1,4 +1,5 @@ import asyncio +from loguru import logger from bot_init import BOT from modules.base.message_queue import MessageQueue @@ -60,7 +61,7 @@ ) async def acg_img(app: Ariadne, group: Group, member: Member): img = await get_acg_img() - print("acgimg: 正在返回图片") + logger.info("acgimg: 正在返回图片") if type(img) == bytes: await app.send_message( group, diff --git a/modules/ACGimg/get_acg_img.py b/modules/ACGimg/get_acg_img.py index cf21480..f0c9e1d 100644 --- a/modules/ACGimg/get_acg_img.py +++ b/modules/ACGimg/get_acg_img.py @@ -2,6 +2,8 @@ import aiohttp import asyncio +from loguru import logger + # TEST from pathlib import Path @@ -14,7 +16,7 @@ async def get_img(url: str): async with session.get(url) as r: if r.status == 200: # 请求成功 img = await r.read() - print(f'acgimg size{len(img)}') + logger.info(f'acgimg size{len(img)}') return img else: # 请求失败 return r.status diff --git a/modules/Admin/recall_message.py b/modules/Admin/recall_message.py index 0da185c..cece03a 100644 --- a/modules/Admin/recall_message.py +++ b/modules/Admin/recall_message.py @@ -1,4 +1,5 @@ from datetime import datetime, timezone +from loguru import logger from bot_init import BOT from modules.base.message_queue import MessageQueue @@ -56,18 +57,18 @@ async def recall_message(app: Ariadne, group: Group, source: Source, num: RegexR if msg.sender.id == BOT.ariadne_config["qq_id"]: # 如果消息已经超过2分钟,一般无法撤回 if (datetime.now(timezone.utc) - msg.source.time).total_seconds() > 120: - print("Bot最近的消息已经超过2分钟") + logger.info("Bot最近的消息已经超过2分钟") # 如果Bot是群主/管理员,继续撤回 if (msg.sender.permission == MemberPerm.Administrator or msg.sender.permission == MemberPerm.Owner): - print(f"使用管理员权限撤回msg={msg}") + logger.info(f"使用管理员权限撤回msg={msg}") await app.recall_message(msg) else: - print("Bot无管理员权限,撤回失败") + logger.info("Bot无管理员权限,撤回失败") await app.send_message(group, MessageChain("消息超过2分钟且无权限撤回")) return - print(f"尝试撤回msg{msg}") + logger.info(f"尝试撤回msg{msg}") await app.recall_message(msg) num -= 1 # 撤回后寻找下一条消息 diff --git a/modules/Bilibili/get_video_info.py b/modules/Bilibili/get_video_info.py index a272343..371dfa4 100644 --- a/modules/Bilibili/get_video_info.py +++ b/modules/Bilibili/get_video_info.py @@ -1,4 +1,5 @@ from .video import get_video_info, get_video +from loguru import logger from ..base.get_quote_message import get_quote_message from ..base.time2str import timestamp2str @@ -49,7 +50,7 @@ ) async def get_video_info_auto(app: Ariadne, target: Group | Friend, bvid: RegexResult): bvid = bvid.result.display - print(f"识别到消息中含有BV:{bvid}") + logger.info(f"识别到消息中含有BV:{bvid}") # 获取视屏信息 video = get_video(bvid) info = await video.get_info() diff --git a/modules/Bilibili/video.py b/modules/Bilibili/video.py index 871e072..576358f 100644 --- a/modules/Bilibili/video.py +++ b/modules/Bilibili/video.py @@ -2,6 +2,7 @@ import asyncio import aiohttp from bilibili_api import video +from loguru import logger def get_video_id(url: str) -> str | None: @@ -34,14 +35,14 @@ async def get_real_url(url: str): 'Connection': 'close' } timeout = aiohttp.ClientTimeout(total = 30) - print(f"Bilibili.get_real_url: 开始访问手机端分享链接 {url}") + logger.info(f"Bilibili.get_real_url: 开始访问手机端分享链接 {url}") async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session: async with session.get(url) as result: if result.status == 200: - print(f"Bilibili.get_real_url: 获取到原始链接 {result.url}") + logger.info(f"Bilibili.get_real_url: 获取到原始链接 {result.url}") return str(result.url) else: - print(f"Bilibili.get_real_url: 返回结果错误,状态码 {result.status}") + logger.error(f"Bilibili.get_real_url: 返回结果错误,状态码 {result.status}") async def get_video_info(string: str) -> dict | None: # 输入信息 @@ -54,10 +55,10 @@ async def get_video_info(string: str) -> dict | None: try: info = await v.get_info() # 打印信息 - print(str(info)[:1000]) + logger.info(f"视频信息:{str(info)[:500]}") return info except: - print("获取视频信息出错了") + logger.error("获取视频信息失败了") async def get_video_ai_conclusion(string: str) -> dict: # 输入信息 @@ -71,10 +72,10 @@ async def get_video_ai_conclusion(string: str) -> dict: cid = list(await v.get_pages())[0]['cid'] ai_conclusion = await v.get_ai_conclusion(cid) # 打印信息 - print(str(ai_conclusion)[:1000]) + logger.info(f"AI总结:{str(ai_conclusion)[:500]}") return ai_conclusion except: - print("获取视频AI总结出错了") + logger.error("获取视频AI总结失败了") if __name__ == '__main__': string = input("输入视屏链接:") diff --git a/modules/BreakTofu/break_tofu.py b/modules/BreakTofu/break_tofu.py index 16f75b2..1c182fb 100644 --- a/modules/BreakTofu/break_tofu.py +++ b/modules/BreakTofu/break_tofu.py @@ -1,5 +1,6 @@ import re import asyncio +from loguru import logger from bot_init import BOT from modules.base.message_queue import MessageQueue @@ -102,7 +103,7 @@ async def break_tofu(app: Ariadne, group: Group, source: Source): #print(f"tofu={tofu}") if tofu not in banText: - print(f"豆腐块:{tofu}") + logger.info(f"渲染豆腐块:{tofu}") await app.send_message( group, # MessageChain(Image(data_bytes= await get_tofu_img(tofu, fd_cache))), @@ -139,7 +140,7 @@ async def break_tofu_cmd(app: Ariadne, target: Group|Friend, msg: MessageChain): if tofu in banText: pass else: - print(f"豆腐块cmd:{tofu}") + logger.info(f"渲染豆腐块:{tofu}") await app.send_message( target, MessageChain( diff --git a/modules/BreakTofu/char2image.py b/modules/BreakTofu/char2image.py index 85ff7b7..cd31154 100644 --- a/modules/BreakTofu/char2image.py +++ b/modules/BreakTofu/char2image.py @@ -46,7 +46,7 @@ def char2image(string: str, font_size=60, background_color=(255, 255, 255), char while True: string_list.append(next(g)) except StopIteration: - print("文字切分完毕") + # print("文字切分完毕") pass string = string_list img = Image.new("RGB", (width, height), background_color) diff --git a/modules/BreakTofu/guess_tofu.py b/modules/BreakTofu/guess_tofu.py index ec66fc9..18503e9 100644 --- a/modules/BreakTofu/guess_tofu.py +++ b/modules/BreakTofu/guess_tofu.py @@ -1,6 +1,7 @@ import re import random import asyncio +from loguru import logger from bot_init import BOT from modules.base.message_queue import MessageQueue @@ -160,7 +161,7 @@ async def waiter(events : GroupMessage | FriendMessage): ) ) # 胜利的玩家 - print(f" 胜利:{player}") + logger.info(f"猜豆腐-单胜利玩家:{player}") return 0 # 答对0 else: msg = await app.send_message( @@ -349,6 +350,7 @@ async def waiter(waiter_events: GroupMessage): else: # 空 scroes[player.id] = gt.score + logger.info(f"猜豆腐-竞赛胜利玩家:{player}") return 0 # 答对0 else: # 答错 @@ -572,6 +574,7 @@ async def waiter(waiter_events: GroupMessage): else: # 空 scroes[player.id] = 1 + logger.info(f"猜豆腐-无尽胜利玩家:{player}") return 0 # 答对0 else: # 答错 diff --git a/modules/BreakTofu/guess_tofu_core.py b/modules/BreakTofu/guess_tofu_core.py index 9f37612..2baf734 100644 --- a/modules/BreakTofu/guess_tofu_core.py +++ b/modules/BreakTofu/guess_tofu_core.py @@ -181,7 +181,7 @@ def random_mask_rule2(self, x, y, p=0.5)->list[list]: for l in rule: sum += l.count(1) self.maskCount = sum - print(self.maskCount) + # print(self.maskCount) self.maxCount = x*y self.score = int((self.maskCount / self.maxCount) * ((self.level + 1) * 10)) + 1 return rule diff --git a/modules/SearchThing/search_char.py b/modules/SearchThing/search_char.py index f470644..87f624f 100644 --- a/modules/SearchThing/search_char.py +++ b/modules/SearchThing/search_char.py @@ -4,6 +4,7 @@ import unicodedata from pypinyin import pinyin from datetime import datetime +from loguru import logger from bot_init import BOT from modules.base.message_queue import MessageQueue @@ -93,7 +94,7 @@ async def search_char_info(app: Ariadne, target: Group | Friend, # 查找的字符 search_char = search_char.split(" | ")[0] re_msg = None - print(f"sm:{search_mode}, sc:{search_char}") + logger.info(f"search_mode:{search_mode}, search_char:{search_char}") #查观星三拼 if search_mode in ["g", "G", "观", "观星三拼"]: re_msg_u = "" @@ -219,13 +220,13 @@ def dict_change(dict_str: str, column: list):#字典处理 column = [字(列 return result def load_dict(dict_path: str, dict_name: str, column = [0, 1]): - print("装载字典……") + logger.info("加载字典……") try: dt_s = readtxt(dict_path, dict_name) dt = dict_change(dt_s, column) - print(f"{dict_name}装载完成!") + logger.info(f"{dict_name}加载完成!") except (Exception, RuntimeError) as e: - print(f"加载{dict_name}字典时发生错误:{e}") + logger.error(f"加载{dict_name}字典时发生错误:{e}") return None return dt @@ -237,7 +238,7 @@ def find_char(dt: dict, ch: str): return '或'.join(tb) def load_img_dict(dict_path: str, sub_path: str): - print("装载字典……") + logger.info("加载字典……") dt_p = os.path.join(dict_path, sub_path) dt = {} try: @@ -245,9 +246,9 @@ def load_img_dict(dict_path: str, sub_path: str): key = os.path.splitext(name)[0] value = os.path.join(dt_p, name) dt[key] = value - print(f"{sub_path}装载完成!") + logger.info(f"{sub_path}加载完成!") except (Exception, RuntimeError) as e: - print(f"加载{sub_path}字典时发生错误:{e}") + logger.error(f"加载{sub_path}字典时发生错误:{e}") return dt def find_img(dt: dict, ch: str): diff --git a/modules/SixtySecNews/SixtySecNews.py b/modules/SixtySecNews/SixtySecNews.py index 1b7efa1..2938eb0 100644 --- a/modules/SixtySecNews/SixtySecNews.py +++ b/modules/SixtySecNews/SixtySecNews.py @@ -1,4 +1,5 @@ import asyncio +from loguru import logger from bot_init import BOT from modules.base.message_queue import MessageQueue @@ -45,7 +46,7 @@ async def send_news_img(app: Ariadne): calendar_img = await get_calendar_img() # 遇到错误将隔30s重试 while type(news_img) != bytes and i < 16: - print(f"请求新闻图片失败,错误码{news_img},重试{i}…") + logger.info(f"请求新闻图片失败,错误码{news_img},重试{i}…") news_img = await get_news_img() i += 1 await asyncio.sleep(30) @@ -69,7 +70,7 @@ async def send_news_img(app: Ariadne): ) ) except: - print("定时发送60秒看世界新闻 发送消息时错误") + logger.error("定时发送60秒看世界新闻 发送消息时错误") # 管理员指令: @channel.use( diff --git a/modules/Yiyan/get_yiyan.py b/modules/Yiyan/get_yiyan.py index 7d6c880..0670256 100644 --- a/modules/Yiyan/get_yiyan.py +++ b/modules/Yiyan/get_yiyan.py @@ -1,5 +1,6 @@ import aiohttp import asyncio +from loguru import logger # 获取一言 @@ -26,7 +27,7 @@ async def get_yiyan(c: list[str], encode: str, min_length=1, max_length=100): elif encode == 'json': return await r.json() else: - print('指定的返回格式不合法') + logger.error('指定的返回格式不合法') return None else: return r.status diff --git a/modules/base/check.py b/modules/base/check.py index 14f4f13..da2de19 100644 --- a/modules/base/check.py +++ b/modules/base/check.py @@ -1,5 +1,6 @@ import asyncio from datetime import datetime +from loguru import logger from graia.ariadne import Ariadne from graia.ariadne.message.chain import MessageChain @@ -23,7 +24,7 @@ def cool_down(prev_time: datetime, second: int): second 延时的秒数\n """ async def cool_down_time(app: Ariadne, target: Group | Friend): - print(prev_time) + logger.debug(f"prev_time={prev_time}") if prev_time == None: return elif get_delay(prev_time) < second: @@ -52,7 +53,7 @@ def check_frequency(fqc_dict: dict, max_frequency: int): max_frequency: 允许的最大频率,单位:秒/次\n """ async def check_frequency_deco(app: Ariadne, group: Group, member: Member): - print(f"fqc_dict={fqc_dict}") + logger.debug(f"fqc_dict={fqc_dict}") fqc = frequency(fqc_dict, member.id) if fqc == -1: # 第一次的请求 return diff --git a/modules/base/get_quote_message.py b/modules/base/get_quote_message.py index da8ba1a..db80c3d 100644 --- a/modules/base/get_quote_message.py +++ b/modules/base/get_quote_message.py @@ -2,6 +2,8 @@ from graia.ariadne.model import Group, Friend from graia.ariadne.message.element import Quote +from loguru import logger + async def get_quote_message(message_id: int, target: Group | Friend): """ message_id: 消息的id号 @@ -16,5 +18,5 @@ async def get_quote_message(message_id: int, target: Group | Friend): quote_message = await Ariadne.current().get_message_from_id(message=current_message.quote.id, target=target) return quote_message except: - print("get quote_message failed! return current_message's quote.") + logger.warning("get quote_message failed! return current_message's quote.") return current_message.quote \ No newline at end of file diff --git a/modules/base/message_queue.py b/modules/base/message_queue.py index 683f720..1d7c6be 100644 --- a/modules/base/message_queue.py +++ b/modules/base/message_queue.py @@ -2,8 +2,8 @@ # 2023-06-01 Shitlime: 为了躲避风控,需要收集全局的消息发送,并进行排队延时 import asyncio - import random +from loguru import logger from graia.ariadne.app import Ariadne @@ -24,7 +24,7 @@ def __new__(cls): return cls.__instance async def send_message_worker(self): - print(f"消息队列开始工作,当前延时{msg_delay}秒") + logger.info(f"消息队列开始工作,当前延时{msg_delay}秒") while True: # 从消息队列中取出待发送的消息 app, target, message, quote = await self.queue.get() @@ -39,7 +39,7 @@ async def send_message_worker(self): # 原始内容发送 await app.send_message(target, message) except Exception as e: - print(f"ERROR: {e}") + logger.error(f"消息队列发生了异常:{e}") await asyncio.sleep(msg_delay) async def send_message(self, app: Ariadne, target, message, *, quote = False,): diff --git a/modules/scheduler/TrimeNightlyUpload/get_trime_nightly.py b/modules/scheduler/TrimeNightlyUpload/get_trime_nightly.py index ed60f9d..1133cf1 100644 --- a/modules/scheduler/TrimeNightlyUpload/get_trime_nightly.py +++ b/modules/scheduler/TrimeNightlyUpload/get_trime_nightly.py @@ -2,6 +2,7 @@ import aiohttp import datetime import pytz +from loguru import logger from .OutdatedAssetsException import OutdatedAssetsException @@ -38,7 +39,7 @@ async def get_info() -> dict: if type(infos) == dict: return infos else: - print(f"获取trime nightly下载链接出错!状态码:{infos}") + logger.error(f"获取trime nightly下载链接出错!状态码:{infos}") async def get_file_bytes(url: str): """ @@ -50,18 +51,18 @@ async def get_file_bytes(url: str): async with aiohttp.request("GET", url=url) as r: return await r.read() except TimeoutError: - print(f"下载文件数据超时 第{count}次") + logger.info(f"下载文件数据超时 第{count}次") await asyncio.sleep(4) finally: count += 1 -async def test(): - info = await get_info() - data = await get_file_bytes(list(info['assets'].items())[0][1]) - print(data) - print(len(data)) - print(info['body']) - if __name__ == "__main__": + async def test(): + info = await get_info() + data = await get_file_bytes(list(info['assets'].items())[0][1]) + print(data) + print(len(data)) + print(info['body']) + loop = asyncio.get_event_loop() loop.run_until_complete(test()) \ No newline at end of file diff --git a/modules/scheduler/TrimeNightlyUpload/trime_nightly_upload.py b/modules/scheduler/TrimeNightlyUpload/trime_nightly_upload.py index d99e519..ee9833f 100644 --- a/modules/scheduler/TrimeNightlyUpload/trime_nightly_upload.py +++ b/modules/scheduler/TrimeNightlyUpload/trime_nightly_upload.py @@ -1,6 +1,7 @@ import re import datetime import asyncio +from loguru import logger from bot_init import BOT from graia.saya import Channel @@ -35,7 +36,7 @@ async def upload_trime_nightly(app: Ariadne): try: all_info = await get_info() except OutdatedAssetsException as e: - print(f"{e.message} 第{count}次 120s后重新获取") + logger.info(f"{e.message} 第{count}次 120s后重新获取") await asyncio.sleep(120) finally: count += 1 diff --git a/modules/scheduler/new_year.py b/modules/scheduler/new_year.py index 5f87a13..832259c 100644 --- a/modules/scheduler/new_year.py +++ b/modules/scheduler/new_year.py @@ -1,3 +1,5 @@ +from loguru import logger + from bot_init import BOT from graia.saya import Channel from graia.scheduler import timers @@ -36,4 +38,4 @@ async def send_happy_new_year(app: Ariadne): message= msg ) except: - print("定时发送消息错误") \ No newline at end of file + logger.error("定时发送消息错误") \ No newline at end of file