🎨 Improve code quality

This commit is contained in:
洛水居室 2022-12-25 21:26:08 +08:00 committed by GitHub
parent e5ab9d71ca
commit 6552606cc7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 100 additions and 99 deletions

View File

@ -277,7 +277,7 @@ class _AvatarAssets(_AssetsService):
yield str(AMBR_HOST.join(f"assets/UI/{self.game_name_map[item]}.png")) yield str(AMBR_HOST.join(f"assets/UI/{self.game_name_map[item]}.png"))
async def _get_from_enka(self, item: str) -> AsyncIterator[str | None]: async def _get_from_enka(self, item: str) -> AsyncIterator[str | None]:
if (item_id := self.game_name_map.get(item, None)) is not None: if (item_id := self.game_name_map.get(item)) is not None:
yield str(ENKA_HOST.join(f"ui/{item_id}.png")) yield str(ENKA_HOST.join(f"ui/{item_id}.png"))
@cached_property @cached_property

View File

@ -106,7 +106,7 @@ class Bot:
import_module(pkg) # 导入插件 import_module(pkg) # 导入插件
except Exception as e: # pylint: disable=W0703 except Exception as e: # pylint: disable=W0703
logger.exception( logger.exception(
f'在导入文件 "{pkg}" 的过程中遇到了错误: \n[red bold]{type(e).__name__}: {e}[/]', extra={"markup": True} '在导入文件 "%s" 的过程中遇到了错误 [red bold]%s[/]', pkg, type(e).__name__, exc_info=e, extra={"markup": True}
) )
continue # 如有错误则继续 continue # 如有错误则继续
callback_dict: Dict[int, List[Callable]] = {} callback_dict: Dict[int, List[Callable]] = {}
@ -123,7 +123,7 @@ class Bot:
self.app.add_handler(handler, group=-1) self.app.add_handler(handler, group=-1)
self.app.add_handlers(handlers) self.app.add_handlers(handlers)
if handlers: if handlers:
logger.debug(f'插件 "{path}" 添加了 {len(handlers)} 个 handler ') logger.debug('插件 "%s" 添加了 %s 个 handler ', path, len(handlers))
# noinspection PyProtectedMember # noinspection PyProtectedMember
for priority, callback in plugin._new_chat_members_handler_funcs(): # pylint: disable=W0212 for priority, callback in plugin._new_chat_members_handler_funcs(): # pylint: disable=W0212
@ -135,14 +135,14 @@ class Bot:
for callback, block in error_handlers.items(): for callback, block in error_handlers.items():
self.app.add_error_handler(callback, block) self.app.add_error_handler(callback, block)
if error_handlers: if error_handlers:
logger.debug(f'插件 "{path}" 添加了 {len(error_handlers)} 个 error handler') logger.debug('插件 "%s" 添加了 %s 个 error handler ', path, len(error_handlers))
if jobs := plugin.jobs: if jobs := plugin.jobs:
logger.debug(f'插件 "{path}" 添加了 {len(jobs)} 个任务') logger.debug('插件 "%s" 添加了 %s 个 jobs ', path, len(jobs))
logger.success(f'插件 "{path}" 载入成功') logger.success('插件 "%s" 载入成功', path)
except Exception as e: # pylint: disable=W0703 except Exception as e: # pylint: disable=W0703
logger.exception( logger.exception(
f'在安装插件 "{path}" 的过程中遇到了错误: \n[red bold]{type(e).__name__}: {e}[/]', extra={"markup": True} '在安装插件 "%s" 的过程中遇到了错误 [red bold]%s[/]', path, type(e).__name__, exc_info=e, extra={"markup": True}
) )
if callback_dict: if callback_dict:
num = sum(len(callback_dict[i]) for i in callback_dict) num = sum(len(callback_dict[i]) for i in callback_dict)
@ -157,7 +157,9 @@ class Bot:
MessageHandler(callback=_new_chat_member_callback, filters=StatusUpdate.NEW_CHAT_MEMBERS, block=False) MessageHandler(callback=_new_chat_member_callback, filters=StatusUpdate.NEW_CHAT_MEMBERS, block=False)
) )
logger.success( logger.success(
f"成功添加了 {num} 个针对 [blue]{StatusUpdate.NEW_CHAT_MEMBERS}[/] 的 [blue]MessageHandler[/]", "成功添加了 %s 个针对 [blue]%s[/] 的 [blue]MessageHandler[/]",
num,
StatusUpdate.NEW_CHAT_MEMBERS,
extra={"markup": True}, extra={"markup": True},
) )
# special handler # special handler
@ -175,9 +177,9 @@ class Bot:
import_module(pkg) import_module(pkg)
except Exception as e: # pylint: disable=W0703 except Exception as e: # pylint: disable=W0703
logger.exception( logger.exception(
f'在导入文件 "{pkg}" 的过程中遇到了错误: \n[red bold]{type(e).__name__}: {e}[/]', extra={"markup": True} '在导入文件 "%s" 的过程中遇到了错误 [red bold]%s[/]', pkg, type(e).__name__, exc_info=e, extra={"markup": True}
) )
continue raise SystemExit from e
for base_service_cls in Service.__subclasses__(): for base_service_cls in Service.__subclasses__():
try: try:
if hasattr(base_service_cls, "from_config"): if hasattr(base_service_cls, "from_config"):
@ -185,10 +187,10 @@ class Bot:
else: else:
instance = self.init_inject(base_service_cls) instance = self.init_inject(base_service_cls)
await instance.start() await instance.start()
logger.success(f'服务 "{base_service_cls.__name__}" 初始化成功') logger.success('服务 "%s" 初始化成功', base_service_cls.__name__)
self._services.update({base_service_cls: instance}) self._services.update({base_service_cls: instance})
except Exception as e: except Exception as e:
logger.exception(f'服务 "{base_service_cls.__name__}" 初始化失败: {e}') logger.error('服务 "%s" 初始化失败', base_service_cls.__name__)
raise SystemExit from e raise SystemExit from e
async def start_services(self): async def start_services(self):
@ -201,7 +203,11 @@ class Bot:
import_module(pkg) import_module(pkg)
except Exception as e: # pylint: disable=W0703 except Exception as e: # pylint: disable=W0703
logger.exception( logger.exception(
f'在导入文件 "{pkg}" 的过程中遇到了错误: \n[red bold]{type(e).__name__}: {e}[/]', extra={"markup": True} '在导入文件 "%s" 的过程中遇到了错误 [red bold]%s[/]',
pkg,
type(e).__name__,
exc_info=e,
extra={"markup": True},
) )
continue continue
@ -218,11 +224,11 @@ class Bot:
await service.stop() await service.stop()
else: else:
service.stop() service.stop()
logger.success(f'服务 "{service.__class__.__name__}" 关闭成功') logger.success('服务 "%s" 关闭成功', service.__class__.__name__)
except CancelledError: except CancelledError:
logger.warning(f'服务 "{service.__class__.__name__}" 关闭超时') logger.warning('服务 "%s" 关闭超时', service.__class__.__name__)
except Exception as e: # pylint: disable=W0703 except Exception as e: # pylint: disable=W0703
logger.exception(f'服务 "{service.__class__.__name__}" 关闭失败: \n{type(e).__name__}: {e}') logger.exception('服务 "%s" 关闭失败', service.__class__.__name__, exc_info=e)
async def _post_init(self, context: CallbackContext) -> NoReturn: async def _post_init(self, context: CallbackContext) -> NoReturn:
logger.info("开始初始化 genshin.py 相关资源") logger.info("开始初始化 genshin.py 相关资源")
@ -276,7 +282,6 @@ class Bot:
logger.warning("连接至 [blue]telegram[/] 服务器失败,正在重试", extra={"markup": True}) logger.warning("连接至 [blue]telegram[/] 服务器失败,正在重试", extra={"markup": True})
continue continue
except NetworkError as e: except NetworkError as e:
logger.exception()
if "SSLZeroReturnError" in str(e): if "SSLZeroReturnError" in str(e):
logger.error("代理服务出现异常, 请检查您的代理服务是否配置成功.") logger.error("代理服务出现异常, 请检查您的代理服务是否配置成功.")
else: else:
@ -285,7 +290,7 @@ class Bot:
except (SystemExit, KeyboardInterrupt): except (SystemExit, KeyboardInterrupt):
pass pass
except Exception as e: # pylint: disable=W0703 except Exception as e: # pylint: disable=W0703
logger.exception(f"BOT 执行过程中出现错误: {e}") logger.exception("BOT 执行过程中出现错误", exc_info=e)
finally: finally:
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
loop.run_until_complete(self.stop_services()) loop.run_until_complete(self.stop_services())

View File

@ -118,14 +118,14 @@ async def update_metadata_from_github(overwrite: bool = True):
data = json.dumps(data, ensure_ascii=False) data = json.dumps(data, ensure_ascii=False)
await file.write(data) await file.write(data)
return data return data
except RemoteProtocolError as e: except RemoteProtocolError as exc:
logger.warning(f"在从 {host} 下载元数据的过程中遇到了错误: {repr(e)}") logger.warning("在从 %s 下载元数据的过程中遇到了错误: %s", host, str(exc))
continue continue
except Exception as e: except Exception as exc:
if num != len(hosts) - 1: if num != len(hosts) - 1:
logger.error(f"在从 {host} 下载元数据的过程中遇到了错误: {repr(e)}") logger.error("在从 %s 下载元数据的过程中遇到了错误: %s", host, str(exc))
continue continue
raise e raise exc
def make_github_fast(url: str) -> str: def make_github_fast(url: str) -> str:

View File

@ -70,22 +70,21 @@ class AvatarListPlugin(Plugin, BasePlugin):
) )
async def get_avatar_data(self, character: Character, client: Client) -> Optional["AvatarData"]: async def get_avatar_data(self, character: Character, client: Client) -> Optional["AvatarData"]:
detail = None
for _ in range(5): for _ in range(5):
try: try:
detail = await client.get_character_details(character) detail = await client.get_character_details(character)
except Exception as e: # pylint: disable=W0703 except Exception as exc: # pylint: disable=W0703
if isinstance(e, GenshinException) and "Too Many Requests" in e.msg: if isinstance(exc, GenshinException) and "Too Many Requests" in exc.msg:
await asyncio.sleep(0.2) await asyncio.sleep(0.2)
continue continue
if character.name == "旅行者": if character.name == "旅行者":
logger.debug(f"解析旅行者数据时遇到了错误:{e}") logger.debug("解析旅行者数据时遇到了错误:%s", str(exc))
return None return None
raise e raise exc
else: else:
break break
else: else:
logger.warning(f"解析[bold]{character.name}[/]的数据时遇到了 Too Many Requests 错误", extra={"markup": True}) logger.warning("解析[bold]%s[/]的数据时遇到了 Too Many Requests 错误", character.name, extra={"markup": True})
return None return None
if character.id == 10000005: # 针对男草主 if character.id == 10000005: # 针对男草主
talents = [] talents = []
@ -134,43 +133,43 @@ class AvatarListPlugin(Plugin, BasePlugin):
async def get_final_data(self, client: Client, characters: Sequence[Character], update: Update): async def get_final_data(self, client: Client, characters: Sequence[Character], update: Update):
try: try:
response = await self.enka_client.fetch_user(client.uid) response = await self.enka_client.fetch_user(client.uid)
namecard = (await self.assets_service.namecard(response.player.namecard.id).navbar()).as_uri() name_card = (await self.assets_service.namecard(response.player.namecard.id).navbar()).as_uri()
avatar = (await self.assets_service.avatar(response.player.avatar.id).icon()).as_uri() avatar = (await self.assets_service.avatar(response.player.avatar.id).icon()).as_uri()
nickname = response.player.nickname nickname = response.player.nickname
if response.player.avatar.id in [10000005, 10000007]: if response.player.avatar.id in [10000005, 10000007]:
rarity = 5 rarity = 5
else: else:
rarity = {k: v["rank"] for k, v in AVATAR_DATA.items()}[str(response.player.avatar.id)] rarity = {k: v["rank"] for k, v in AVATAR_DATA.items()}[str(response.player.avatar.id)]
except Exception as e: # pylint: disable=W0703 except Exception as exc: # pylint: disable=W0703
logger.debug(f"enka 请求失败: {e}") logger.error("enka 请求失败: %s", str(exc))
choices = ArkoWrapper(characters).filter(lambda x: x.friendship == 10) # 筛选出好感满了的角色 choices = ArkoWrapper(characters).filter(lambda x: x.friendship == 10) # 筛选出好感满了的角色
if choices.length == 0: # 若没有满好感角色、则以好感等级排序 if choices.length == 0: # 若没有满好感角色、则以好感等级排序
choices = ArkoWrapper(characters).sort(lambda x: x.friendship, reverse=True) choices = ArkoWrapper(characters).sort(lambda x: x.friendship, reverse=True)
namecard_choices = ( # 找到与角色对应的满好感名片ID name_card_choices = ( # 找到与角色对应的满好感名片ID
ArkoWrapper(choices) ArkoWrapper(choices)
.map(lambda x: next(filter(lambda y: y["name"].split(".")[0] == x.name, NAMECARD_DATA.values()), None)) .map(lambda x: next(filter(lambda y: y["name"].split(".")[0] == x.name, NAMECARD_DATA.values()), None))
.filter(lambda x: x) .filter(lambda x: x)
.map(lambda x: x["id"]) .map(lambda x: x["id"])
) )
namecard = (await self.assets_service.namecard(namecard_choices[0]).navbar()).as_uri() name_card = (await self.assets_service.namecard(name_card_choices[0]).navbar()).as_uri()
avatar = (await self.assets_service.avatar(cid := choices[0].id).icon()).as_uri() avatar = (await self.assets_service.avatar(cid := choices[0].id).icon()).as_uri()
nickname = update.effective_user.full_name nickname = update.effective_user.full_name
if cid in [10000005, 10000007]: if cid in [10000005, 10000007]:
rarity = 5 rarity = 5
else: else:
rarity = {k: v["rank"] for k, v in AVATAR_DATA.items()}[str(cid)] rarity = {k: v["rank"] for k, v in AVATAR_DATA.items()}[str(cid)]
return namecard, avatar, nickname, rarity return name_card, avatar, nickname, rarity
async def get_default_final_data(self, characters: Sequence[Character], update: Update): async def get_default_final_data(self, characters: Sequence[Character], update: Update):
nickname = update.effective_user.full_name nickname = update.effective_user.full_name
rarity = 5 rarity = 5
# 须弥·正明 # 须弥·正明
namecard = (await self.assets_service.namecard(210132).navbar()).as_uri() name_card = (await self.assets_service.namecard(210132).navbar()).as_uri()
if traveller := next(filter(lambda x: x.id in [10000005, 10000007], characters), None): if traveller := next(filter(lambda x: x.id in [10000005, 10000007], characters), None):
avatar = (await self.assets_service.avatar(traveller.id).icon()).as_uri() avatar = (await self.assets_service.avatar(traveller.id).icon()).as_uri()
else: else:
avatar = (await self.assets_service.avatar(10000005).icon()).as_uri() avatar = (await self.assets_service.avatar(10000005).icon()).as_uri()
return namecard, avatar, nickname, rarity return name_card, avatar, nickname, rarity
@handler.command("avatars", filters.Regex(r"^/avatars\s*(?:(\d+)|(all))?$"), block=False) @handler.command("avatars", filters.Regex(r"^/avatars\s*(?:(\d+)|(all))?$"), block=False)
@handler.message(filters.Regex(r"^(全部)?练度统计$"), block=False) @handler.message(filters.Regex(r"^(全部)?练度统计$"), block=False)
@ -216,17 +215,17 @@ class AvatarListPlugin(Plugin, BasePlugin):
raise e raise e
try: try:
namecard, avatar, nickname, rarity = await self.get_final_data(client, characters, update) name_card, avatar, nickname, rarity = await self.get_final_data(client, characters, update)
except Exception as e: except Exception as exc:
logger.debug(f"卡片信息请求失败: {e}") logger.error("卡片信息请求失败", exc_info=exc)
namecard, avatar, nickname, rarity = await self.get_default_final_data(characters, update) name_card, avatar, nickname, rarity = await self.get_default_final_data(characters, update)
render_data = { render_data = {
"uid": client.uid, # 玩家uid "uid": client.uid, # 玩家uid
"nickname": nickname, # 玩家昵称 "nickname": nickname, # 玩家昵称
"avatar": avatar, # 玩家头像 "avatar": avatar, # 玩家头像
"rarity": rarity, # 玩家头像对应的角色星级 "rarity": rarity, # 玩家头像对应的角色星级
"namecard": namecard, # 玩家名片 "namecard": name_card, # 玩家名片
"avatar_datas": avatar_datas, # 角色数据 "avatar_datas": avatar_datas, # 角色数据
"has_more": len(characters) != len(avatar_datas), # 是否显示了全部角色 "has_more": len(characters) != len(avatar_datas), # 是否显示了全部角色
} }

View File

@ -74,7 +74,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
async def command_start(self, update: Update, context: CallbackContext) -> int: async def command_start(self, update: Update, context: CallbackContext) -> int:
user = update.effective_user user = update.effective_user
message = update.effective_message message = update.effective_message
logger.info(f"用户 {user.full_name}[{user.id}] 绑定账号命令请求") logger.info("用户 %s[%s] 绑定账号命令请求", user.full_name, user.id)
add_user_command_data: AddUserCommandData = context.chat_data.get("add_user_command_data") add_user_command_data: AddUserCommandData = context.chat_data.get("add_user_command_data")
if add_user_command_data is None: if add_user_command_data is None:
cookies_command_data = AddUserCommandData() cookies_command_data = AddUserCommandData()
@ -254,7 +254,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
add_user_command_data.cookies["account_id"] = str(account_id) add_user_command_data.cookies["account_id"] = str(account_id)
logger.success("获取用户 %s[%s] account_id[%s] 成功", user.full_name, user.id, account_id) logger.success("获取用户 %s[%s] account_id[%s] 成功", user.full_name, user.id, account_id)
else: else:
logger.warning("用户 %s[%s] region 也许是不正确的", user.full_name, user.id, client.region.name) logger.warning("用户 %s[%s] region[%s] 也许是不正确的", user.full_name, user.id, client.region.name)
genshin_accounts = await client.genshin_accounts() genshin_accounts = await client.genshin_accounts()
except DataNotPublic: except DataNotPublic:
logger.info("用户 %s[%s] 账号疑似被注销", user.full_name, user.id) logger.info("用户 %s[%s] 账号疑似被注销", user.full_name, user.id)
@ -352,7 +352,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
await self.cookies_service.update_cookies( await self.cookies_service.update_cookies(
user.id, add_user_command_data.cookies, add_user_command_data.region user.id, add_user_command_data.cookies, add_user_command_data.region
) )
logger.info(f"用户 {user.full_name}[{user.id}] 绑定账号成功") logger.info("用户 %s[%s] 绑定账号成功", user.full_name, user.id)
await message.reply_text("保存成功", reply_markup=ReplyKeyboardRemove()) await message.reply_text("保存成功", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
else: else:

View File

@ -122,7 +122,7 @@ class DailyMaterial(Plugin, BasePlugin):
if (not DATA_FILE_PATH.exists()) or ( # 若缓存不存在 if (not DATA_FILE_PATH.exists()) or ( # 若缓存不存在
(datetime.today() - datetime.fromtimestamp(os.stat(DATA_FILE_PATH).st_mtime)).days > 3 # 若缓存过期超过了3天 (datetime.today() - datetime.fromtimestamp(os.stat(DATA_FILE_PATH).st_mtime)).days > 3 # 若缓存过期超过了3天
): ):
self.refresh_task = asyncio.create_task(task_daily()) # 创建后台任务 asyncio.create_task(task_daily()) # 创建后台任务
if not data and DATA_FILE_PATH.exists(): # 若存在,则读取至内存中 if not data and DATA_FILE_PATH.exists(): # 若存在,则读取至内存中
async with async_open(DATA_FILE_PATH) as file: async with async_open(DATA_FILE_PATH) as file:
data = json.loads(await file.read()) data = json.loads(await file.read())
@ -147,7 +147,7 @@ class DailyMaterial(Plugin, BasePlugin):
else: else:
# 如果重试了5次都失败了则直接返回 None # 如果重试了5次都失败了则直接返回 None
logger.warning( logger.warning(
f"daily_material 解析角色 id 为 [bold]{character.id}[/]的数据时遇到了 Too Many Requests 错误", extra={"markup": True} "daily_material 解析角色 id 为 [bold]%s[/]的数据时遇到了 Too Many Requests 错误", character.id, extra={"markup": True}
) )
return None return None
# 不用针对旅行者、草主进行特殊处理,因为输入数据不会有旅行者。 # 不用针对旅行者、草主进行特殊处理,因为输入数据不会有旅行者。
@ -161,7 +161,7 @@ class DailyMaterial(Plugin, BasePlugin):
try: try:
logger.debug("尝试获取已绑定的原神账号") logger.debug("尝试获取已绑定的原神账号")
client = await get_genshin_client(user.id) client = await get_genshin_client(user.id)
logger.debug(f"获取账号数据成功: UID={client.uid}") logger.debug("获取账号数据成功: UID=%s", client.uid)
characters = await client.get_genshin_characters(client.uid) characters = await client.get_genshin_characters(client.uid)
for character in characters: for character in characters:
if character.name == "旅行者": # 跳过主角 if character.name == "旅行者": # 跳过主角
@ -196,9 +196,9 @@ class DailyMaterial(Plugin, BasePlugin):
) )
) )
except (UserNotFoundError, CookiesNotFoundError): except (UserNotFoundError, CookiesNotFoundError):
logger.info(f"未查询到用户({user.full_name} {user.id}) 所绑定的账号信息") logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id)
except InvalidCookies: except InvalidCookies:
logger.info(f"用户({user.full_name} {user.id}) 所绑定的账号信息已失效") logger.info("用户 %s[%s] 所绑定的账号信息已失效", user.full_name, user.id)
else: else:
# 没有异常返回数据 # 没有异常返回数据
return client, user_data return client, user_data
@ -225,7 +225,7 @@ class DailyMaterial(Plugin, BasePlugin):
time = f"星期{WEEK_MAP[weekday]}" time = f"星期{WEEK_MAP[weekday]}"
full = bool(args and args[-1] == "full") # 判定最后一个参数是不是 full full = bool(args and args[-1] == "full") # 判定最后一个参数是不是 full
logger.info(f'用户 {user.full_name}[{user.id}] 每日素材命令请求 || 参数 weekday="{WEEK_MAP[weekday]}" full={full}') logger.info("用户 %s[%s}] 每日素材命令请求 || 参数 weekday=%s full=%s", user.full_name, user.id, WEEK_MAP[weekday], full)
if weekday == 6: if weekday == 6:
await message.reply_text( await message.reply_text(
@ -295,7 +295,7 @@ class DailyMaterial(Plugin, BasePlugin):
try: try:
item = HONEY_DATA[type_][id_] item = HONEY_DATA[type_][id_]
except KeyError: # 跳过不存在或者已忽略的角色、武器 except KeyError: # 跳过不存在或者已忽略的角色、武器
logger.warning(f"未在 honey 数据中找到 {type_} {id_} 的信息") logger.warning("未在 honey 数据中找到 %s[%s] 的信息", type_, id_)
continue continue
if item[2] < 4: # 跳过 3 星及以下的武器 if item[2] < 4: # 跳过 3 星及以下的武器
continue continue
@ -314,7 +314,7 @@ class DailyMaterial(Plugin, BasePlugin):
material = HONEY_DATA["material"][mid] material = HONEY_DATA["material"][mid]
materials.append(ItemData(id=mid, icon=path, name=material[1], rarity=material[2])) materials.append(ItemData(id=mid, icon=path, name=material[1], rarity=material[2]))
except AssetsCouldNotFound as exc: except AssetsCouldNotFound as exc:
logger.warning("%s mid[%s]", exc.message, exc.target) logger.warning("AssetsCouldNotFound message[%s] target[%s]", exc.message, exc.target)
await notice.edit_text("出错了呜呜呜 ~ 派蒙找不到一些素材") await notice.edit_text("出错了呜呜呜 ~ 派蒙找不到一些素材")
return return
areas.append( areas.append(
@ -366,7 +366,7 @@ class DailyMaterial(Plugin, BasePlugin):
user = update.effective_user user = update.effective_user
message = update.effective_message message = update.effective_message
logger.info(f"用户 {user.full_name}[{user.id}] 刷新[bold]每日素材[/]缓存命令", extra={"markup": True}) logger.info("用户 {%s}[%s] 刷新[bold]每日素材[/]缓存命令", user.full_name, user.id, extra={"markup": True})
if self.locks[0].locked(): if self.locks[0].locked():
notice = await message.reply_text("派蒙还在抄每日素材表呢,我有在好好工作哦~") notice = await message.reply_text("派蒙还在抄每日素材表呢,我有在好好工作哦~")
self._add_delete_message_job(context, notice.chat_id, notice.message_id, 10) self._add_delete_message_job(context, notice.chat_id, notice.message_id, 10)
@ -465,7 +465,7 @@ class DailyMaterial(Plugin, BasePlugin):
the_time.value = time_() the_time.value = time_()
async def task(item_id, name, item_type): async def task(item_id, name, item_type):
logger.debug(f'正在开始下载 "{name}" 的图标素材') logger.debug("正在开始下载 %s 的图标素材", name)
await edit_message(f"正在搬运 <b>{name}</b> 的图标素材。。。") await edit_message(f"正在搬运 <b>{name}</b> 的图标素材。。。")
asset: AssetsServiceType = getattr(self.assets_service, item_type)(item_id) # 获取素材对象 asset: AssetsServiceType = getattr(self.assets_service, item_type)(item_id) # 获取素材对象
asset_list.append(asset.honey_id) asset_list.append(asset.honey_id)
@ -473,7 +473,7 @@ class DailyMaterial(Plugin, BasePlugin):
# 并根据图标类型找到下载对应图标的函数 # 并根据图标类型找到下载对应图标的函数
for icon_type in asset.icon_types: for icon_type in asset.icon_types:
await getattr(asset, icon_type)(True) # 执行下载函数 await getattr(asset, icon_type)(True) # 执行下载函数
logger.debug(f'"{name}" 的图标素材下载成功') logger.debug("%s 的图标素材下载成功", name)
await edit_message(f"正在搬运 <b>{name}</b> 的图标素材。。。<b>成功!</b>") await edit_message(f"正在搬运 <b>{name}</b> 的图标素材。。。<b>成功!</b>")
for TYPE, ITEMS in HONEY_DATA.items(): # 遍历每个对象 for TYPE, ITEMS in HONEY_DATA.items(): # 遍历每个对象

View File

@ -49,7 +49,7 @@ class VerificationPlugins(Plugin, BasePlugin):
async def verify(self, update: Update, context: CallbackContext) -> None: async def verify(self, update: Update, context: CallbackContext) -> None:
user = update.effective_user user = update.effective_user
message = update.effective_message message = update.effective_message
logger.info(f"用户 %s[%s] 发出verify命令", user.full_name, user.id) logger.info("用户 %s[%s] 发出verify命令", user.full_name, user.id)
try: try:
client = await get_genshin_client(user.id) client = await get_genshin_client(user.id)
if client.region != Region.CHINESE: if client.region != Region.CHINESE:

View File

@ -48,9 +48,11 @@ class SignJob(Plugin):
if context.job.name == "SignJob": if context.job.name == "SignJob":
if sign_db.status not in [SignStatusEnum.STATUS_SUCCESS, SignStatusEnum.ALREADY_CLAIMED]: if sign_db.status not in [SignStatusEnum.STATUS_SUCCESS, SignStatusEnum.ALREADY_CLAIMED]:
continue continue
elif context.job.name == "SignAgainJob": elif context.job.name == "SignAgainJob" and sign_db.status in [
if sign_db.status in [SignStatusEnum.STATUS_SUCCESS, SignStatusEnum.ALREADY_CLAIMED]: SignStatusEnum.STATUS_SUCCESS,
continue SignStatusEnum.ALREADY_CLAIMED,
]:
continue
try: try:
client = await get_genshin_client(user_id) client = await get_genshin_client(user_id)
text = await self.sign_system.start_sign( text = await self.sign_system.start_sign(

View File

@ -1,4 +1,5 @@
import contextlib import contextlib
from telegram import Update from telegram import Update
from telegram.error import BadRequest, Forbidden from telegram.error import BadRequest, Forbidden
from telegram.ext import CallbackContext, CommandHandler from telegram.ext import CallbackContext, CommandHandler
@ -57,7 +58,7 @@ class AdminPlugin(Plugin):
await message.reply_text("输入错误") await message.reply_text("输入错误")
return return
except ValueError as error: except ValueError as error:
logger.error("获取 chat_id 发生错误! 错误信息为 \n", error) logger.error("获取 chat_id 发生错误! 错误信息为 \n", exc_info=error)
await message.reply_text("输入错误") await message.reply_text("输入错误")
return return
try: try:

View File

@ -94,16 +94,16 @@ class GetChat(Plugin):
f"\n签到状态:<code>{sign_info.status.name}</code>" f"\n签到状态:<code>{sign_info.status.name}</code>"
) )
else: else:
text += f"\n自动签到:未开启" text += "\n自动签到:未开启"
with contextlib.suppress(Exception): with contextlib.suppress(Exception):
gacha_log, status = await self.gacha_log.load_history_info(str(chat.id), str(uid)) gacha_log, status = await self.gacha_log.load_history_info(str(chat.id), str(uid))
if status: if status:
text += f"\n抽卡记录:" text += "\n抽卡记录:"
for key, value in gacha_log.item_list.items(): for key, value in gacha_log.item_list.items():
text += f"\n - {key}{len(value)}" text += f"\n - {key}{len(value)}"
text += f"\n - 最后更新:{gacha_log.update_time.strftime('%Y-%m-%d %H:%M:%S')}" text += f"\n - 最后更新:{gacha_log.update_time.strftime('%Y-%m-%d %H:%M:%S')}"
else: else:
text += f"\n抽卡记录:<code>未导入</code>" text += "\n抽卡记录:<code>未导入</code>"
return text return text
@handler(CommandHandler, command="get_chat", block=False) @handler(CommandHandler, command="get_chat", block=False)

View File

@ -31,7 +31,7 @@ class BotJoiningGroupsVerification(Plugin):
from_user = message.from_user from_user = message.from_user
for new_chat_members_user in message.new_chat_members: for new_chat_members_user in message.new_chat_members:
if new_chat_members_user.id == context.bot.id: if new_chat_members_user.id == context.bot.id:
logger.info(f"有人邀请BOT进入群 {chat.title}[{chat.id}]") logger.info("有人邀请BOT进入群 %s[%s]", chat.title, chat.id)
quit_status = True quit_status = True
if from_user is not None: if from_user is not None:
logger.info(f"用户 {from_user.full_name}[{from_user.id}] 在群 {chat.title}[{chat.id}] 邀请BOT") logger.info(f"用户 {from_user.full_name}[{from_user.id}] 在群 {chat.title}[{chat.id}] 邀请BOT")
@ -42,22 +42,22 @@ class BotJoiningGroupsVerification(Plugin):
quit_status = False quit_status = False
else: else:
logger.warning("不是管理员邀请!退出群聊") logger.warning("不是管理员邀请!退出群聊")
except Exception as exc: except Exception as exc: # pylint: disable=W0703
logger.error(f"获取信息出现错误 {repr(exc)}") logger.error("获取信息出现错误", exc_info=exc)
elif config.join_groups == JoinGroups.ALLOW_AUTH_USER: elif config.join_groups == JoinGroups.ALLOW_AUTH_USER:
try: try:
user_info = await self.user_service.get_user_by_id(from_user.id) user_info = await self.user_service.get_user_by_id(from_user.id)
await self.cookies_service.get_cookies(from_user.id, user_info.region) await self.cookies_service.get_cookies(from_user.id, user_info.region)
except (UserNotFoundError, CookiesNotFoundError): except (UserNotFoundError, CookiesNotFoundError):
logger.warning(f"用户 {from_user.full_name}[{from_user.id}] 邀请请求被拒绝") logger.warning("用户 %s[%s] 邀请请求被拒绝", from_user.full_name, from_user.id)
except Exception as exc: except Exception as exc:
logger.error(f"获取信息出现错误 {repr(exc)}") logger.error("获取信息出现错误", exc_info=exc)
else: else:
quit_status = False quit_status = False
else: else:
quit_status = True quit_status = True
else: else:
logger.info(f"未知用户 在群 {chat.title}[{chat.id}] 邀请BOT") logger.info("未知用户 在群 %s[%s] 邀请BOT", chat.title, chat.id)
if quit_status: if quit_status:
await context.bot.send_message(message.chat_id, "派蒙不想进去!不是旅行者的邀请!") await context.bot.send_message(message.chat_id, "派蒙不想进去!不是旅行者的邀请!")
await context.bot.leave_chat(chat.id) await context.bot.leave_chat(chat.id)

View File

@ -50,7 +50,7 @@ class SetQuizPlugin(Plugin.Conversation, BasePlugin.Conversation):
async def command_start(self, update: Update, context: CallbackContext) -> int: async def command_start(self, update: Update, context: CallbackContext) -> int:
user = update.effective_user user = update.effective_user
message = update.effective_message message = update.effective_message
logger.info(f"用户 {user.full_name}[{user.id}] set_quiz命令请求") logger.info("用户 %s[%s] set_quiz命令请求", user.full_name, user.id)
quiz_command_data: QuizCommandData = context.chat_data.get("quiz_command_data") quiz_command_data: QuizCommandData = context.chat_data.get("quiz_command_data")
if quiz_command_data is None: if quiz_command_data is None:
quiz_command_data = QuizCommandData() quiz_command_data = QuizCommandData()
@ -110,8 +110,8 @@ class SetQuizPlugin(Plugin.Conversation, BasePlugin.Conversation):
except DataError: except DataError:
await update.message.reply_text("Redis数据错误重载失败", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("Redis数据错误重载失败", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
except ResponseError as error: except ResponseError as exc:
logger.error("重载问题失败", error) logger.error("重载问题失败", exc_info=exc)
await update.message.reply_text("重载问题失败异常抛出Redis请求错误异常详情错误请看日记", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("重载问题失败异常抛出Redis请求错误异常详情错误请看日记", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
await update.message.reply_text("重载成功", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("重载成功", reply_markup=ReplyKeyboardRemove())
@ -189,8 +189,8 @@ class SetQuizPlugin(Plugin.Conversation, BasePlugin.Conversation):
await update.message.reply_text("保存成功", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("保存成功", reply_markup=ReplyKeyboardRemove())
try: try:
await self.quiz_service.refresh_quiz() await self.quiz_service.refresh_quiz()
except ResponseError as error: except ResponseError as exc:
logger.error("重载问题失败", error) logger.error("重载问题失败", exc_info=exc)
await update.message.reply_text( await update.message.reply_text(
"重载问题失败异常抛出Redis请求错误异常详情错误请看日记", reply_markup=ReplyKeyboardRemove() "重载问题失败异常抛出Redis请求错误异常详情错误请看日记", reply_markup=ReplyKeyboardRemove()
) )
@ -223,8 +223,8 @@ class SetQuizPlugin(Plugin.Conversation, BasePlugin.Conversation):
await self.quiz_service.delete_question_by_id(question.question_id) await self.quiz_service.delete_question_by_id(question.question_id)
await update.message.reply_text("删除问题成功", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("删除问题成功", reply_markup=ReplyKeyboardRemove())
await self.quiz_service.refresh_quiz() await self.quiz_service.refresh_quiz()
except ResponseError as error: except ResponseError as exc:
logger.error("重载问题失败", error) logger.error("重载问题失败", exc_info=exc)
await update.message.reply_text("重载问题失败异常抛出Redis请求错误异常详情错误请看日记", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("重载问题失败异常抛出Redis请求错误异常详情错误请看日记", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
await update.message.reply_text("重载配置成功", reply_markup=ReplyKeyboardRemove()) await update.message.reply_text("重载配置成功", reply_markup=ReplyKeyboardRemove())

View File

@ -54,22 +54,22 @@ class StartPlugin(Plugin):
f"{escape_markdown('发送 /setuid 或 /setcookie 命令进入绑定账号流程')}" f"{escape_markdown('发送 /setuid 或 /setcookie 命令进入绑定账号流程')}"
) )
elif args[0] == "verify_verification": elif args[0] == "verify_verification":
logger.info(f"用户 %s[%s] 通过start命令 获取认证信息", user.full_name, user.id) logger.info("用户 %s[%s] 通过start命令 获取认证信息", user.full_name, user.id)
await self.process_validate(message, user, bot_username=context.bot.username) await self.process_validate(message, user, bot_username=context.bot.username)
elif args[0] == "sign": elif args[0] == "sign":
logger.info(f"用户 %s[%s] 通过start命令 获取签到信息", user.full_name, user.id) logger.info("用户 %s[%s] 通过start命令 获取签到信息", user.full_name, user.id)
await self.gen_sign_button(message, user) await self.gen_sign_button(message, user)
elif args[0].startswith("challenge_"): elif args[0].startswith("challenge_"):
_data = args[0].split("_") _data = args[0].split("_")
_command = _data[1] _command = _data[1]
_challenge = _data[2] _challenge = _data[2]
if _command == "sign": if _command == "sign":
logger.info(f"用户 %s[%s] 通过start命令 进入签到流程", user.full_name, user.id) logger.info("用户 %s[%s] 通过start命令 进入签到流程", user.full_name, user.id)
await self.process_sign_validate(message, user, _challenge) await self.process_sign_validate(message, user, _challenge)
else: else:
await message.reply_html(f"你好 {user.mention_html()} !我是派蒙 \n请点击 /{args[0]} 命令进入对应流程") await message.reply_html(f"你好 {user.mention_html()} !我是派蒙 \n请点击 /{args[0]} 命令进入对应流程")
return return
logger.info(f"用户 %s[%s] 发出start命令", user.full_name, user.id) logger.info("用户 %s[%s] 发出start命令", user.full_name, user.id)
await message.reply_markdown_v2(f"你好 {user.mention_markdown_v2()} {escape_markdown('!我是派蒙 ')}") await message.reply_markdown_v2(f"你好 {user.mention_markdown_v2()} {escape_markdown('!我是派蒙 ')}")
@staticmethod @staticmethod

View File

@ -49,14 +49,14 @@ class UpdatePlugin(Plugin):
return return
async with self._lock: async with self._lock:
reply_text = await message.reply_text("正在更新") reply_text = await message.reply_text("正在更新")
logger.info(f"正在更新代码") logger.info("正在更新代码")
await execute("git fetch --all") await execute("git fetch --all")
if len(args) > 0: if len(args) > 0:
await execute("git reset --hard origin/main") await execute("git reset --hard origin/main")
await execute("git pull --all") await execute("git pull --all")
if len(args) > 0: if len(args) > 0:
await execute(f"{executable} -m poetry install --extras all") await execute(f"{executable} -m poetry install --extras all")
logger.info(f"更新成功 正在重启") logger.info("更新成功 正在重启")
await reply_text.edit_text("更新成功 正在重启") await reply_text.edit_text("更新成功 正在重启")
async with async_open(UPDATE_DATA, mode="w", encoding="utf-8") as file: async with async_open(UPDATE_DATA, mode="w", encoding="utf-8") as file:
await file.write(reply_text.to_json()) await file.write(reply_text.to_json())

View File

@ -57,9 +57,8 @@ def restricts(
user = update.effective_user user = update.effective_user
_restricts_time = restricts_time _restricts_time = restricts_time
if restricts_time_of_groups is not None: if restricts_time_of_groups is not None and filters.ChatType.GROUPS.filter(message):
if filters.ChatType.GROUPS.filter(message): _restricts_time = restricts_time_of_groups
_restricts_time = restricts_time_of_groups
async with _lock: async with _lock:
user_lock = context.user_data.get("lock") user_lock = context.user_data.get("lock")
@ -68,7 +67,7 @@ def restricts(
# 如果上一个命令还未完成,忽略后续重复调用 # 如果上一个命令还未完成,忽略后续重复调用
if without_overlapping and user_lock.locked(): if without_overlapping and user_lock.locked():
logger.warning(f"用户 {user.full_name}[{user.id}] 触发 overlapping 该次命令已忽略") logger.warning("用户 %s[%s] 触发 overlapping 该次命令已忽略", user.full_name, user.id)
return return_data return return_data
async with user_lock: async with user_lock:
@ -90,7 +89,7 @@ def restricts(
await update.callback_query.answer("你已经触发洪水防御请等待60秒", show_alert=True) await update.callback_query.answer("你已经触发洪水防御请等待60秒", show_alert=True)
else: else:
await message.reply_text("你已经触发洪水防御请等待60秒") await message.reply_text("你已经触发洪水防御请等待60秒")
logger.warning(f"用户 {user.full_name}[{user.id}] 触发洪水限制 已被限制60秒") logger.warning("用户 %s[%s] 触发洪水限制 已被限制60秒", user.full_name, user.id)
return return_data return return_data
# 单次使用限制 # 单次使用限制
if command_time: if command_time:

View File

@ -79,17 +79,17 @@ async def url_to_file(url: str, return_path: bool = False) -> str:
try: try:
data = await client.get(url) data = await client.get(url)
except UnsupportedProtocol: except UnsupportedProtocol:
logger.error(f"连接不支持 url[{url}]") logger.error("连接不支持 url[%s]", url)
return "" return ""
if data.is_error: if data.is_error:
logger.error(f"请求出现错误 url[{url}] status_code[{data.status_code}]") logger.error("请求出现错误 url[%s] status_code[%s]", url, data.status_code)
raise UrlResourcesNotFoundError(url) raise UrlResourcesNotFoundError(url)
if data.status_code != 200: if data.status_code != 200:
logger.error(f"url_to_file 获取url[{url}] 错误 status_code[f{data.status_code}]") logger.error("url_to_file 获取url[%s] 错误 status_code[%s]", url, data.status_code)
raise UrlResourcesNotFoundError(url) raise UrlResourcesNotFoundError(url)
async with aiofiles.open(file_dir, mode="wb") as f: async with aiofiles.open(file_dir, mode="wb") as f:
await f.write(data.content) await f.write(data.content)
logger.debug(f"url_to_file 获取url[{url}] 并下载到 file_dir[{file_dir}]") logger.debug("url_to_file 获取url[%s] 并下载到 file_dir[%s]", url, file_dir)
return file_dir if return_path else Path(file_dir).as_uri() return file_dir if return_path else Path(file_dir).as_uri()

View File

@ -31,10 +31,7 @@ logger = Logger(
@lru_cache @lru_cache
def _name_filter(record_name: str) -> bool: def _name_filter(record_name: str) -> bool:
for name in config.logger.filtered_names + [config.logger.name]: return any(re.match(rf"^{name}.*?$", record_name) for name in config.logger.filtered_names + [config.logger.name])
if re.match(rf"^{name}.*?$", record_name):
return True
return False
def name_filter(record: "LogRecord") -> bool: def name_filter(record: "LogRecord") -> bool:

View File

@ -231,9 +231,7 @@ class Handler(DefaultRichHandler):
locals_max_length=(getattr(record, "locals_max_length", None) or self.locals_max_length), locals_max_length=(getattr(record, "locals_max_length", None) or self.locals_max_length),
locals_max_string=(getattr(record, "locals_max_string", None) or self.locals_max_string), locals_max_string=(getattr(record, "locals_max_string", None) or self.locals_max_string),
locals_max_depth=( locals_max_depth=(
getattr(record, "locals_max_depth") record.locals_max_depth if hasattr(record, "locals_max_depth") else self.locals_max_depth
if hasattr(record, "locals_max_depth")
else self.locals_max_depth
), ),
suppress=self.tracebacks_suppress, suppress=self.tracebacks_suppress,
max_frames=self.tracebacks_max_frames, max_frames=self.tracebacks_max_frames,