From 9ed30d41430460ce9418dd69a87025e251ee3606 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B4=9B=E6=B0=B4=E5=B1=85=E5=AE=A4?= Date: Sat, 12 Nov 2022 23:08:25 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20Cancel=20authentication=20if=20`?= =?UTF-8?q?cookies`=20is=20None?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 处理 CookiesNotFoundError 异常 --- modules/apihelper/hyperion.py | 4 +-- plugins/genshin/verification.py | 44 ++++++++++++++++++++++----------- plugins/system/start.py | 41 +++++++++++++++++++----------- utils/decorators/error.py | 10 ++++++-- 4 files changed, 67 insertions(+), 32 deletions(-) diff --git a/modules/apihelper/hyperion.py b/modules/apihelper/hyperion.py index 42a1f12..26229d2 100644 --- a/modules/apihelper/hyperion.py +++ b/modules/apihelper/hyperion.py @@ -389,8 +389,8 @@ class Verification: "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7", } - def __init__(self, cookie: Dict = None): - self.client = HOYORequest(headers=self.BBS_HEADERS, cookies=cookie) + def __init__(self, cookies: Dict = None): + self.client = HOYORequest(headers=self.BBS_HEADERS, cookies=cookies) def get_verification_headers(self, referer: str): headers = self.VERIFICATION_HEADERS.copy() diff --git a/plugins/genshin/verification.py b/plugins/genshin/verification.py index 389e596..0f59e83 100644 --- a/plugins/genshin/verification.py +++ b/plugins/genshin/verification.py @@ -1,5 +1,6 @@ from typing import Tuple, Optional +from genshin import Region, GenshinException from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CallbackContext @@ -7,12 +8,14 @@ from core.base.redisdb import RedisDB from core.baseplugin import BasePlugin from core.config import config from core.cookies import CookiesService +from core.cookies.error import CookiesNotFoundError from core.plugin import Plugin, handler from core.user import UserService +from core.user.error import UserNotFoundError from modules.apihelper.hyperion import Verification from utils.decorators.error import error_callable from utils.decorators.restricts import restricts -from utils.models.base import RegionEnum +from utils.helpers import get_genshin_client class VerificationSystem: @@ -44,31 +47,44 @@ class VerificationPlugins(Plugin, BasePlugin): async def verify(self, update: Update, context: CallbackContext) -> None: user = update.effective_user message = update.effective_message - user_info = await self.user_service.get_user_by_id(user.id) - if user_info.region != RegionEnum.HYPERION: - await message.reply_text("非法用户") + try: + client = await get_genshin_client(user.id) + if client.region != Region.CHINESE: + await message.reply_text("非法用户") + return + except UserNotFoundError: + await message.reply_text("用户未找到") return - uid = user_info.yuanshen_uid - cookie = await self.cookies_service.get_cookies(user.id, RegionEnum.HYPERION) - client = Verification(cookie=cookie.cookies) + except CookiesNotFoundError: + await message.reply_text("检测到用户为UID绑定,无需认证") + return + verification = Verification(cookies=client.cookie_manager.cookies) if context.args and len(context.args) > 0: validate = context.args[0] - _, challenge = await self.system.get_challenge(uid) + _, challenge = await self.system.get_challenge(client.uid) if challenge: - await client.verify(challenge, validate) + await verification.verify(challenge, validate) await message.reply_text("验证成功") else: await message.reply_text("验证失效") return - data = await client.create() + try: + await client.get_genshin_notes() + except GenshinException as exc: + if exc.retcode != 1034: + raise exc + else: + await message.reply_text("账户正常,无需认证") + return + data = await verification.create() challenge = data["challenge"] gt = data["gt"] - validate = await client.ajax(referer="https://webstatic.mihoyo.com/", gt=gt, challenge=challenge) + validate = await verification.ajax(referer="https://webstatic.mihoyo.com/", gt=gt, challenge=challenge) if validate: - await client.verify(challenge, validate) + await verification.verify(challenge, validate) await message.reply_text("验证成功") return - await self.system.set_challenge(uid, gt, challenge) - url = f"{config.pass_challenge_user_web}?username={context.bot.username}&command=verify>={gt}&challenge={challenge}&uid={uid}" + await self.system.set_challenge(client.uid, gt, challenge) + url = f"{config.pass_challenge_user_web}?username={context.bot.username}&command=verify>={gt}&challenge={challenge}&uid={client.uid}" button = InlineKeyboardMarkup([[InlineKeyboardButton("验证", url=url)]]) await message.reply_text("请尽快点击下方手动验证", reply_markup=button) diff --git a/plugins/system/start.py b/plugins/system/start.py index 42abe76..aa22245 100644 --- a/plugins/system/start.py +++ b/plugins/system/start.py @@ -1,5 +1,6 @@ from typing import Optional +from genshin import GenshinException, Region from telegram import Update, ReplyKeyboardRemove, Message, User, InlineKeyboardMarkup, InlineKeyboardButton from telegram.constants import ChatAction from telegram.ext import CallbackContext, CommandHandler @@ -18,7 +19,6 @@ from plugins.genshin.verification import VerificationSystem from utils.decorators.restricts import restricts from utils.helpers import get_genshin_client from utils.log import logger -from utils.models.base import RegionEnum class StartPlugin(Plugin): @@ -117,30 +117,43 @@ class StartPlugin(Plugin): async def process_validate( self, message: Message, user: User, validate: Optional[str] = None, bot_username: Optional[str] = None ): - user_info = await self.user_service.get_user_by_id(user.id) - if user_info.region != RegionEnum.HYPERION: - await message.reply_text("非法用户") + try: + client = await get_genshin_client(user.id) + if client.region != Region.CHINESE: + await message.reply_text("非法用户") + return + except UserNotFoundError: + await message.reply_text("用户未找到") return - uid = user_info.yuanshen_uid - cookie = await self.cookies_service.get_cookies(user.id, RegionEnum.HYPERION) - client = Verification(cookie=cookie.cookies) + except CookiesNotFoundError: + await message.reply_text("检测到用户为UID绑定,无需认证") + return + try: + await client.get_genshin_notes() + except GenshinException as exc: + if exc.retcode != 1034: + raise exc + else: + await message.reply_text("账户正常,无需认证") + return + verification = Verification(cookies=client.cookie_manager.cookies) if validate: - _, challenge = await self.verification_system.get_challenge(uid) + _, challenge = await self.verification_system.get_challenge(client.uid) if challenge: - await client.verify(challenge, validate) + await verification.verify(challenge, validate) await message.reply_text("验证成功") else: await message.reply_text("验证失效") if bot_username: - data = await client.create() + data = await verification.create() challenge = data["challenge"] gt = data["gt"] - validate = await client.ajax(referer="https://webstatic.mihoyo.com/", gt=gt, challenge=challenge) + validate = await verification.ajax(referer="https://webstatic.mihoyo.com/", gt=gt, challenge=challenge) if validate: - await client.verify(challenge, validate) + await verification.verify(challenge, validate) await message.reply_text("验证成功") return - await self.sign_system.set_challenge(uid, gt, challenge) - url = f"{config.pass_challenge_user_web}?username={bot_username}&command=verify>={gt}&challenge={challenge}&uid={uid}" + await self.sign_system.set_challenge(client.uid, gt, challenge) + url = f"{config.pass_challenge_user_web}?username={bot_username}&command=verify>={gt}&challenge={challenge}&uid={client.uid}" button = InlineKeyboardMarkup([[InlineKeyboardButton("验证", url=url)]]) await message.reply_text("请尽快点击下方手动验证", reply_markup=button) diff --git a/utils/decorators/error.py b/utils/decorators/error.py index 775d4ce..e643b9a 100644 --- a/utils/decorators/error.py +++ b/utils/decorators/error.py @@ -9,7 +9,7 @@ from telegram import Update, ReplyKeyboardRemove, InlineKeyboardButton, InlineKe from telegram.error import BadRequest, TimedOut, Forbidden from telegram.ext import CallbackContext, ConversationHandler -from modules.apihelper.error import APIHelperException, ReturnCodeError, APIHelperTimedOut +from modules.apihelper.error import APIHelperException, ReturnCodeError, APIHelperTimedOut, ResponseException from utils.error import UrlResourcesNotFoundError from utils.log import logger @@ -115,7 +115,7 @@ def error_callable(func: Callable) -> Callable: logger.error("GenshinException") logger.exception(exc) await send_user_notification( - update, context, f"出错了呜呜呜 ~ 获取账号信息发生错误 错误信息为 { exc.msg if exc.msg else exc.retcode} ~ 请稍后再试" + update, context, f"出错了呜呜呜 ~ 获取账号信息发生错误 错误信息为 {exc.msg if exc.msg else exc.retcode} ~ 请稍后再试" ) return ConversationHandler.END except ReturnCodeError as exc: @@ -124,6 +124,12 @@ def error_callable(func: Callable) -> Callable: except APIHelperTimedOut: logger.warning("APIHelperException") await send_user_notification(update, context, "出错了呜呜呜 ~ API请求超时 ~ 请稍后再试") + except ResponseException as exc: + logger.error("APIHelperException [%s]%s", exc.code, exc.message) + await send_user_notification( + update, context, f"出错了呜呜呜 ~ API请求错误 错误信息为 {exc.message if exc.message else exc.code} ~ 请稍后再试" + ) + return ConversationHandler.END except APIHelperException as exc: logger.error("APIHelperException") logger.exception(exc)