Skip to content

Commit

Permalink
更新依赖和工具类
Browse files Browse the repository at this point in the history
  • Loading branch information
NekoRabi committed Jun 16, 2023
1 parent eb1dbec commit c75fab5
Show file tree
Hide file tree
Showing 6 changed files with 365 additions and 157 deletions.
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ uvicorn~=0.17.6
tencentcloud-sdk-python==3.0.638
pytz~=2022.1
websockets~=10.3
pyecharts~=2.0.3
snapshot-selenium~=0.0.2
248 changes: 128 additions & 120 deletions utils/Logger.py
Original file line number Diff line number Diff line change
@@ -1,120 +1,128 @@
import logging
from logging.handlers import TimedRotatingFileHandler
from utils.cfg_loader import read_file

import time
import os

__all__ = ['root_logger', 'create_logger']


def make_dir(make_dir_path):
path = make_dir_path.strip()
if not os.path.exists(path):
os.makedirs(path)
return path


_cfg = read_file(r'./config/config.yml')


def log_config():
LOG_FORMAT = "[%(asctime)s][%(levelname)s]: %(message)s"
fname = time.strftime("news_%Y%m%d.log", time.localtime())
level = logging.INFO
logging.basicConfig(level=level, format=LOG_FORMAT)

# 创建TimedRotatingFileHandler对象,每天生成一个文件
log_file_handler = TimedRotatingFileHandler(filename='test.log', when="D", interval=1, backupCount=3)
# 设置日志打印格式
formatter = logging.Formatter(LOG_FORMAT)
log_file_handler.setFormatter(formatter)
logging.getLogger('').addHandler(log_file_handler)


def create_logger(log_level: str = 'INFO', logger_name: str = None, log_file_folder: str = r'./log',
fmt='%(asctime)s - %(name)s - %(levelname)-6s - %(message)s', date_fmt='%Y-%m-%d %H:%M:%S',
timer_config=None):
"""
创建Logger
Args:
log_level: 日志等级
logger_name: Logger_Name,默认root
log_file_folder: 日志存储路径
fmt: 日志输出格式
date_fmt: 时间格式
timer_config: Timer配置
Returns:Logger
"""
if timer_config is None:
timer_config = dict(when="D", interval=1, backupCount=0)
project_name = "log"
folder_format = time.strftime('%Y-%m', time.localtime(time.time()))
log_file_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'
# log_file_folder = os.path.abspath(
# os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + os.sep + project_name + os.sep + folder_format
make_dir(log_file_folder)
log_file_str = log_file_folder + os.sep + log_file_name
if logger_name:
logger = logging.getLogger(logger_name)
else:
logger = logging.getLogger()
loglevel = log_level.upper()
if loglevel in ["CRITICAL", "FATAL"]:
loggerlevel = logging.CRITICAL
elif loglevel == "ERROR":
loggerlevel = logging.ERROR
elif loglevel == "INFO":
loggerlevel = logging.INFO
elif loglevel in ["WARNING", "WARN"]:
loggerlevel = logging.WARNING
else:
loggerlevel = logging.DEBUG
logger.setLevel(loggerlevel)
# logger_format = logging.Formatter(
# fmt='%(asctime)s - %(name)s - %(levelname)-9s - %(filename)-8s : %(lineno)s line - %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S')
logger_format = logging.Formatter(
fmt=fmt,
datefmt=date_fmt)

timerhandler = TimedRotatingFileHandler(filename=log_file_str, when=timer_config.get('when', 'D'),
interval=timer_config.get('interval', 1),
backupCount=timer_config.get('backupCount', 0),
encoding='utf-8')
timerhandler.setFormatter(logger_format)

logger.addHandler(timerhandler)

return logger


def getQQlogger():
project_name = "qq-log"
folder_format = time.strftime('%Y-%m', time.localtime(time.time()))
log_file_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'
# log_file_folder = os.path.abspath(
# os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + os.sep + project_name + os.sep + folder_format
log_file_folder = r'./qq-log'
make_dir(log_file_folder)
log_file_str = log_file_folder + os.sep + log_file_name

logger = logging.getLogger("qqlogger")
logger.setLevel(20)
logger_format = logging.Formatter(fmt='time="%(asctime)s" - level=%(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')

timerhandler = TimedRotatingFileHandler(filename=log_file_str, when="D", interval=1, backupCount=0,
encoding='utf-8')
timerhandler.setFormatter(logger_format)

logger.addHandler(timerhandler)

return logger


root_logger = create_logger(_cfg.get('loglevel', 'INFO'))
# QQ_logger = getQQlogger()
import logging
from logging.handlers import TimedRotatingFileHandler
from utils.cfg_loader import read_file

import time
import os

__all__ = ['root_logger', 'create_logger']


def make_dir(make_dir_path):
path = make_dir_path.strip()
if not os.path.exists(path):
os.makedirs(path)
return path


_cfg = read_file(r'./config/config.yml')


def log_config():
LOG_FORMAT = "[%(asctime)s][%(levelname)s]: %(message)s"
fname = time.strftime("news_%Y%m%d.log", time.localtime())
level = logging.INFO
logging.basicConfig(level=level, format=LOG_FORMAT)

# 创建TimedRotatingFileHandler对象,每天生成一个文件
log_file_handler = TimedRotatingFileHandler(filename='test.log', when="D", interval=1, backupCount=3)
# 设置日志打印格式
formatter = logging.Formatter(LOG_FORMAT)
log_file_handler.setFormatter(formatter)
logging.getLogger('').addHandler(log_file_handler)


def create_logger(log_level: str = 'INFO', logger_name: str = None, log_file_folder: str = r'./log',
fmt='%(asctime)s - %(name)s - %(levelname)-6s - %(message)s', date_fmt='%Y-%m-%d %H:%M:%S',
timer_config=None):
"""
创建Logger
Args:
log_level: 日志等级
logger_name: Logger_Name,默认root
log_file_folder: 日志存储路径
fmt: 日志输出格式
date_fmt: 时间格式
timer_config: Timer配置
Returns:Logger
"""
if timer_config is None:
timer_config = dict(when="D", interval=1, backupCount=0)
if logger_name:
logger = logging.getLogger(logger_name)
else:
logger = logging.getLogger()
loglevel = log_level.upper()
if loglevel in ["CRITICAL", "FATAL"]:
loggerlevel = logging.CRITICAL
elif loglevel == "ERROR":
loggerlevel = logging.ERROR
elif loglevel == "INFO":
loggerlevel = logging.INFO
elif loglevel in ["WARNING", "WARN"]:
loggerlevel = logging.WARNING
else:
loggerlevel = logging.DEBUG
logger.setLevel(loggerlevel)
# logger_format = logging.Formatter(
# fmt='%(asctime)s - %(name)s - %(levelname)-9s - %(filename)-8s : %(lineno)s line - %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S')
logger_format = logging.Formatter(
fmt=fmt,
datefmt=date_fmt)

timerhandler = TimedRotatingFileHandler(filename=_get_rootlog_filename(log_file_folder),
when=timer_config.get('when', 'D'),
interval=timer_config.get('interval', 1),
backupCount=timer_config.get('backupCount', 0),
encoding='utf-8')
timerhandler.setFormatter(logger_format)

logger.addHandler(timerhandler)

return logger


def _get_rootlog_filename(log_file_folder):
"""自动生成日志文件名"""
# project_name = "log"
folder_format = time.strftime('%Y-%m', time.localtime(time.time()))
log_file_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'
# log_file_folder = os.path.abspath(
# os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + os.sep + project_name + os.sep + folder_format
make_dir(log_file_folder)
log_file_str = log_file_folder + os.sep + log_file_name
return log_file_str


# def getQQlogger():
# """已弃用的聊天记录日志记录器"""
# project_name = "qq-log"
# # log_file_folder = os.path.abspath(
# # os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + os.sep + project_name + os.sep + folder_format
#
# log_file_folder = r'./qq-log'
# make_dir(log_file_folder)
# folder_format = time.strftime('%Y-%m', time.localtime(time.time()))
# log_file_name = time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log'
# log_file_str = log_file_folder + os.sep + log_file_name
# logger = logging.getLogger("qqlogger")
# logger.setLevel(20)
# logger_format = logging.Formatter(fmt='time="%(asctime)s" - level=%(levelname)s - %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S')
#
# timerhandler = TimedRotatingFileHandler(filename=log_file_str, when="D", interval=1, backupCount=1,
# encoding='utf-8')
# timerhandler.setFormatter(logger_format)
#
# logger.addHandler(timerhandler)
#
# return logger


root_logger = create_logger(_cfg.get('loglevel', 'INFO'))
# QQ_logger = getQQlogger()
# 每隔 1000 Byte 划分一个日志文件,备份文件为 3 个
18 changes: 12 additions & 6 deletions utils/MessageChainBuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
__all__ = ['messagechain_builder']


async def messagechain_builder(reply_choices: list = None, text: str = None, imgpath: str = None, rndimg=False,
async def messagechain_builder(reply_choices: list = None, text: str = None, imgpath: Union[str, list] = None,
rndimg=False,
imgurl: str = None, imgbase64=None, at: Union[list, int] = None,
atall=False) -> MessageChain:
"""
Expand Down Expand Up @@ -63,15 +64,20 @@ async def messagechain_builder(reply_choices: list = None, text: str = None, img
msgchain.append(
await Image.from_local(
filename=f"./data/reply/img/{replydata['replyimgpath']}/{random.choice(replydata['img'])}"))
if imgpath:
if reply_choices or text:
msgchain.append(Plain("\n"))
msgchain.append(
await Image.from_local(filename=f"{imgpath}"))
if imgbase64:
if reply_choices or text:
msgchain.append(Plain("\n"))
msgchain.append(Image(base64=imgbase64))
if imgpath:
if reply_choices or text:
msgchain.append(Plain("\n"))
if isinstance(imgpath, str):
msgchain.append(
await Image.from_local(filename=f"{imgpath}"))
elif isinstance(imgpath, list):
for path in imgpath:
msgchain.append(
await Image.from_local(filename=f"{path}"))
if imgurl:
if reply_choices or text:
msgchain.append(Plain("\n"))
Expand Down
22 changes: 11 additions & 11 deletions utils/MessageChainSender.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
:Create: 2022/8/16 16:15
:Update: /
:Describe: 消息链发送工具
:Version: 0.0.1
:Version: 0.0.2
"""
import logging
import time
import traceback
from typing import Union
Expand All @@ -27,7 +26,7 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e
grouptarget: int = None, friendtarget: int = None, errortext: str = None) -> int:
"""
消息链发送工具\n
event,grouptarget,friendtarget三者有一个就行
event,grouptarget,friendtarget三者有一个就行\n
Args:
msg: 消息,可以是字符串、消息组件、消息链
Expand Down Expand Up @@ -58,9 +57,9 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e
onlyImg = True
try:
if event:
if isinstance(event,GroupMessage):
if isinstance(event, GroupMessage):
grouptarget = event.group.id
elif isinstance(event,FriendMessage):
elif isinstance(event, FriendMessage):
friendtarget = event.sender.id
# res = await bot.send(event, msg)
# target = event
Expand Down Expand Up @@ -94,7 +93,8 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e
elif event:
await bot.send(event, await messagechain_builder(text=imgSendErrText, rndimg=True))
elif friendtarget:
await bot.send_friend_message(friendtarget, await messagechain_builder(text=imgSendErrText, rndimg=True))
await bot.send_friend_message(friendtarget,
await messagechain_builder(text=imgSendErrText, rndimg=True))
except mirai.exceptions.ApiError as _e:
# 消息发送失败时,进行日志记录,并尝试告诉机器人主人,每次发送CD 3600 s
nowtime = int(time.time())
Expand All @@ -103,19 +103,19 @@ async def messagechain_sender(msg: Union[MessageChain, str, MessageComponent], e
if nowtime - last_time > 3600:
_last_error_message['groupmessage'] = dict(time=nowtime, target=target, message=msg,
error='Bot被禁言')
await bot.send_friend_message(master, f"{target.group.id}群消息发送失败,疑似被禁言")
print('Bot被禁言')
root_logger.error('Bot发送消息失败,Bot被禁言')
await bot.send_friend_message(master, f"{target} 发送消息失败,可能被禁言")
print(f"向 {target} 发送消息失败,可能被禁言")
root_logger.error(f"向 {target} 发送消息失败,可能被禁言")
else:
if nowtime - last_time > 3600:
_last_error_message['groupmessage'] = dict(time=nowtime, target=target, message=msg, error=_e)
await bot.send_friend_message(master, f"群消息发送失败,可能被群消息风\n{_e}")
await bot.send_friend_message(master, f"群消息发送失败,可能被群消息风控\n{_e}")
print(f'Bot发送消息失败,MiraI错误码{_e}')
root_logger.error(f'Bot发送消息失败,Mirai错误码{_e}')
res = -1
except Exception as _e:
traceback.print_exc()
logging.error(f'出现未知错误:{_e}')
root_logger.error(f'出现未知错误:{_e}')
nowtime = int(time.time())
last_time = _last_error_message.get('groupmessage').get('time', 0)
if nowtime - last_time > 3600:
Expand Down
Loading

0 comments on commit c75fab5

Please sign in to comment.