🎨 提高代码质量

This commit is contained in:
洛水居室 2022-10-11 14:45:07 +08:00 committed by GitHub
parent 70eba45f13
commit ec8175eea2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 41 additions and 27 deletions

View File

@ -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:

View File

@ -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()

View File

@ -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):

View File

@ -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

View File

@ -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

View File

@ -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):

View File

@ -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,8 +86,10 @@ 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)}")
await message.reply_text("文件解析失败,请检查文件是否符合 UIGF 标准")
return
@ -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)

View File

@ -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"))

View File

@ -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

View File

@ -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:

View File

@ -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,

View File

@ -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):