🎨 Cancel authentication if cookies is None

处理 CookiesNotFoundError 异常
This commit is contained in:
洛水居室 2022-11-12 23:08:25 +08:00
parent c73685e311
commit 9ed30d4143
No known key found for this signature in database
GPG Key ID: C9DE87DA724B88FC
4 changed files with 67 additions and 32 deletions

View File

@ -389,8 +389,8 @@ class Verification:
"Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7", "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
} }
def __init__(self, cookie: Dict = None): def __init__(self, cookies: Dict = None):
self.client = HOYORequest(headers=self.BBS_HEADERS, cookies=cookie) self.client = HOYORequest(headers=self.BBS_HEADERS, cookies=cookies)
def get_verification_headers(self, referer: str): def get_verification_headers(self, referer: str):
headers = self.VERIFICATION_HEADERS.copy() headers = self.VERIFICATION_HEADERS.copy()

View File

@ -1,5 +1,6 @@
from typing import Tuple, Optional from typing import Tuple, Optional
from genshin import Region, GenshinException
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackContext from telegram.ext import CallbackContext
@ -7,12 +8,14 @@ from core.base.redisdb import RedisDB
from core.baseplugin import BasePlugin from core.baseplugin import BasePlugin
from core.config import config from core.config import config
from core.cookies import CookiesService from core.cookies import CookiesService
from core.cookies.error import CookiesNotFoundError
from core.plugin import Plugin, handler from core.plugin import Plugin, handler
from core.user import UserService from core.user import UserService
from core.user.error import UserNotFoundError
from modules.apihelper.hyperion import Verification from modules.apihelper.hyperion import Verification
from utils.decorators.error import error_callable from utils.decorators.error import error_callable
from utils.decorators.restricts import restricts from utils.decorators.restricts import restricts
from utils.models.base import RegionEnum from utils.helpers import get_genshin_client
class VerificationSystem: class VerificationSystem:
@ -44,31 +47,44 @@ 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
user_info = await self.user_service.get_user_by_id(user.id) try:
if user_info.region != RegionEnum.HYPERION: client = await get_genshin_client(user.id)
if client.region != Region.CHINESE:
await message.reply_text("非法用户") await message.reply_text("非法用户")
return return
uid = user_info.yuanshen_uid except UserNotFoundError:
cookie = await self.cookies_service.get_cookies(user.id, RegionEnum.HYPERION) await message.reply_text("用户未找到")
client = Verification(cookie=cookie.cookies) return
except CookiesNotFoundError:
await message.reply_text("检测到用户为UID绑定无需认证")
return
verification = Verification(cookies=client.cookie_manager.cookies)
if context.args and len(context.args) > 0: if context.args and len(context.args) > 0:
validate = context.args[0] validate = context.args[0]
_, challenge = await self.system.get_challenge(uid) _, challenge = await self.system.get_challenge(client.uid)
if challenge: if challenge:
await client.verify(challenge, validate) await verification.verify(challenge, validate)
await message.reply_text("验证成功") await message.reply_text("验证成功")
else: else:
await message.reply_text("验证失效") await message.reply_text("验证失效")
return 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"] challenge = data["challenge"]
gt = data["gt"] 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: if validate:
await client.verify(challenge, validate) await verification.verify(challenge, validate)
await message.reply_text("验证成功") await message.reply_text("验证成功")
return return
await self.system.set_challenge(uid, gt, challenge) await self.system.set_challenge(client.uid, gt, challenge)
url = f"{config.pass_challenge_user_web}?username={context.bot.username}&command=verify&gt={gt}&challenge={challenge}&uid={uid}" url = f"{config.pass_challenge_user_web}?username={context.bot.username}&command=verify&gt={gt}&challenge={challenge}&uid={client.uid}"
button = InlineKeyboardMarkup([[InlineKeyboardButton("验证", url=url)]]) button = InlineKeyboardMarkup([[InlineKeyboardButton("验证", url=url)]])
await message.reply_text("请尽快点击下方手动验证", reply_markup=button) await message.reply_text("请尽快点击下方手动验证", reply_markup=button)

View File

@ -1,5 +1,6 @@
from typing import Optional from typing import Optional
from genshin import GenshinException, Region
from telegram import Update, ReplyKeyboardRemove, Message, User, InlineKeyboardMarkup, InlineKeyboardButton from telegram import Update, ReplyKeyboardRemove, Message, User, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.constants import ChatAction from telegram.constants import ChatAction
from telegram.ext import CallbackContext, CommandHandler from telegram.ext import CallbackContext, CommandHandler
@ -18,7 +19,6 @@ from plugins.genshin.verification import VerificationSystem
from utils.decorators.restricts import restricts from utils.decorators.restricts import restricts
from utils.helpers import get_genshin_client from utils.helpers import get_genshin_client
from utils.log import logger from utils.log import logger
from utils.models.base import RegionEnum
class StartPlugin(Plugin): class StartPlugin(Plugin):
@ -117,30 +117,43 @@ class StartPlugin(Plugin):
async def process_validate( async def process_validate(
self, message: Message, user: User, validate: Optional[str] = None, bot_username: Optional[str] = None 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) try:
if user_info.region != RegionEnum.HYPERION: client = await get_genshin_client(user.id)
if client.region != Region.CHINESE:
await message.reply_text("非法用户") await message.reply_text("非法用户")
return return
uid = user_info.yuanshen_uid except UserNotFoundError:
cookie = await self.cookies_service.get_cookies(user.id, RegionEnum.HYPERION) await message.reply_text("用户未找到")
client = Verification(cookie=cookie.cookies) return
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: if validate:
_, challenge = await self.verification_system.get_challenge(uid) _, challenge = await self.verification_system.get_challenge(client.uid)
if challenge: if challenge:
await client.verify(challenge, validate) await verification.verify(challenge, validate)
await message.reply_text("验证成功") await message.reply_text("验证成功")
else: else:
await message.reply_text("验证失效") await message.reply_text("验证失效")
if bot_username: if bot_username:
data = await client.create() data = await verification.create()
challenge = data["challenge"] challenge = data["challenge"]
gt = data["gt"] 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: if validate:
await client.verify(challenge, validate) await verification.verify(challenge, validate)
await message.reply_text("验证成功") await message.reply_text("验证成功")
return return
await self.sign_system.set_challenge(uid, gt, challenge) await self.sign_system.set_challenge(client.uid, gt, challenge)
url = f"{config.pass_challenge_user_web}?username={bot_username}&command=verify&gt={gt}&challenge={challenge}&uid={uid}" url = f"{config.pass_challenge_user_web}?username={bot_username}&command=verify&gt={gt}&challenge={challenge}&uid={client.uid}"
button = InlineKeyboardMarkup([[InlineKeyboardButton("验证", url=url)]]) button = InlineKeyboardMarkup([[InlineKeyboardButton("验证", url=url)]])
await message.reply_text("请尽快点击下方手动验证", reply_markup=button) await message.reply_text("请尽快点击下方手动验证", reply_markup=button)

View File

@ -9,7 +9,7 @@ from telegram import Update, ReplyKeyboardRemove, InlineKeyboardButton, InlineKe
from telegram.error import BadRequest, TimedOut, Forbidden from telegram.error import BadRequest, TimedOut, Forbidden
from telegram.ext import CallbackContext, ConversationHandler 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.error import UrlResourcesNotFoundError
from utils.log import logger from utils.log import logger
@ -115,7 +115,7 @@ def error_callable(func: Callable) -> Callable:
logger.error("GenshinException") logger.error("GenshinException")
logger.exception(exc) logger.exception(exc)
await send_user_notification( 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 return ConversationHandler.END
except ReturnCodeError as exc: except ReturnCodeError as exc:
@ -124,6 +124,12 @@ def error_callable(func: Callable) -> Callable:
except APIHelperTimedOut: except APIHelperTimedOut:
logger.warning("APIHelperException") logger.warning("APIHelperException")
await send_user_notification(update, context, "出错了呜呜呜 ~ API请求超时 ~ 请稍后再试") 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: except APIHelperException as exc:
logger.error("APIHelperException") logger.error("APIHelperException")
logger.exception(exc) logger.exception(exc)