Skip to content

Commit

Permalink
优化不合法消息发送时的异常文本
Browse files Browse the repository at this point in the history
(cherry picked from commit e31744c)
  • Loading branch information
ssttkkl committed Mar 23, 2023
1 parent 9acdb24 commit 9d89e28
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 34 deletions.
20 changes: 17 additions & 3 deletions nonebot/adapters/kaiheila/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,15 @@ def _prepare_body(self, body: dict):
self.message = body.get("message", None)
self.data = body.get("data", None)


class UnauthorizedException(ActionFailed):
pass


class RateLimitException(ActionFailed):
pass


class NetworkError(BaseNetworkError, KaiheilaAdapterException):
"""
:说明:
Expand Down Expand Up @@ -89,9 +91,15 @@ class UnsupportedMessageType(KaiheilaAdapterException):
"""
:说明:
在发送不支持的消息类型时抛出,开黑啦 Bot 仅支持发送以下三种消息类型: "text"、"KMarkdown" 和 "Card", 尝试发送其他类型时抛出此异常
在发送不支持的消息类型时抛出,开黑啦 Bot 不支持发送音频消息
"""
pass

def __init__(self, message: str = ""):
super().__init__()
self.message = message

def __repr__(self) -> str:
return self.message


class UnsupportedMessageOperation(KaiheilaAdapterException):
Expand All @@ -100,7 +108,13 @@ class UnsupportedMessageOperation(KaiheilaAdapterException):
在调用不支持的 Message 或 MessageSegment 操作时抛出,例如对图片类型的 MessageSegment 使用加运算。
"""
pass

def __init__(self, message: str = ""):
super().__init__()
self.message = message

def __repr__(self) -> str:
return self.message


class ReconnectError(KaiheilaAdapterException):
Expand Down
68 changes: 37 additions & 31 deletions nonebot/adapters/kaiheila/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
from typing import Any, Type, Tuple, Union, Mapping, Iterable, Dict, cast, Optional

from deprecated import deprecated
from nonebot.typing import overrides

from nonebot.adapters import Message as BaseMessage
from nonebot.adapters import MessageSegment as BaseMessageSegment
from nonebot.typing import overrides

from .exception import UnsupportedMessageType, UnsupportedMessageOperation
from .utils import unescape_kmarkdown
from .utils import unescape_kmarkdown, escape_kmarkdown

msg_type_map = {
"text": 1,
Expand Down Expand Up @@ -58,7 +58,7 @@ def __str__(self) -> str:
elif self.type == "at":
return str(f"@{self.data['user_name']}")
else:
return segment_text.get(msg_type_map.get(self.type, ""), "[未知类型消息]")
return segment_text.get(self.type, "[未知类型消息]")

@property
def plain_text(self):
Expand All @@ -79,34 +79,20 @@ def __radd__(self, other: Union[str, "MessageSegment", Iterable["MessageSegment"
other = MessageSegment(self.type, {"content": other})
return Message(other.conduct(self))

def _conduct_single(self, other: "MessageSegment") -> "MessageSegment":
if self.type == "text":
return MessageSegment("text", {"content": self.data["content"] + other.data["content"]})
elif self.type == "kmarkdown":
return MessageSegment("kmarkdown", {"content": self.data["content"] + other.data["content"],
"raw_content": self.data["raw_content"] + other.data["raw_content"]})
else:
raise UnsupportedMessageOperation()

def conduct(self, other: Union[str, "MessageSegment", Iterable["MessageSegment"]]) -> "MessageSegment":
"""
连接两个或多个 MessageSegment,必须同时为 text 或 KMarkdown
连接两个或多个 MessageSegment,必须为纯文本段或 KMarkdown
"""
if self.type != "text" and self.type != "kmarkdown":
raise UnsupportedMessageOperation()

if isinstance(other, str):
other = [MessageSegment.text(other)]
elif isinstance(other, MessageSegment):
if isinstance(other, str) or isinstance(other, MessageSegment):
other = [other]
msg = Message([self, *other])
msg.reduce()

seg = self
for o in other:
if o.type == seg.type:
seg = self._conduct_single(o)
else:
raise UnsupportedMessageOperation()
return seg
if len(msg) != 1:
raise UnsupportedMessageOperation("必须为纯文本段或 KMarkdown 段")
else:
return msg[0]

@overrides(BaseMessageSegment)
def is_text(self) -> bool:
Expand Down Expand Up @@ -215,12 +201,29 @@ def reduce(self) -> None:
while index < len(self):
prev = self[index - 1]
cur = self[index]
if prev.type == "text" and cur.type == "text" \
or prev.type == "kmarkdown" and cur.type == "kmarkdown":
if prev.type == "text" and cur.type == "text":
self[index - 1] = MessageSegment(prev.type, {
"content": prev.data["content"] + cur.data["content"]
})
del self[index]
elif prev.type == "kmarkdown" and cur.type == "kmarkdown":
self[index - 1] = MessageSegment(prev.type, {
"content": prev.data["content"] + cur.data["content"],
"raw_content": prev.data["raw_content"] + cur.data["raw_content"],
})
del self[index]
elif prev.type == "kmarkdown" and cur.type == "text":
self[index - 1] = MessageSegment(prev.type, {
"content": prev.data["content"] + escape_kmarkdown(cur.data["content"]),
"raw_content": prev.data["raw_content"] + cur.data["content"],
})
del self[index]
elif prev.type == "text" and cur.type == "kmarkdown":
self[index - 1] = MessageSegment(prev.type, {
"content": escape_kmarkdown(prev.data["content"]) + cur.data["content"],
"raw_content": prev.data["content"] + cur.data["raw_content"],
})
del self[index]
else:
index += 1

Expand All @@ -238,7 +241,7 @@ def serialize(self, for_send: bool = True) -> Tuple[int, str]:
self.message.reduce()

if len(self.message) != 1:
raise UnsupportedMessageOperation()
raise UnsupportedMessageOperation("图片/视频/文件/卡片消息必须单独发送")

msg_type = self.message[0].type
msg_type_code = msg_type_map[msg_type]
Expand All @@ -248,8 +251,11 @@ def serialize(self, for_send: bool = True) -> Tuple[int, str]:
return msg_type_code, self.message[0].data['content']
elif msg_type in ("image", "video", "file"):
return msg_type_code, self.message[0].data['file_key']
elif msg_type == "audio" and not for_send:
return msg_type_code, self.message[0].data['file_key']
elif msg_type == "audio":
if not for_send:
return msg_type_code, self.message[0].data['file_key']
else:
raise UnsupportedMessageType("音频消息不支持发送")
else:
raise UnsupportedMessageType()

Expand Down

0 comments on commit 9d89e28

Please sign in to comment.