Skip to content

Commit

Permalink
cron: add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
shitlime committed Apr 14, 2024
1 parent 9647f5a commit dc08d48
Show file tree
Hide file tree
Showing 22 changed files with 74 additions and 51 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ __pycache__
resources/font/*
resources/search_char/private/*
.pdm.toml
.pdm-python
1 change: 0 additions & 1 deletion .pdm-python

This file was deleted.

5 changes: 3 additions & 2 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
6 changes: 4 additions & 2 deletions bot_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import yaml
import platform

from loguru import logger

class BotData(yaml.YAMLObject):
yaml_tag = '!BotData'
yaml_loader = yaml.SafeLoader
Expand Down Expand Up @@ -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]
Expand Down
3 changes: 2 additions & 1 deletion modules/ACGimg/ACGimg.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from loguru import logger

from bot_init import BOT
from modules.base.message_queue import MessageQueue
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion modules/ACGimg/get_acg_img.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import aiohttp
import asyncio

from loguru import logger

# TEST
from pathlib import Path

Expand All @@ -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
Expand Down
9 changes: 5 additions & 4 deletions modules/Admin/recall_message.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
# 撤回后寻找下一条消息
Expand Down
3 changes: 2 additions & 1 deletion modules/Bilibili/get_video_info.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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()
Expand Down
15 changes: 8 additions & 7 deletions modules/Bilibili/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
# 输入信息
Expand All @@ -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:
# 输入信息
Expand All @@ -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("输入视屏链接:")
Expand Down
5 changes: 3 additions & 2 deletions modules/BreakTofu/break_tofu.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
import asyncio
from loguru import logger

from bot_init import BOT
from modules.base.message_queue import MessageQueue
Expand Down Expand Up @@ -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))),
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion modules/BreakTofu/char2image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 4 additions & 1 deletion modules/BreakTofu/guess_tofu.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -349,6 +350,7 @@ async def waiter(waiter_events: GroupMessage):
else:
# 空
scroes[player.id] = gt.score
logger.info(f"猜豆腐-竞赛胜利玩家:{player}")
return 0 # 答对0
else:
# 答错
Expand Down Expand Up @@ -572,6 +574,7 @@ async def waiter(waiter_events: GroupMessage):
else:
# 空
scroes[player.id] = 1
logger.info(f"猜豆腐-无尽胜利玩家:{player}")
return 0 # 答对0
else:
# 答错
Expand Down
2 changes: 1 addition & 1 deletion modules/BreakTofu/guess_tofu_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 8 additions & 7 deletions modules/SearchThing/search_char.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = ""
Expand Down Expand Up @@ -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

Expand All @@ -237,17 +238,17 @@ 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:
for name in os.listdir(dt_p):
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):
Expand Down
5 changes: 3 additions & 2 deletions modules/SixtySecNews/SixtySecNews.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from loguru import logger

from bot_init import BOT
from modules.base.message_queue import MessageQueue
Expand Down Expand Up @@ -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)
Expand All @@ -69,7 +70,7 @@ async def send_news_img(app: Ariadne):
)
)
except:
print("定时发送60秒看世界新闻 发送消息时错误")
logger.error("定时发送60秒看世界新闻 发送消息时错误")

# 管理员指令:
@channel.use(
Expand Down
3 changes: 2 additions & 1 deletion modules/Yiyan/get_yiyan.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import aiohttp
import asyncio
from loguru import logger

# 获取一言

Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions modules/base/check.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion modules/base/get_quote_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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号
Expand All @@ -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
Loading

0 comments on commit dc08d48

Please sign in to comment.