diff --git a/core/base/assets.py b/core/base/assets.py index 1743baf..96dcce5 100644 --- a/core/base/assets.py +++ b/core/base/assets.py @@ -277,7 +277,7 @@ class _AvatarAssets(_AssetsService): 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]: - 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")) @cached_property diff --git a/core/bot.py b/core/bot.py index b6688ef..0d09323 100644 --- a/core/bot.py +++ b/core/bot.py @@ -106,7 +106,7 @@ class Bot: import_module(pkg) # 导入插件 except Exception as e: # pylint: disable=W0703 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 # 如有错误则继续 callback_dict: Dict[int, List[Callable]] = {} @@ -123,7 +123,7 @@ class Bot: self.app.add_handler(handler, group=-1) self.app.add_handlers(handlers) if handlers: - logger.debug(f'插件 "{path}" 添加了 {len(handlers)} 个 handler ') + logger.debug('插件 "%s" 添加了 %s 个 handler ', path, len(handlers)) # noinspection PyProtectedMember 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(): self.app.add_error_handler(callback, block) 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: - logger.debug(f'插件 "{path}" 添加了 {len(jobs)} 个任务') - logger.success(f'插件 "{path}" 载入成功') + logger.debug('插件 "%s" 添加了 %s 个 jobs ', path, len(jobs)) + logger.success('插件 "%s" 载入成功', path) except Exception as e: # pylint: disable=W0703 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: 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) ) logger.success( - f"成功添加了 {num} 个针对 [blue]{StatusUpdate.NEW_CHAT_MEMBERS}[/] 的 [blue]MessageHandler[/]", + "成功添加了 %s 个针对 [blue]%s[/] 的 [blue]MessageHandler[/]", + num, + StatusUpdate.NEW_CHAT_MEMBERS, extra={"markup": True}, ) # special handler @@ -175,9 +177,9 @@ class Bot: import_module(pkg) except Exception as e: # pylint: disable=W0703 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__(): try: if hasattr(base_service_cls, "from_config"): @@ -185,10 +187,10 @@ class Bot: else: instance = self.init_inject(base_service_cls) await instance.start() - logger.success(f'服务 "{base_service_cls.__name__}" 初始化成功') + logger.success('服务 "%s" 初始化成功', base_service_cls.__name__) self._services.update({base_service_cls: instance}) except Exception as e: - logger.exception(f'服务 "{base_service_cls.__name__}" 初始化失败: {e}') + logger.error('服务 "%s" 初始化失败', base_service_cls.__name__) raise SystemExit from e async def start_services(self): @@ -201,7 +203,11 @@ class Bot: import_module(pkg) except Exception as e: # pylint: disable=W0703 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 @@ -218,11 +224,11 @@ class Bot: await service.stop() else: service.stop() - logger.success(f'服务 "{service.__class__.__name__}" 关闭成功') + logger.success('服务 "%s" 关闭成功', service.__class__.__name__) except CancelledError: - logger.warning(f'服务 "{service.__class__.__name__}" 关闭超时') + logger.warning('服务 "%s" 关闭超时', service.__class__.__name__) 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: logger.info("开始初始化 genshin.py 相关资源") @@ -276,7 +282,6 @@ class Bot: logger.warning("连接至 [blue]telegram[/] 服务器失败,正在重试", extra={"markup": True}) continue except NetworkError as e: - logger.exception() if "SSLZeroReturnError" in str(e): logger.error("代理服务出现异常, 请检查您的代理服务是否配置成功.") else: @@ -285,7 +290,7 @@ class Bot: except (SystemExit, KeyboardInterrupt): pass except Exception as e: # pylint: disable=W0703 - logger.exception(f"BOT 执行过程中出现错误: {e}") + logger.exception("BOT 执行过程中出现错误", exc_info=e) finally: loop = asyncio.get_event_loop() loop.run_until_complete(self.stop_services()) diff --git a/metadata/scripts/metadatas.py b/metadata/scripts/metadatas.py index cd1fd8a..e6650d0 100644 --- a/metadata/scripts/metadatas.py +++ b/metadata/scripts/metadatas.py @@ -118,14 +118,14 @@ async def update_metadata_from_github(overwrite: bool = True): data = json.dumps(data, ensure_ascii=False) await file.write(data) return data - except RemoteProtocolError as e: - logger.warning(f"在从 {host} 下载元数据的过程中遇到了错误: {repr(e)}") + except RemoteProtocolError as exc: + logger.warning("在从 %s 下载元数据的过程中遇到了错误: %s", host, str(exc)) continue - except Exception as e: + except Exception as exc: if num != len(hosts) - 1: - logger.error(f"在从 {host} 下载元数据的过程中遇到了错误: {repr(e)}") + logger.error("在从 %s 下载元数据的过程中遇到了错误: %s", host, str(exc)) continue - raise e + raise exc def make_github_fast(url: str) -> str: diff --git a/plugins/genshin/avatar_list.py b/plugins/genshin/avatar_list.py index 1cf53f6..af2564f 100644 --- a/plugins/genshin/avatar_list.py +++ b/plugins/genshin/avatar_list.py @@ -70,22 +70,21 @@ class AvatarListPlugin(Plugin, BasePlugin): ) async def get_avatar_data(self, character: Character, client: Client) -> Optional["AvatarData"]: - detail = None for _ in range(5): try: detail = await client.get_character_details(character) - except Exception as e: # pylint: disable=W0703 - if isinstance(e, GenshinException) and "Too Many Requests" in e.msg: + except Exception as exc: # pylint: disable=W0703 + if isinstance(exc, GenshinException) and "Too Many Requests" in exc.msg: await asyncio.sleep(0.2) continue if character.name == "旅行者": - logger.debug(f"解析旅行者数据时遇到了错误:{e}") + logger.debug("解析旅行者数据时遇到了错误:%s", str(exc)) return None - raise e + raise exc else: break 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 if character.id == 10000005: # 针对男草主 talents = [] @@ -134,43 +133,43 @@ class AvatarListPlugin(Plugin, BasePlugin): async def get_final_data(self, client: Client, characters: Sequence[Character], update: Update): try: 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() nickname = response.player.nickname if response.player.avatar.id in [10000005, 10000007]: rarity = 5 else: rarity = {k: v["rank"] for k, v in AVATAR_DATA.items()}[str(response.player.avatar.id)] - except Exception as e: # pylint: disable=W0703 - logger.debug(f"enka 请求失败: {e}") + except Exception as exc: # pylint: disable=W0703 + logger.error("enka 请求失败: %s", str(exc)) choices = ArkoWrapper(characters).filter(lambda x: x.friendship == 10) # 筛选出好感满了的角色 if choices.length == 0: # 若没有满好感角色、则以好感等级排序 choices = ArkoWrapper(characters).sort(lambda x: x.friendship, reverse=True) - namecard_choices = ( # 找到与角色对应的满好感名片ID + name_card_choices = ( # 找到与角色对应的满好感名片ID ArkoWrapper(choices) .map(lambda x: next(filter(lambda y: y["name"].split(".")[0] == x.name, NAMECARD_DATA.values()), None)) .filter(lambda x: x) .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() nickname = update.effective_user.full_name if cid in [10000005, 10000007]: rarity = 5 else: 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): nickname = update.effective_user.full_name 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): avatar = (await self.assets_service.avatar(traveller.id).icon()).as_uri() else: 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.message(filters.Regex(r"^(全部)?练度统计$"), block=False) @@ -216,17 +215,17 @@ class AvatarListPlugin(Plugin, BasePlugin): raise e try: - namecard, avatar, nickname, rarity = await self.get_final_data(client, characters, update) - except Exception as e: - logger.debug(f"卡片信息请求失败: {e}") - namecard, avatar, nickname, rarity = await self.get_default_final_data(characters, update) + name_card, avatar, nickname, rarity = await self.get_final_data(client, characters, update) + except Exception as exc: + logger.error("卡片信息请求失败", exc_info=exc) + name_card, avatar, nickname, rarity = await self.get_default_final_data(characters, update) render_data = { "uid": client.uid, # 玩家uid "nickname": nickname, # 玩家昵称 "avatar": avatar, # 玩家头像 "rarity": rarity, # 玩家头像对应的角色星级 - "namecard": namecard, # 玩家名片 + "namecard": name_card, # 玩家名片 "avatar_datas": avatar_datas, # 角色数据 "has_more": len(characters) != len(avatar_datas), # 是否显示了全部角色 } diff --git a/plugins/genshin/cookies.py b/plugins/genshin/cookies.py index da3bf2d..38c3b95 100644 --- a/plugins/genshin/cookies.py +++ b/plugins/genshin/cookies.py @@ -74,7 +74,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation): async def command_start(self, update: Update, context: CallbackContext) -> int: user = update.effective_user 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") if add_user_command_data is None: cookies_command_data = AddUserCommandData() @@ -254,7 +254,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation): add_user_command_data.cookies["account_id"] = str(account_id) logger.success("获取用户 %s[%s] account_id[%s] 成功", user.full_name, user.id, account_id) 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() except DataNotPublic: 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( 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()) return ConversationHandler.END else: diff --git a/plugins/genshin/daily/material.py b/plugins/genshin/daily/material.py index b358c39..311bce2 100644 --- a/plugins/genshin/daily/material.py +++ b/plugins/genshin/daily/material.py @@ -122,7 +122,7 @@ class DailyMaterial(Plugin, BasePlugin): if (not DATA_FILE_PATH.exists()) or ( # 若缓存不存在 (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(): # 若存在,则读取至内存中 async with async_open(DATA_FILE_PATH) as file: data = json.loads(await file.read()) @@ -147,7 +147,7 @@ class DailyMaterial(Plugin, BasePlugin): else: # 如果重试了5次都失败了,则直接返回 None 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 # 不用针对旅行者、草主进行特殊处理,因为输入数据不会有旅行者。 @@ -161,7 +161,7 @@ class DailyMaterial(Plugin, BasePlugin): try: logger.debug("尝试获取已绑定的原神账号") 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) for character in characters: if character.name == "旅行者": # 跳过主角 @@ -196,9 +196,9 @@ class DailyMaterial(Plugin, BasePlugin): ) ) except (UserNotFoundError, CookiesNotFoundError): - logger.info(f"未查询到用户({user.full_name} {user.id}) 所绑定的账号信息") + logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id) except InvalidCookies: - logger.info(f"用户({user.full_name} {user.id}) 所绑定的账号信息已失效") + logger.info("用户 %s[%s] 所绑定的账号信息已失效", user.full_name, user.id) else: # 没有异常返回数据 return client, user_data @@ -225,7 +225,7 @@ class DailyMaterial(Plugin, BasePlugin): time = f"星期{WEEK_MAP[weekday]}" 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: await message.reply_text( @@ -295,7 +295,7 @@ class DailyMaterial(Plugin, BasePlugin): try: item = HONEY_DATA[type_][id_] except KeyError: # 跳过不存在或者已忽略的角色、武器 - logger.warning(f"未在 honey 数据中找到 {type_} {id_} 的信息") + logger.warning("未在 honey 数据中找到 %s[%s] 的信息", type_, id_) continue if item[2] < 4: # 跳过 3 星及以下的武器 continue @@ -314,7 +314,7 @@ class DailyMaterial(Plugin, BasePlugin): material = HONEY_DATA["material"][mid] materials.append(ItemData(id=mid, icon=path, name=material[1], rarity=material[2])) 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("出错了呜呜呜 ~ 派蒙找不到一些素材") return areas.append( @@ -366,7 +366,7 @@ class DailyMaterial(Plugin, BasePlugin): user = update.effective_user 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(): notice = await message.reply_text("派蒙还在抄每日素材表呢,我有在好好工作哦~") 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_() async def task(item_id, name, item_type): - logger.debug(f'正在开始下载 "{name}" 的图标素材') + logger.debug("正在开始下载 %s 的图标素材", name) await edit_message(f"正在搬运 {name} 的图标素材。。。") asset: AssetsServiceType = getattr(self.assets_service, item_type)(item_id) # 获取素材对象 asset_list.append(asset.honey_id) @@ -473,7 +473,7 @@ class DailyMaterial(Plugin, BasePlugin): # 并根据图标类型找到下载对应图标的函数 for icon_type in asset.icon_types: await getattr(asset, icon_type)(True) # 执行下载函数 - logger.debug(f'"{name}" 的图标素材下载成功') + logger.debug("%s 的图标素材下载成功", name) await edit_message(f"正在搬运 {name} 的图标素材。。。成功!") for TYPE, ITEMS in HONEY_DATA.items(): # 遍历每个对象 diff --git a/plugins/genshin/verification.py b/plugins/genshin/verification.py index d0001e0..a8d1957 100644 --- a/plugins/genshin/verification.py +++ b/plugins/genshin/verification.py @@ -49,7 +49,7 @@ class VerificationPlugins(Plugin, BasePlugin): async def verify(self, update: Update, context: CallbackContext) -> None: user = update.effective_user 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: client = await get_genshin_client(user.id) if client.region != Region.CHINESE: diff --git a/plugins/jobs/sign.py b/plugins/jobs/sign.py index f28f26c..ee6579f 100644 --- a/plugins/jobs/sign.py +++ b/plugins/jobs/sign.py @@ -48,9 +48,11 @@ class SignJob(Plugin): if context.job.name == "SignJob": if sign_db.status not in [SignStatusEnum.STATUS_SUCCESS, SignStatusEnum.ALREADY_CLAIMED]: continue - elif context.job.name == "SignAgainJob": - if sign_db.status in [SignStatusEnum.STATUS_SUCCESS, SignStatusEnum.ALREADY_CLAIMED]: - continue + elif context.job.name == "SignAgainJob" and sign_db.status in [ + SignStatusEnum.STATUS_SUCCESS, + SignStatusEnum.ALREADY_CLAIMED, + ]: + continue try: client = await get_genshin_client(user_id) text = await self.sign_system.start_sign( diff --git a/plugins/system/admin.py b/plugins/system/admin.py index 8a94ddc..984afdd 100644 --- a/plugins/system/admin.py +++ b/plugins/system/admin.py @@ -1,4 +1,5 @@ import contextlib + from telegram import Update from telegram.error import BadRequest, Forbidden from telegram.ext import CallbackContext, CommandHandler @@ -57,7 +58,7 @@ class AdminPlugin(Plugin): await message.reply_text("输入错误") return except ValueError as error: - logger.error("获取 chat_id 发生错误! 错误信息为 \n", error) + logger.error("获取 chat_id 发生错误! 错误信息为 \n", exc_info=error) await message.reply_text("输入错误") return try: diff --git a/plugins/system/get_chat.py b/plugins/system/get_chat.py index 9b734d7..653ca1d 100644 --- a/plugins/system/get_chat.py +++ b/plugins/system/get_chat.py @@ -94,16 +94,16 @@ class GetChat(Plugin): f"\n签到状态:{sign_info.status.name}" ) else: - text += f"\n自动签到:未开启" + text += "\n自动签到:未开启" with contextlib.suppress(Exception): gacha_log, status = await self.gacha_log.load_history_info(str(chat.id), str(uid)) if status: - text += f"\n抽卡记录:" + text += "\n抽卡记录:" for key, value in gacha_log.item_list.items(): text += f"\n - {key}:{len(value)} 条" text += f"\n - 最后更新:{gacha_log.update_time.strftime('%Y-%m-%d %H:%M:%S')}" else: - text += f"\n抽卡记录:未导入" + text += "\n抽卡记录:未导入" return text @handler(CommandHandler, command="get_chat", block=False) diff --git a/plugins/system/new_member.py b/plugins/system/new_member.py index 04fafa7..5d829c8 100644 --- a/plugins/system/new_member.py +++ b/plugins/system/new_member.py @@ -31,7 +31,7 @@ class BotJoiningGroupsVerification(Plugin): from_user = message.from_user for new_chat_members_user in message.new_chat_members: 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 if from_user is not None: 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 else: logger.warning("不是管理员邀请!退出群聊") - except Exception as exc: - logger.error(f"获取信息出现错误 {repr(exc)}") + except Exception as exc: # pylint: disable=W0703 + logger.error("获取信息出现错误", exc_info=exc) elif config.join_groups == JoinGroups.ALLOW_AUTH_USER: try: 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) 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: - logger.error(f"获取信息出现错误 {repr(exc)}") + logger.error("获取信息出现错误", exc_info=exc) else: quit_status = False else: quit_status = True else: - logger.info(f"未知用户 在群 {chat.title}[{chat.id}] 邀请BOT") + logger.info("未知用户 在群 %s[%s] 邀请BOT", chat.title, chat.id) if quit_status: await context.bot.send_message(message.chat_id, "派蒙不想进去!不是旅行者的邀请!") await context.bot.leave_chat(chat.id) diff --git a/plugins/system/set_quiz.py b/plugins/system/set_quiz.py index 6bb073b..f116638 100644 --- a/plugins/system/set_quiz.py +++ b/plugins/system/set_quiz.py @@ -50,7 +50,7 @@ class SetQuizPlugin(Plugin.Conversation, BasePlugin.Conversation): async def command_start(self, update: Update, context: CallbackContext) -> int: user = update.effective_user 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") if quiz_command_data is None: quiz_command_data = QuizCommandData() @@ -110,8 +110,8 @@ class SetQuizPlugin(Plugin.Conversation, BasePlugin.Conversation): except DataError: await update.message.reply_text("Redis数据错误,重载失败", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END - except ResponseError as error: - logger.error("重载问题失败", error) + except ResponseError as exc: + logger.error("重载问题失败", exc_info=exc) await update.message.reply_text("重载问题失败,异常抛出Redis请求错误异常,详情错误请看日记", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END 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()) try: await self.quiz_service.refresh_quiz() - except ResponseError as error: - logger.error("重载问题失败", error) + except ResponseError as exc: + logger.error("重载问题失败", exc_info=exc) await update.message.reply_text( "重载问题失败,异常抛出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 update.message.reply_text("删除问题成功", reply_markup=ReplyKeyboardRemove()) await self.quiz_service.refresh_quiz() - except ResponseError as error: - logger.error("重载问题失败", error) + except ResponseError as exc: + logger.error("重载问题失败", exc_info=exc) await update.message.reply_text("重载问题失败,异常抛出Redis请求错误异常,详情错误请看日记", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END await update.message.reply_text("重载配置成功", reply_markup=ReplyKeyboardRemove()) diff --git a/plugins/system/start.py b/plugins/system/start.py index d27253c..df2afff 100644 --- a/plugins/system/start.py +++ b/plugins/system/start.py @@ -54,22 +54,22 @@ class StartPlugin(Plugin): f"{escape_markdown('发送 /setuid 或 /setcookie 命令进入绑定账号流程')}" ) 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) 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) elif args[0].startswith("challenge_"): _data = args[0].split("_") _command = _data[1] _challenge = _data[2] 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) else: await message.reply_html(f"你好 {user.mention_html()} !我是派蒙 !\n请点击 /{args[0]} 命令进入对应流程") 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('!我是派蒙 !')}") @staticmethod diff --git a/plugins/system/update.py b/plugins/system/update.py index 55fa181..88dd846 100644 --- a/plugins/system/update.py +++ b/plugins/system/update.py @@ -49,14 +49,14 @@ class UpdatePlugin(Plugin): return async with self._lock: reply_text = await message.reply_text("正在更新") - logger.info(f"正在更新代码") + logger.info("正在更新代码") await execute("git fetch --all") if len(args) > 0: await execute("git reset --hard origin/main") await execute("git pull --all") if len(args) > 0: await execute(f"{executable} -m poetry install --extras all") - logger.info(f"更新成功 正在重启") + logger.info("更新成功 正在重启") await reply_text.edit_text("更新成功 正在重启") async with async_open(UPDATE_DATA, mode="w", encoding="utf-8") as file: await file.write(reply_text.to_json()) diff --git a/utils/decorators/restricts.py b/utils/decorators/restricts.py index d28286c..8fba4b3 100644 --- a/utils/decorators/restricts.py +++ b/utils/decorators/restricts.py @@ -57,9 +57,8 @@ def restricts( user = update.effective_user _restricts_time = restricts_time - if restricts_time_of_groups is not None: - if filters.ChatType.GROUPS.filter(message): - _restricts_time = restricts_time_of_groups + if restricts_time_of_groups is not None and filters.ChatType.GROUPS.filter(message): + _restricts_time = restricts_time_of_groups async with _lock: user_lock = context.user_data.get("lock") @@ -68,7 +67,7 @@ def restricts( # 如果上一个命令还未完成,忽略后续重复调用 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 async with user_lock: @@ -90,7 +89,7 @@ def restricts( await update.callback_query.answer("你已经触发洪水防御,请等待60秒", show_alert=True) else: 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 # 单次使用限制 if command_time: diff --git a/utils/helpers.py b/utils/helpers.py index 913b72c..7c8070f 100644 --- a/utils/helpers.py +++ b/utils/helpers.py @@ -79,17 +79,17 @@ async def url_to_file(url: str, return_path: bool = False) -> str: try: data = await client.get(url) except UnsupportedProtocol: - logger.error(f"连接不支持 url[{url}]") + logger.error("连接不支持 url[%s]", url) return "" 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) 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) async with aiofiles.open(file_dir, mode="wb") as f: 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() diff --git a/utils/log/__init__.py b/utils/log/__init__.py index a1b196e..489232c 100644 --- a/utils/log/__init__.py +++ b/utils/log/__init__.py @@ -31,10 +31,7 @@ logger = Logger( @lru_cache def _name_filter(record_name: str) -> bool: - for name in config.logger.filtered_names + [config.logger.name]: - if re.match(rf"^{name}.*?$", record_name): - return True - return False + return any(re.match(rf"^{name}.*?$", record_name) for name in config.logger.filtered_names + [config.logger.name]) def name_filter(record: "LogRecord") -> bool: diff --git a/utils/log/_handler.py b/utils/log/_handler.py index 41baa99..9656859 100644 --- a/utils/log/_handler.py +++ b/utils/log/_handler.py @@ -231,9 +231,7 @@ class Handler(DefaultRichHandler): 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_depth=( - getattr(record, "locals_max_depth") - if hasattr(record, "locals_max_depth") - else self.locals_max_depth + record.locals_max_depth if hasattr(record, "locals_max_depth") else self.locals_max_depth ), suppress=self.tracebacks_suppress, max_frames=self.tracebacks_max_frames,