From ec8175eea2da336189cb9aa8c2316545b431a30e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B4=9B=E6=B0=B4=E5=B1=85=E5=AE=A4?= Date: Tue, 11 Oct 2022 14:45:07 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20=E6=8F=90=E9=AB=98=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E8=B4=A8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/bot.py | 3 +-- core/template/services.py | 12 +++++++++--- core/wiki/cache.py | 2 +- modules/apihelper/gacha_log.py | 3 ++- plugins/genshin/cookies.py | 7 +++++-- plugins/genshin/daily/material.py | 2 +- plugins/genshin/gacha/gacha_log.py | 13 +++++++------ plugins/genshin/player_cards.py | 5 ++--- plugins/other/post.py | 12 ++++++++---- plugins/system/errorhandler.py | 2 +- utils/log/_logger.py | 2 +- utils/patch/aiohttp.py | 5 +++-- 12 files changed, 41 insertions(+), 27 deletions(-) diff --git a/core/bot.py b/core/bot.py index 3245aae..00d30cd 100644 --- a/core/bot.py +++ b/core/bot.py @@ -23,7 +23,6 @@ from telegram.ext.filters import StatusUpdate from core.config import BotConfig, config # pylint: disable=W0611 from core.error import ServiceNotFoundError - # noinspection PyProtectedMember from core.plugin import Plugin, _Plugin from core.service import Service @@ -208,7 +207,7 @@ class Bot: getattr(genshin.utility.extdb, i).replace("githubusercontent.com", "fastgit.org"), ) await genshin.utility.update_characters_enka() - except Exception as exc: + except Exception as exc: # pylint: disable=W0703 logger.error("初始化 genshin.py 相关资源失败") logger.exception(exc) else: diff --git a/core/template/services.py b/core/template/services.py index a9f459d..37584b0 100644 --- a/core/template/services.py +++ b/core/template/services.py @@ -10,6 +10,10 @@ from core.bot import bot from utils.log import logger +class _QuerySelectorNotFound(Exception): + pass + + class TemplateService: def __init__(self, browser: AioBrowser, template_package_name: str = "resources", cache_dir_name: str = "cache"): self._browser = browser @@ -89,10 +93,12 @@ class TemplateService: if query_selector: try: card = await page.query_selector(query_selector) - assert card + if not card: + raise _QuerySelectorNotFound clip = await card.bounding_box() - assert clip - except AssertionError: + if not clip: + raise _QuerySelectorNotFound + except _QuerySelectorNotFound: logger.warning(f"未找到 {query_selector} 元素") png_data = await page.screenshot(clip=clip, full_page=full_page) await page.close() diff --git a/core/wiki/cache.py b/core/wiki/cache.py index 5de0050..a73ee80 100644 --- a/core/wiki/cache.py +++ b/core/wiki/cache.py @@ -26,7 +26,7 @@ class WikiCache: # noinspection PyBroadException try: result = json.loads(await self.client.get(qname)) - except Exception: + except Exception: # pylint: disable=W0703 result = [] if isinstance(result, list) and len(result) > 0: for num, item in enumerate(result): diff --git a/modules/apihelper/gacha_log.py b/modules/apihelper/gacha_log.py index 697f8e1..887c8ab 100644 --- a/modules/apihelper/gacha_log.py +++ b/modules/apihelper/gacha_log.py @@ -258,7 +258,8 @@ class GachaLog: if four_star < five_star: return False, "检测到您将要导入的抽卡记录中五星数量过多,可能是由于文件错误导致的,请检查后重新导入。" return True, "" - except Exception: + except Exception as exc: # pylint: disable=W0703 + logger.warning(f"抽卡记录数据验证失败 {repr(exc)}") return False, "导入失败,数据格式错误" @staticmethod diff --git a/plugins/genshin/cookies.py b/plugins/genshin/cookies.py index 97ecc9a..5a73ab9 100644 --- a/plugins/genshin/cookies.py +++ b/plugins/genshin/cookies.py @@ -162,6 +162,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation): @handler.message(filters=filters.TEXT & ~filters.COMMAND, block=True) @error_callable async def check_captcha(self, update: Update, context: CallbackContext) -> int: + user = update.effective_user message = update.effective_message if message.text == "退出": await message.reply_text("退出任务", reply_markup=ReplyKeyboardRemove()) @@ -183,7 +184,8 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation): await message.reply_text("登录失败:可能是验证码错误,注意不要在登录页面使用掉验证码,如果验证码已经使用,请重新获取验证码!") return ConversationHandler.END await client.get_s_token() - except Exception: + except Exception as exc: # pylint: disable=W0703 + logger.error(f"用户 {user.full_name}[{user.id}] 登录失败 {repr(exc)}") await message.reply_text("登录失败:米游社返回了错误的数据,请稍后再试!") return ConversationHandler.END add_user_command_data.sign_in_client = client @@ -198,7 +200,8 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation): if not success: await message.reply_text("登录失败:可能是验证码错误,注意不要在登录页面使用掉验证码,如果验证码已经使用,请重新获取验证码!") return ConversationHandler.END - except Exception: + except Exception as exc: # pylint: disable=W0703 + logger.error(f"用户 {user.full_name}[{user.id}] 登录失败 {repr(exc)}") await message.reply_text("登录失败:米游社返回了错误的数据,请稍后再试!") return ConversationHandler.END add_user_command_data.cookies = client.cookie diff --git a/plugins/genshin/daily/material.py b/plugins/genshin/daily/material.py index 31c2544..7a28d76 100644 --- a/plugins/genshin/daily/material.py +++ b/plugins/genshin/daily/material.py @@ -367,7 +367,7 @@ class DailyMaterial(Plugin, BasePlugin): # noinspection PyUnresolvedReferences result[stage][day][1] = list(set(result[stage][day][1])) # 去重 async with async_open(DATA_FILE_PATH, "w", encoding="utf-8") as file: - await file.write(json.dumps(result)) # pylint: disable=PY-W0079 + await file.write(json.dumps(result)) # skipcq: PY-W0079 logger.info("每日素材刷新成功") break except (HTTPError, SSLZeroReturnError): diff --git a/plugins/genshin/gacha/gacha_log.py b/plugins/genshin/gacha/gacha_log.py index 0be759e..103db87 100644 --- a/plugins/genshin/gacha/gacha_log.py +++ b/plugins/genshin/gacha/gacha_log.py @@ -1,8 +1,7 @@ import json -import genshin - from io import BytesIO +import genshin from genshin.models import BannerType from telegram import Update, User, Message, Document from telegram.constants import ChatAction @@ -10,8 +9,8 @@ from telegram.ext import CallbackContext, CommandHandler, MessageHandler, filter from core.base.assets import AssetsService from core.baseplugin import BasePlugin -from core.cookies.error import CookiesNotFoundError from core.cookies import CookiesService +from core.cookies.error import CookiesNotFoundError from core.plugin import Plugin, handler, conversation from core.template import TemplateService from core.user import UserService @@ -87,9 +86,11 @@ class GachaLog(Plugin.Conversation, BasePlugin.Conversation): # bytesio to json data = data.getvalue().decode("utf-8") data = json.loads(data) + except UnicodeDecodeError: + await message.reply_text("文件解析失败,请检查文件编码是否正确或符合 UIGF 标准") + return except Exception as exc: - if not isinstance(exc, UnicodeDecodeError): - logger.error(f"文件解析失败:{repr(exc)}") + logger.error(f"文件解析失败:{repr(exc)}") await message.reply_text("文件解析失败,请检查文件是否符合 UIGF 标准") return await message.reply_chat_action(ChatAction.TYPING) @@ -97,7 +98,7 @@ class GachaLog(Plugin.Conversation, BasePlugin.Conversation): await message.reply_chat_action(ChatAction.TYPING) try: text = await self._refresh_user_data(user, data=data) - except Exception as exc: + except Exception as exc: # pylint: disable=W0703 logger.error(f"文件解析失败:{repr(exc)}") text = "文件解析失败,请检查文件是否符合 UIGF 标准" await reply.edit_text(text) diff --git a/plugins/genshin/player_cards.py b/plugins/genshin/player_cards.py index 0479079..84be19f 100644 --- a/plugins/genshin/player_cards.py +++ b/plugins/genshin/player_cards.py @@ -1,7 +1,6 @@ from typing import Any, List, Tuple, Union from enkanetwork import ( - Assets, CharacterInfo, DigitType, EnkaNetworkAPI, @@ -123,7 +122,7 @@ class PlayerCards(Plugin, BasePlugin): await message.reply_text(f"角色展柜中未找到 {character_name}") return await message.reply_chat_action(ChatAction.UPLOAD_PHOTO) - pnd_data = await RenderTemplate(uid, characters, self.template_service).render() + pnd_data = await RenderTemplate(uid, characters, self.template_service).render() # pylint: disable=W0631 await message.reply_photo(pnd_data, filename=f"player_card_{uid}_{character_name}.png") @handler(CallbackQueryHandler, pattern=r"^get_player_card\|", block=False) @@ -162,7 +161,7 @@ class PlayerCards(Plugin, BasePlugin): return await callback_query.answer(text="正在渲染图片中 请稍等 请不要重复点击按钮", show_alert=False) await message.reply_chat_action(ChatAction.UPLOAD_PHOTO) - pnd_data = await RenderTemplate(uid, characters, self.template_service).render() + pnd_data = await RenderTemplate(uid, characters, self.template_service).render() # pylint: disable=W0631 await message.edit_media(InputMediaPhoto(pnd_data, filename=f"player_card_{uid}_{result}.png")) diff --git a/plugins/other/post.py b/plugins/other/post.py index 9667d21..f9bb277 100644 --- a/plugins/other/post.py +++ b/plugins/other/post.py @@ -130,7 +130,8 @@ class Post(Plugin.Conversation, BasePlugin): return await self.delete_photo(update, context) return ConversationHandler.END - async def delete_photo(self, update: Update, context: CallbackContext) -> int: + @staticmethod + async def delete_photo(update: Update, context: CallbackContext) -> int: post_handler_data: PostHandlerData = context.chat_data.get("post_handler_data") photo_len = len(post_handler_data.post_images) message = update.effective_message @@ -159,7 +160,8 @@ class Post(Plugin.Conversation, BasePlugin): await message.reply_text("请选择你的操作", reply_markup=self.MENU_KEYBOARD) return CHECK_COMMAND - async def get_channel(self, update: Update, _: CallbackContext) -> int: + @staticmethod + async def get_channel(update: Update, _: CallbackContext) -> int: message = update.effective_message reply_keyboard = [] try: @@ -197,7 +199,8 @@ class Post(Plugin.Conversation, BasePlugin): await message.reply_text("请核对你修改的信息", reply_markup=ReplyKeyboardMarkup(reply_keyboard, True, True)) return SEND_POST - async def add_tags(self, update: Update, _: CallbackContext) -> int: + @staticmethod + async def add_tags(update: Update, _: CallbackContext) -> int: message = update.effective_message await message.reply_text("请回复添加的tag名称,如果要添加多个tag请以空格作为分隔符,不用添加 # 作为开头,推送时程序会自动添加") return GET_TAGS @@ -214,7 +217,8 @@ class Post(Plugin.Conversation, BasePlugin): await message.reply_text("请选择你的操作", reply_markup=self.MENU_KEYBOARD) return CHECK_COMMAND - async def edit_text(self, update: Update, _: CallbackContext) -> int: + @staticmethod + async def edit_text(update: Update, _: CallbackContext) -> int: message = update.effective_message await message.reply_text("请回复替换的文本") return GET_TEXT diff --git a/plugins/system/errorhandler.py b/plugins/system/errorhandler.py index 7046753..a7b4419 100644 --- a/plugins/system/errorhandler.py +++ b/plugins/system/errorhandler.py @@ -53,7 +53,7 @@ class ErrorHandler(Plugin): try: async with aiofiles.open(log_file, mode="w+", encoding="utf-8") as f: await f.write(error_text) - except Exception as exc: + except Exception as exc: # pylint: disable=W0703 logger.error("保存日记失败") logger.exception(exc) try: diff --git a/utils/log/_logger.py b/utils/log/_logger.py index 0f99932..e2aaf95 100644 --- a/utils/log/_logger.py +++ b/utils/log/_logger.py @@ -430,7 +430,7 @@ class Logger(logging.Logger): stacklevel: int = 1, extra: Optional[Mapping[str, Any]] = None, **kwargs, - ) -> None: + ) -> None: # pylint: disable=W1113 super(Logger, self).exception( "" if msg is NOT_SET else msg, *args, diff --git a/utils/patch/aiohttp.py b/utils/patch/aiohttp.py index 5c1df95..0e5d566 100644 --- a/utils/patch/aiohttp.py +++ b/utils/patch/aiohttp.py @@ -1,8 +1,9 @@ import asyncio -import aiohttp +from typing import Optional + +import aiohttp # pylint: disable=W0406 from utils.patch.methods import patch, patchable -from typing import Optional class AioHttpTimeoutException(asyncio.TimeoutError):