mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-01-19 01:18:19 +08:00
🏗️ change exception structure
This commit is contained in:
parent
8f89e0f26e
commit
9658e446e5
@ -10,6 +10,7 @@ CQHTTP (OneBot) v11 协议适配
|
||||
https://github.com/howmanybots/onebot/blob/master/README.md
|
||||
"""
|
||||
|
||||
from .message import Message, MessageSegment
|
||||
from .bot import Bot
|
||||
from .utils import log
|
||||
from .event import Event
|
||||
from .message import Message, MessageSegment
|
||||
from .bot import Bot, _check_at_me, _check_nickname, _check_reply
|
||||
|
@ -8,15 +8,16 @@ import httpx
|
||||
|
||||
from nonebot.log import logger
|
||||
from nonebot.config import Config
|
||||
from nonebot.message import handle_event
|
||||
from nonebot.typing import overrides, Driver, WebSocket, NoReturn
|
||||
from nonebot.typing import Any, Dict, Union, Optional
|
||||
from nonebot.adapters import BaseBot
|
||||
from nonebot.exception import NetworkError, ActionFailed, RequestDenied, ApiNotAvailable
|
||||
from nonebot.message import handle_event
|
||||
from nonebot.typing import Any, Dict, Union, Optional
|
||||
from nonebot.typing import overrides, Driver, WebSocket, NoReturn
|
||||
from nonebot.exception import NetworkError, RequestDenied, ApiNotAvailable
|
||||
|
||||
from .message import Message, MessageSegment
|
||||
from .utils import log, get_auth_bearer
|
||||
from .event import Event
|
||||
from .exception import ApiError
|
||||
from .utils import log, get_auth_bearer
|
||||
from .message import Message, MessageSegment
|
||||
|
||||
|
||||
async def _check_reply(bot: "Bot", event: "Event"):
|
||||
@ -159,11 +160,11 @@ def _handle_api_result(
|
||||
|
||||
:异常:
|
||||
|
||||
- ``ActionFailed``: API 调用失败
|
||||
- ``ApiError``: API 调用失败
|
||||
"""
|
||||
if isinstance(result, dict):
|
||||
if result.get("status") == "failed":
|
||||
raise ActionFailed(retcode=result.get("retcode"))
|
||||
raise ApiError(retcode=result.get("retcode"))
|
||||
return result.get("data")
|
||||
|
||||
|
||||
@ -317,7 +318,7 @@ class Bot(BaseBot):
|
||||
:异常:
|
||||
|
||||
- ``NetworkError``: 网络错误
|
||||
- ``ActionFailed``: API 调用失败
|
||||
- ``ApiError``: API 调用失败
|
||||
"""
|
||||
if "self_id" in data:
|
||||
self_id = data.pop("self_id")
|
||||
@ -368,8 +369,8 @@ class Bot(BaseBot):
|
||||
|
||||
@overrides(BaseBot)
|
||||
async def send(self,
|
||||
event: "Event",
|
||||
message: Union[str, "Message", "MessageSegment"],
|
||||
event: Event,
|
||||
message: Union[str, Message, MessageSegment],
|
||||
at_sender: bool = False,
|
||||
**kwargs) -> Union[Any, NoReturn]:
|
||||
"""
|
||||
@ -392,7 +393,7 @@ class Bot(BaseBot):
|
||||
|
||||
- ``ValueError``: 缺少 ``user_id``, ``group_id``
|
||||
- ``NetworkError``: 网络错误
|
||||
- ``ActionFailed``: API 调用失败
|
||||
- ``ApiError``: API 调用失败
|
||||
"""
|
||||
msg = message if isinstance(message, Message) else Message(message)
|
||||
|
||||
|
29
nonebot/adapters/cqhttp/exception.py
Normal file
29
nonebot/adapters/cqhttp/exception.py
Normal file
@ -0,0 +1,29 @@
|
||||
from nonebot.exception import AdapterException, ActionFailed
|
||||
|
||||
|
||||
class CQHTTPAdapterException(AdapterException):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("cqhttp")
|
||||
|
||||
|
||||
class ApiError(CQHTTPAdapterException, ActionFailed):
|
||||
"""
|
||||
:说明:
|
||||
|
||||
API 请求返回错误信息。
|
||||
|
||||
:参数:
|
||||
|
||||
* ``retcode: Optional[int]``: 错误码
|
||||
"""
|
||||
|
||||
def __init__(self, retcode: Optional[int] = None):
|
||||
super().__init__()
|
||||
self.retcode = retcode
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ActionFailed retcode={self.retcode}>"
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
@ -1,18 +1,19 @@
|
||||
from datetime import datetime
|
||||
import httpx
|
||||
from datetime import datetime
|
||||
|
||||
from nonebot.log import logger
|
||||
from nonebot.config import Config
|
||||
from nonebot.adapters import BaseBot
|
||||
from nonebot.message import handle_event
|
||||
from nonebot.typing import Driver, NoReturn
|
||||
from nonebot.typing import Any, Union, Optional
|
||||
from nonebot.adapters import BaseBot
|
||||
from nonebot.exception import NetworkError, RequestDenied, ApiNotAvailable
|
||||
from .exception import ApiError, SessionExpired
|
||||
from .utils import check_legal, log
|
||||
|
||||
from .event import Event
|
||||
from .message import Message, MessageSegment
|
||||
from .model import MessageModel
|
||||
from .utils import check_legal, log
|
||||
from .message import Message, MessageSegment
|
||||
from .exception import ApiError, SessionExpired
|
||||
|
||||
|
||||
class Bot(BaseBot):
|
||||
@ -38,12 +39,11 @@ class Bot(BaseBot):
|
||||
body: Optional[dict]) -> Union[str, NoReturn]:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
钉钉协议鉴权。参考 `鉴权 <https://ding-doc.dingtalk.com/doc#/serverapi2/elzz1p>`_
|
||||
"""
|
||||
timestamp = headers.get("timestamp")
|
||||
sign = headers.get("sign")
|
||||
log("DEBUG", "headers: {}".format(headers))
|
||||
log("DEBUG", "body: {}".format(body))
|
||||
|
||||
# 检查 timestamp
|
||||
if not timestamp:
|
||||
@ -69,7 +69,6 @@ class Bot(BaseBot):
|
||||
message = MessageModel.parse_obj(body)
|
||||
if not message:
|
||||
return
|
||||
log("DEBUG", "message: {}".format(message))
|
||||
|
||||
try:
|
||||
event = Event(message)
|
||||
@ -110,7 +109,6 @@ class Bot(BaseBot):
|
||||
return await bot.call_api(api, **data)
|
||||
|
||||
log("DEBUG", f"Calling API <y>{api}</y>")
|
||||
log("DEBUG", f"Calling data <y>{data}</y>")
|
||||
|
||||
if api == "send_message":
|
||||
raw_event: MessageModel = data["raw_event"]
|
||||
@ -149,7 +147,7 @@ class Bot(BaseBot):
|
||||
raise NetworkError("HTTP request failed")
|
||||
|
||||
async def send(self,
|
||||
event: "Event",
|
||||
event: Event,
|
||||
message: Union[str, "Message", "MessageSegment"],
|
||||
at_sender: bool = False,
|
||||
**kwargs) -> Union[Any, NoReturn]:
|
||||
@ -176,10 +174,8 @@ class Bot(BaseBot):
|
||||
- ``ActionFailed``: API 调用失败
|
||||
"""
|
||||
msg = message if isinstance(message, Message) else Message(message)
|
||||
log("DEBUG", f"send -> msg: {msg}")
|
||||
|
||||
at_sender = at_sender and bool(event.user_id)
|
||||
log("DEBUG", f"send -> at_sender: {at_sender}")
|
||||
params = {"raw_event": event.raw_event}
|
||||
params.update(kwargs)
|
||||
|
||||
@ -187,6 +183,5 @@ class Bot(BaseBot):
|
||||
params["message"] = f"@{event.user_id} " + msg
|
||||
else:
|
||||
params["message"] = msg
|
||||
log("DEBUG", f"send -> params: {params}")
|
||||
|
||||
return await self.call_api("send_message", **params)
|
||||
|
@ -1,4 +1,4 @@
|
||||
from nonebot.exception import AdapterException
|
||||
from nonebot.exception import AdapterException, ActionFailed, ApiNotAvailable
|
||||
|
||||
|
||||
class DingAdapterException(AdapterException):
|
||||
@ -10,10 +10,10 @@ class DingAdapterException(AdapterException):
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__("DING")
|
||||
super().__init__("ding")
|
||||
|
||||
|
||||
class ApiError(DingAdapterException):
|
||||
class ApiError(DingAdapterException, ActionFailed):
|
||||
"""
|
||||
:说明:
|
||||
|
||||
@ -30,7 +30,7 @@ class ApiError(DingAdapterException):
|
||||
return f"<ApiError errcode={self.errcode} errmsg={self.errmsg}>"
|
||||
|
||||
|
||||
class SessionExpired(DingAdapterException):
|
||||
class SessionExpired(DingAdapterException, ApiNotAvailable):
|
||||
"""
|
||||
:说明:
|
||||
|
||||
@ -39,4 +39,4 @@ class SessionExpired(DingAdapterException):
|
||||
"""
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<sessionWebhook is Expired>"
|
||||
return f"<Session Webhook is Expired>"
|
||||
|
@ -155,17 +155,5 @@ class ActionFailed(AdapterException):
|
||||
:说明:
|
||||
|
||||
API 请求成功返回数据,但 API 操作失败。
|
||||
|
||||
:参数:
|
||||
|
||||
* ``retcode: Optional[int]``: 错误代码
|
||||
"""
|
||||
|
||||
def __init__(self, retcode: Optional[int]):
|
||||
self.retcode = retcode
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ActionFailed, retcode={self.retcode}>"
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
pass
|
||||
|
Loading…
Reference in New Issue
Block a user