修改 error_handler 异常处理

This commit is contained in:
洛水居室 2022-06-26 20:16:34 +08:00
parent 6057821989
commit 86dfce0b09
No known key found for this signature in database
GPG Key ID: C9DE87DA724B88FC

View File

@ -6,6 +6,7 @@ import ujson
from aiohttp import ClientConnectorError from aiohttp import ClientConnectorError
from genshin import InvalidCookies, GenshinException, TooManyRequests from genshin import InvalidCookies, GenshinException, TooManyRequests
from httpx import ConnectTimeout from httpx import ConnectTimeout
from pyrogram.errors import Forbidden
from telegram import Update, ReplyKeyboardRemove from telegram import Update, ReplyKeyboardRemove
from telegram.constants import ParseMode from telegram.constants import ParseMode
from telegram.error import BadRequest, TimedOut from telegram.error import BadRequest, TimedOut
@ -35,6 +36,10 @@ async def send_user_notification(update: Update, _: CallbackContext, text: str):
await message.reply_text(text, reply_markup=ReplyKeyboardRemove(), allow_sending_without_reply=True) await message.reply_text(text, reply_markup=ReplyKeyboardRemove(), allow_sending_without_reply=True)
except BadRequest as exc: except BadRequest as exc:
Log.error(f"发送 update_id[{update.update_id}] 错误信息失败 错误信息为 {str(exc)}") Log.error(f"发送 update_id[{update.update_id}] 错误信息失败 错误信息为 {str(exc)}")
except Forbidden as exc:
Log.error(f"发送 update_id[{update.update_id}] 错误信息失败 错误信息为 {str(exc)}")
except BaseException as exc:
Log.error(f"发送 update_id[{update.update_id}] 错误信息失败 错误信息为 {str(exc)}")
finally: finally:
pass pass
@ -48,12 +53,13 @@ def conversation_error_handler(func: Callable) -> Callable:
async def decorator(*args, **kwargs): async def decorator(*args, **kwargs):
update: Optional[Update] = None update: Optional[Update] = None
context: Optional[CallbackContext] = None context: Optional[CallbackContext] = None
for arg in args: if len(args) == 3:
if isinstance(arg, Update): # self update context
update = arg _, update, context = args
if isinstance(arg, CallbackContext): elif len(args) == 2:
context = arg # update context
if update is None or context is None: update, context = args
else:
return await func(*args, **kwargs) return await func(*args, **kwargs)
try: try:
return await func(*args, **kwargs) return await func(*args, **kwargs)
@ -95,6 +101,9 @@ def conversation_error_handler(func: Callable) -> Callable:
Log.warning("python-telegram-bot请求错误", exc) Log.warning("python-telegram-bot请求错误", exc)
await send_user_notification(update, context, f"telegram-bot-api请求错误 错误信息为 {str(exc)}") await send_user_notification(update, context, f"telegram-bot-api请求错误 错误信息为 {str(exc)}")
return ConversationHandler.END return ConversationHandler.END
except Forbidden as exc:
Log.warning("python-telegram-bot 返回 Forbidden", exc)
return ConversationHandler.END
return decorator return decorator