Handle All PlayerNotFoundError, CookiesNotFoundError

This commit is contained in:
omg-xtao 2023-08-21 22:42:44 +08:00 committed by GitHub
parent e2095edf81
commit 5e18290f9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 54 additions and 206 deletions

1
.gitignore vendored
View File

@ -136,6 +136,7 @@ logs/
report/
data/
/resources/*/*/test/
/resources/*/*/*.map
plugins/genshin/daily/daily.json
metadata/data/
resources/assets/

@ -1 +1 @@
Subproject commit 6f366f6367d29cc89643ddf591608f58826dd9dd
Subproject commit 5743ac6ea8ab35ab3149e13c66d0465ab253f29a

View File

@ -9,17 +9,16 @@ from arkowrapper import ArkoWrapper
from pytz import timezone
from simnet import GenshinClient
from simnet.errors import BadRequest as SimnetBadRequest
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Message, Update
from telegram import Message, Update
from telegram.constants import ChatAction, ParseMode
from telegram.ext import CallbackContext, filters
from telegram.helpers import create_deep_linked_url
from core.dependence.assets import AssetsService
from core.plugin import Plugin, handler
from core.services.cookies.error import TooManyRequestPublicCookies
from core.services.template.models import RenderGroupResult, RenderResult
from core.services.template.services import TemplateService
from plugins.tools.genshin import PlayerNotFoundError, CookiesNotFoundError, GenshinHelper
from plugins.tools.genshin import CookiesNotFoundError, GenshinHelper
from utils.log import logger
try:
@ -76,7 +75,7 @@ class AbyssPlugin(Plugin):
@handler.command("abyss", block=False)
@handler.message(filters.Regex(msg_pattern), block=False)
async def command_start(self, update: Update, context: CallbackContext) -> None:
async def command_start(self, update: Update, _: CallbackContext) -> None:
user = update.effective_user
message = update.effective_message
uid: Optional[int] = None
@ -147,17 +146,6 @@ class AbyssPlugin(Plugin):
except AbyssNotFoundError:
await message.reply_text("无法查询玩家挑战队伍详情,只能查询统计详情哦~")
return
except PlayerNotFoundError: # 若未找到账号
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_uid"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message)
self.add_delete_message_job(message)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
return
except TooManyRequestPublicCookies:
reply_message = await message.reply_text("查询次数太多,请您稍后重试")
if filters.ChatType.GROUPS.filter(message):

View File

@ -2,13 +2,12 @@ import asyncio
from typing import List, Optional, Sequence, TYPE_CHECKING
from simnet import GenshinClient
from simnet.errors import BadRequest as SimnetBadRequest, InvalidCookies
from simnet.errors import BadRequest as SimnetBadRequest
from simnet.models.genshin.calculator import CalculatorTalent, CalculatorCharacterDetails
from simnet.models.genshin.chronicle.characters import Character
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, User
from telegram.constants import ChatAction, ParseMode
from telegram import User
from telegram.constants import ChatAction
from telegram.ext import filters
from telegram.helpers import create_deep_linked_url
from core.dependence.assets import AssetsService
from core.plugin import Plugin, handler
@ -19,7 +18,7 @@ from core.services.template.models import FileType
from core.services.template.services import TemplateService
from metadata.genshin import AVATAR_DATA
from modules.wiki.base import Model
from plugins.tools.genshin import CharacterDetails, PlayerNotFoundError, CookiesNotFoundError, GenshinHelper
from plugins.tools.genshin import CharacterDetails, GenshinHelper
from utils.log import logger
if TYPE_CHECKING:
@ -70,40 +69,6 @@ class AvatarListPlugin(Plugin):
self.player_service = player_service
self.player_info_service = player_info_service
async def get_user_client(
self, update: "Update", context: "ContextTypes.DEFAULT_TYPE"
) -> Optional["GenshinClient"]:
message = update.effective_message
user = update.effective_user
try:
return await self.helper.get_genshin_client(user.id)
except PlayerNotFoundError: # 若未找到账号
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_cookie"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
except CookiesNotFoundError:
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_cookie"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"此功能需要绑定<code>cookie</code>后使用,请先私聊派蒙绑定账号",
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.HTML,
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text(
"此功能需要绑定<code>cookie</code>后使用,请先私聊派蒙进行绑定",
parse_mode=ParseMode.HTML,
reply_markup=InlineKeyboardMarkup(buttons),
)
async def get_avatar_data(self, character: Character, client: "GenshinClient") -> Optional["AvatarData"]:
detail = await self.character_details.get_character_details(client, character)
if detail is None:
@ -191,43 +156,29 @@ class AvatarListPlugin(Plugin):
@handler.command("avatars", block=False)
@handler.message(filters.Regex(r"^(全部)?练度统计$"), block=False)
async def avatar_list(self, update: "Update", context: "ContextTypes.DEFAULT_TYPE"):
async def avatar_list(self, update: "Update", _: "ContextTypes.DEFAULT_TYPE"):
user = update.effective_user
message = update.effective_message
all_avatars = "全部" in message.text or "all" in message.text # 是否发送全部角色
logger.info("用户 %s[%s] [bold]练度统计[/bold]: all=%s", user.full_name, user.id, all_avatars, extra={"markup": True})
client = await self.get_user_client(update, context)
if not client:
return
notice = await message.reply_text("派蒙需要收集整理数据,还请耐心等待哦~")
await message.reply_chat_action(ChatAction.TYPING)
notice = None
try:
characters = await client.get_genshin_characters(client.player_id)
avatar_datas: List[AvatarData] = await self.get_avatars_data(
characters, client, None if all_avatars else 20
)
except InvalidCookies as exc:
await notice.delete()
await client.get_genshin_user(client.player_id)
logger.warning("用户 %s[%s] 无法请求角色数数据 API返回信息为 [%s]%s", user.full_name, user.id, exc.ret_code, exc.original)
reply_message = await message.reply_text("出错了呜呜呜 ~ 当前访问令牌无法请求角色数数据请尝试重新获取Cookie。")
if filters.ChatType.GROUPS.filter(message):
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
return
async with self.helper.genshin(user.id) as client:
notice = await message.reply_text("派蒙需要收集整理数据,还请耐心等待哦~")
await message.reply_chat_action(ChatAction.TYPING)
characters = await client.get_genshin_characters(client.player_id)
avatar_datas: List[AvatarData] = await self.get_avatars_data(
characters, client, None if all_avatars else 20
)
except SimnetBadRequest as e:
await notice.delete()
if notice:
await notice.delete()
if e.ret_code == -502002:
reply_message = await message.reply_html("请先在米游社中使用一次<b>养成计算器</b>后再使用此功能~")
self.add_delete_message_job(reply_message, delay=20)
return
raise e
finally:
await client.shutdown()
name_card, avatar, nickname, rarity = await self.get_final_data(client.player_id, user)

View File

@ -3,15 +3,13 @@ from datetime import datetime
from typing import Optional, TYPE_CHECKING
from simnet.errors import DataNotPublic
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ChatAction
from telegram.ext import ConversationHandler, filters
from telegram.helpers import create_deep_linked_url
from core.plugin import Plugin, handler
from core.services.template.models import RenderResult
from core.services.template.services import TemplateService
from plugins.tools.genshin import PlayerNotFoundError, CookiesNotFoundError, GenshinHelper
from plugins.tools.genshin import GenshinHelper
from utils.log import logger
if TYPE_CHECKING:
@ -105,23 +103,6 @@ class DailyNotePlugin(Plugin):
# 获取当前用户的 genshin.Client
async with self.helper.genshin(user.id) as client:
render_result = await self._get_daily_note(client)
except (CookiesNotFoundError, PlayerNotFoundError):
buttons = [
[
InlineKeyboardButton(
"点我绑定账号", url=create_deep_linked_url(self.application.bot.username, "set_cookie")
)
]
]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
return
except DataNotPublic:
reply_message = await message.reply_text("查询失败惹,可能是便签功能被禁用了?请尝试通过米游社或者 hoyolab 获取一次便签信息后重试。")
if filters.ChatType.GROUPS.filter(message):

View File

@ -3,17 +3,15 @@ import re
from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from simnet.errors import DataNotPublic, BadRequest as SimnetBadRequest, InvalidCookies
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from simnet.errors import DataNotPublic, BadRequest as SimnetBadRequest
from telegram.constants import ChatAction
from telegram.ext import filters
from telegram.helpers import create_deep_linked_url
from core.plugin import Plugin, handler
from core.services.cookies import CookiesService
from core.services.template.models import RenderResult
from core.services.template.services import TemplateService
from plugins.tools.genshin import PlayerNotFoundError, CookiesNotFoundError, GenshinHelper
from plugins.tools.genshin import GenshinHelper
from utils.log import logger
if TYPE_CHECKING:
@ -113,35 +111,7 @@ class LedgerPlugin(Plugin):
await message.reply_chat_action(ChatAction.TYPING)
try:
async with self.helper.genshin(user.id) as client:
try:
render_result = await self._start_get_ledger(client, month)
except InvalidCookies as exc: # 如果抛出InvalidCookies 判断是否真的玄学过期(或权限不足?)
await client.get_genshin_user(client.player_id)
logger.warning(
"用户 %s[%s] 无法请求旅行札记数据 API返回信息为 [%s]%s", user.full_name, user.id, exc.ret_code, exc.original
)
reply_message = await message.reply_text("出错了呜呜呜 ~ 当前访问令牌无法请求角色数数据请尝试重新获取Cookie。")
if filters.ChatType.GROUPS.filter(message):
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
return
except (PlayerNotFoundError, CookiesNotFoundError):
buttons = [
[
InlineKeyboardButton(
"点我绑定账号", url=create_deep_linked_url(self.application.bot.username, "set_cookie")
)
]
]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
return
render_result = await self._start_get_ledger(client, month)
except DataNotPublic:
reply_message = await message.reply_text("查询失败惹,可能是旅行札记功能被禁用了?请先通过米游社或者 hoyolab 获取一次旅行札记后重试。")
if filters.ChatType.GROUPS.filter(message):

View File

@ -236,14 +236,3 @@ class PayLogPlugin(Plugin.Conversation):
[InlineKeyboardButton("点我导入", url=create_deep_linked_url(context.bot.username, "pay_log_import"))]
]
await message.reply_text("派蒙没有找到你的充值记录,快来点击按钮私聊派蒙导入吧~", reply_markup=InlineKeyboardMarkup(buttons))
except PlayerNotFoundError:
logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id)
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_uid"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))

View File

@ -2,7 +2,7 @@ from datetime import datetime
from typing import TYPE_CHECKING
from simnet.client.routes import InternationalRoute
from simnet.errors import InvalidCookies, BadRequest as SIMNetBadRequest
from simnet.errors import BadRequest as SIMNetBadRequest
from simnet.utils.player import recognize_genshin_server, recognize_genshin_game_biz
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ParseMode
@ -97,15 +97,6 @@ class RegTimePlugin(Plugin):
parse_mode=ParseMode.HTML,
reply_markup=InlineKeyboardMarkup(buttons),
)
except InvalidCookies as exc:
async with self.helper.genshin(user.id) as client:
await client.get_genshin_user(client.player_id)
logger.warning("用户 %s[%s] 无法请求注册时间 API返回信息为 [%s]%s", user.full_name, user.id, exc.ret_code, exc.original)
reply_message = await message.reply_text("出错了呜呜呜 ~ 当前访问令牌无法请求角色数数据,")
if filters.ChatType.GROUPS.filter(message):
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
return
except SIMNetBadRequest as exc:
if exc.ret_code == -501101:
await message.reply_text("当前角色冒险等阶未达到10级暂时无法获取信息")

View File

@ -1,6 +1,6 @@
from typing import Optional, Tuple
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram import Update
from telegram.constants import ChatAction
from telegram.ext import CommandHandler, CallbackContext
from telegram.ext import MessageHandler, filters
@ -14,7 +14,7 @@ from core.services.players import PlayersService
from core.services.task.models import Task as SignUser, TaskStatusEnum
from core.services.task.services import SignServices
from core.services.users.services import UserAdminService
from plugins.tools.genshin import PlayerNotFoundError, CookiesNotFoundError, GenshinHelper
from plugins.tools.genshin import GenshinHelper
from plugins.tools.sign import SignSystem, NeedChallenge
from utils.log import logger
@ -112,17 +112,6 @@ class Sign(Plugin):
reply_message = await message.reply_text(sign_text, allow_sending_without_reply=True)
if filters.ChatType.GROUPS.filter(reply_message):
self.add_delete_message_job(reply_message)
except (PlayerNotFoundError, CookiesNotFoundError):
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_cookie"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
except NeedChallenge as exc:
button = await self.sign_system.get_challenge_button(
context.bot.username,

View File

@ -2,16 +2,14 @@ import random
from typing import Optional, TYPE_CHECKING
from simnet.errors import BadRequest as SimnetBadRequest
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ChatAction
from telegram.ext import filters
from telegram.helpers import create_deep_linked_url
from core.plugin import Plugin, handler
from core.services.cookies.error import TooManyRequestPublicCookies
from core.services.template.models import RenderResult
from core.services.template.services import TemplateService
from plugins.tools.genshin import PlayerNotFoundError, CookiesNotFoundError, GenshinHelper
from plugins.tools.genshin import CookiesNotFoundError, GenshinHelper
from utils.log import logger
if TYPE_CHECKING:
@ -52,17 +50,6 @@ class PlayerStatsPlugins(Plugin):
except CookiesNotFoundError:
async with self.helper.public_genshin(user.id) as client:
render_result = await self.render(client, uid)
except PlayerNotFoundError:
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_cookie"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
return
except SimnetBadRequest as exc:
if exc.ret_code == 1034 and uid:
await message.reply_text("出错了呜呜呜 ~ 请稍后重试")

View File

@ -352,17 +352,6 @@ class WishLogPlugin(Plugin.Conversation):
[InlineKeyboardButton("点我导入", url=create_deep_linked_url(context.bot.username, "gacha_log_import"))]
]
await message.reply_text("派蒙没有找到你的抽卡记录,快来点击按钮私聊派蒙导入吧~", reply_markup=InlineKeyboardMarkup(buttons))
except PlayerNotFoundError:
logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id)
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_uid"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))
@handler(CommandHandler, command="gacha_count", block=False)
@handler(MessageHandler, filters=filters.Regex("^抽卡统计?(武器|角色|常驻|仅五星|)$"), block=False)
@ -417,15 +406,3 @@ class WishLogPlugin(Plugin.Conversation):
[InlineKeyboardButton("点我导入", url=create_deep_linked_url(context.bot.username, "gacha_log_import"))]
]
await message.reply_text("派蒙没有找到你的抽卡记录,快来私聊派蒙导入吧~", reply_markup=InlineKeyboardMarkup(buttons))
except PlayerNotFoundError:
logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id)
buttons = [[InlineKeyboardButton("点我绑定账号", url=create_deep_linked_url(context.bot.username, "set_uid"))]]
if filters.ChatType.GROUPS.filter(message):
reply_message = await message.reply_text(
"未查询到您所绑定的账号信息,请先私聊派蒙绑定账号", reply_markup=InlineKeyboardMarkup(buttons)
)
self.add_delete_message_job(reply_message, delay=30)
self.add_delete_message_job(message, delay=30)
else:
await message.reply_text("未查询到您所绑定的账号信息,请先绑定账号", reply_markup=InlineKeyboardMarkup(buttons))

View File

@ -23,6 +23,7 @@ from telegram.helpers import create_deep_linked_url
from core.config import config
from core.plugin import Plugin, error_handler
from gram_core.services.players.error import PlayerNotFoundError
from modules.apihelper.error import APIHelperException, APIHelperTimedOut, ResponseException, ReturnCodeError
from modules.errorpush import (
PbClient,
@ -30,6 +31,7 @@ from modules.errorpush import (
SentryClient,
SentryClientException,
)
from plugins.tools.genshin import CookiesNotFoundError, PlayerNotFoundError as GenshinPlayerNotFoundError
from utils.log import logger
from utils.patch.aiohttp import AioHttpTimeoutException
@ -77,6 +79,16 @@ class ErrorHandler(Plugin):
]
]
)
elif "绑定账号" in content:
buttons = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"点我绑定账号", url=create_deep_linked_url(self.application.bot.username, "set_cookie")
)
]
]
)
else:
buttons = ReplyKeyboardRemove()
@ -237,6 +249,16 @@ class ErrorHandler(Plugin):
self.create_notice_task(update, context, notice)
raise ApplicationHandlerStop
@error_handler()
async def process_player_and_cookie_not_found(self, update: object, context: CallbackContext):
if not isinstance(
context.error, (CookiesNotFoundError, PlayerNotFoundError, GenshinPlayerNotFoundError)
) or not isinstance(update, Update):
return
notice = "未查询到您所绑定的账号信息,请先私聊派蒙绑定账号"
self.create_notice_task(update, context, notice)
raise ApplicationHandlerStop
@error_handler(block=False)
async def process_z_error(self, update: object, context: CallbackContext) -> None:
# 必须 `process_` 加上 `z` 保证该函数最后一个注册

View File

@ -254,10 +254,12 @@ class GenshinHelper(Plugin):
stoken = client.cookies.get("stoken")
if stoken is not None:
try:
cookie_model.data["cookie_token"] = await client.get_cookie_token_by_stoken()
new_cookies = cookie_model.data.copy()
new_cookies["cookie_token"] = await client.get_cookie_token_by_stoken()
logger.success("用户 %s 刷新 cookie_token 成功", user_id)
cookie_model.data["ltoken"] = await client.get_ltoken_by_stoken()
new_cookies["ltoken"] = await client.get_ltoken_by_stoken()
logger.success("用户 %s 刷新 ltoken 成功", user_id)
cookie_model.data = new_cookies
await self.cookies_service.update(cookie_model)
except SimnetBadRequest as _exc:
logger.warning(