We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bug: MessageTemplate无法对数字字符等类型进行格式化
**描述问题：**

上游issue：https://github.com/mnixry/nonebot-plugin-gocqhttp/issues/281

**如何复现？**

在一个消息模板中格式化数字

**期望的结果**

不报错

**故障原因**

推测原因如下

在函数`Message.__iadd__`中，如果相加类型错误会抛出`ValueError`异常：
https://github.com/nonebot/nonebot2/blob/549a37b172ceeedac183fb48b58fe13a16eb56cd/nonebot/internal/adapter/message.py#L181-L190

在`MessageTemplate._add`中，只对一般类型相加出错的`TypeError`做了处理：
https://github.com/nonebot/nonebot2/blob/549a37b172ceeedac183fb48b58fe13a16eb56cd/nonebot/internal/adapter/template.py#L180-L184

因此导致了该错误

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nonebot/internal/adapter/message.py`
Content:
```
1 import abc
2 from copy import deepcopy
3 from dataclasses import field, asdict, dataclass
4 from typing import (
5     Any,
6     Dict,
7     List,
8     Type,
9     Tuple,
10     Union,
11     Generic,
12     TypeVar,
13     Iterable,
14     Optional,
15     overload,
16 )
17 
18 from pydantic import parse_obj_as
19 
20 from .template import MessageTemplate
21 
22 T = TypeVar("T")
23 TMS = TypeVar("TMS", bound="MessageSegment")
24 TM = TypeVar("TM", bound="Message")
25 
26 
27 @dataclass
28 class MessageSegment(abc.ABC, Generic[TM]):
29     """消息段基类"""
30 
31     type: str
32     """消息段类型"""
33     data: Dict[str, Any] = field(default_factory=dict)
34     """消息段数据"""
35 
36     @classmethod
37     @abc.abstractmethod
38     def get_message_class(cls) -> Type[TM]:
39         """获取消息数组类型"""
40         raise NotImplementedError
41 
42     @abc.abstractmethod
43     def __str__(self) -> str:
44         """该消息段所代表的 str，在命令匹配部分使用"""
45         raise NotImplementedError
46 
47     def __len__(self) -> int:
48         return len(str(self))
49 
50     def __ne__(self: T, other: T) -> bool:
51         return not self == other
52 
53     def __add__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:
54         return self.get_message_class()(self) + other
55 
56     def __radd__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:
57         return self.get_message_class()(other) + self
58 
59     @classmethod
60     def __get_validators__(cls):
61         yield cls._validate
62 
63     @classmethod
64     def _validate(cls, value):
65         if isinstance(value, cls):
66             return value
67         if not isinstance(value, dict):
68             raise ValueError(f"Expected dict for MessageSegment, got {type(value)}")
69         if "type" not in value:
70             raise ValueError(
71                 f"Expected dict with 'type' for MessageSegment, got {value}"
72             )
73         return cls(type=value["type"], data=value.get("data", {}))
74 
75     def get(self, key: str, default: Any = None):
76         return asdict(self).get(key, default)
77 
78     def keys(self):
79         return asdict(self).keys()
80 
81     def values(self):
82         return asdict(self).values()
83 
84     def items(self):
85         return asdict(self).items()
86 
87     def copy(self: T) -> T:
88         return deepcopy(self)
89 
90     @abc.abstractmethod
91     def is_text(self) -> bool:
92         """当前消息段是否为纯文本"""
93         raise NotImplementedError
94 
95 
96 class Message(List[TMS], abc.ABC):
97     """消息数组
98 
99     参数:
100         message: 消息内容
101     """
102 
103     def __init__(
104         self,
105         message: Union[str, None, Iterable[TMS], TMS] = None,
106     ):
107         super().__init__()
108         if message is None:
109             return
110         elif isinstance(message, str):
111             self.extend(self._construct(message))
112         elif isinstance(message, MessageSegment):
113             self.append(message)
114         elif isinstance(message, Iterable):
115             self.extend(message)
116         else:
117             self.extend(self._construct(message))  # pragma: no cover
118 
119     @classmethod
120     def template(cls: Type[TM], format_string: Union[str, TM]) -> MessageTemplate[TM]:
121         """创建消息模板。
122 
123         用法和 `str.format` 大致相同, 但是可以输出消息对象, 并且支持以 `Message` 对象作为消息模板
124 
125         并且提供了拓展的格式化控制符, 可以用适用于该消息类型的 `MessageSegment` 的工厂方法创建消息
126 
127         参数:
128             format_string: 格式化模板
129 
130         返回:
131             消息格式化器
132         """
133         return MessageTemplate(format_string, cls)
134 
135     @classmethod
136     @abc.abstractmethod
137     def get_segment_class(cls) -> Type[TMS]:
138         """获取消息段类型"""
139         raise NotImplementedError
140 
141     def __str__(self) -> str:
142         return "".join(str(seg) for seg in self)
143 
144     @classmethod
145     def __get_validators__(cls):
146         yield cls._validate
147 
148     @classmethod
149     def _validate(cls, value):
150         if isinstance(value, cls):
151             return value
152         elif isinstance(value, Message):
153             raise ValueError(f"Type {type(value)} can not be converted to {cls}")
154         elif isinstance(value, str):
155             pass
156         elif isinstance(value, dict):
157             value = parse_obj_as(cls.get_segment_class(), value)
158         elif isinstance(value, Iterable):
159             value = [parse_obj_as(cls.get_segment_class(), v) for v in value]
160         else:
161             raise ValueError(
162                 f"Expected str, dict or iterable for Message, got {type(value)}"
163             )
164         return cls(value)
165 
166     @staticmethod
167     @abc.abstractmethod
168     def _construct(msg: str) -> Iterable[TMS]:
169         """构造消息数组"""
170         raise NotImplementedError
171 
172     def __add__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:
173         result = self.copy()
174         result += other
175         return result
176 
177     def __radd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:
178         result = self.__class__(other)
179         return result + self
180 
181     def __iadd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:
182         if isinstance(other, str):
183             self.extend(self._construct(other))
184         elif isinstance(other, MessageSegment):
185             self.append(other)
186         elif isinstance(other, Iterable):
187             self.extend(other)
188         else:
189             raise ValueError(f"Unsupported type: {type(other)}")  # pragma: no cover
190         return self
191 
192     @overload
193     def __getitem__(self: TM, __args: str) -> TM:
194         """
195         参数:
196             __args: 消息段类型
197 
198         返回:
199             所有类型为 `__args` 的消息段
200         """
201 
202     @overload
203     def __getitem__(self, __args: Tuple[str, int]) -> TMS:
204         """
205         参数:
206             __args: 消息段类型和索引
207 
208         返回:
209             类型为 `__args[0]` 的消息段第 `__args[1]` 个
210         """
211 
212     @overload
213     def __getitem__(self: TM, __args: Tuple[str, slice]) -> TM:
214         """
215         参数:
216             __args: 消息段类型和切片
217 
218         返回:
219             类型为 `__args[0]` 的消息段切片 `__args[1]`
220         """
221 
222     @overload
223     def __getitem__(self, __args: int) -> TMS:
224         """
225         参数:
226             __args: 索引
227 
228         返回:
229             第 `__args` 个消息段
230         """
231 
232     @overload
233     def __getitem__(self: TM, __args: slice) -> TM:
234         """
235         参数:
236             __args: 切片
237 
238         返回:
239             消息切片 `__args`
240         """
241 
242     def __getitem__(
243         self: TM,
244         args: Union[
245             str,
246             Tuple[str, int],
247             Tuple[str, slice],
248             int,
249             slice,
250         ],
251     ) -> Union[TMS, TM]:
252         arg1, arg2 = args if isinstance(args, tuple) else (args, None)
253         if isinstance(arg1, int) and arg2 is None:
254             return super().__getitem__(arg1)
255         elif isinstance(arg1, slice) and arg2 is None:
256             return self.__class__(super().__getitem__(arg1))
257         elif isinstance(arg1, str) and arg2 is None:
258             return self.__class__(seg for seg in self if seg.type == arg1)
259         elif isinstance(arg1, str) and isinstance(arg2, int):
260             return [seg for seg in self if seg.type == arg1][arg2]
261         elif isinstance(arg1, str) and isinstance(arg2, slice):
262             return self.__class__([seg for seg in self if seg.type == arg1][arg2])
263         else:
264             raise ValueError("Incorrect arguments to slice")  # pragma: no cover
265 
266     def index(self, value: Union[TMS, str], *args) -> int:
267         if isinstance(value, str):
268             first_segment = next((seg for seg in self if seg.type == value), None)
269             if first_segment is None:
270                 raise ValueError(f"Segment with type {value} is not in message")
271             return super().index(first_segment, *args)
272         return super().index(value, *args)
273 
274     def get(self: TM, type_: str, count: Optional[int] = None) -> TM:
275         if count is None:
276             return self[type_]
277 
278         iterator, filtered = (
279             seg for seg in self if seg.type == type_
280         ), self.__class__()
281         for _ in range(count):
282             seg = next(iterator, None)
283             if seg is None:
284                 break
285             filtered.append(seg)
286         return filtered
287 
288     def count(self, value: Union[TMS, str]) -> int:
289         return len(self[value]) if isinstance(value, str) else super().count(value)
290 
291     def append(self: TM, obj: Union[str, TMS]) -> TM:
292         """添加一个消息段到消息数组末尾。
293 
294         参数:
295             obj: 要添加的消息段
296         """
297         if isinstance(obj, MessageSegment):
298             super().append(obj)
299         elif isinstance(obj, str):
300             self.extend(self._construct(obj))
301         else:
302             raise ValueError(f"Unexpected type: {type(obj)} {obj}")  # pragma: no cover
303         return self
304 
305     def extend(self: TM, obj: Union[TM, Iterable[TMS]]) -> TM:
306         """拼接一个消息数组或多个消息段到消息数组末尾。
307 
308         参数:
309             obj: 要添加的消息数组
310         """
311         for segment in obj:
312             self.append(segment)
313         return self
314 
315     def copy(self: TM) -> TM:
316         return deepcopy(self)
317 
318     def extract_plain_text(self) -> str:
319         """提取消息内纯文本消息"""
320 
321         return "".join(str(seg) for seg in self if seg.is_text())
322 
323 
324 __autodoc__ = {
325     "MessageSegment.__str__": True,
326     "MessageSegment.__add__": True,
327     "Message.__getitem__": True,
328     "Message._construct": True,
329 }
330
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/nonebot/internal/adapter/message.py b/nonebot/internal/adapter/message.py
--- a/nonebot/internal/adapter/message.py
+++ b/nonebot/internal/adapter/message.py
@@ -186,7 +186,7 @@
         elif isinstance(other, Iterable):
             self.extend(other)
         else:
-            raise ValueError(f"Unsupported type: {type(other)}")  # pragma: no cover
+            raise TypeError(f"Unsupported type {type(other)!r}")
         return self
 
     @overload

{"golden_diff": "diff --git a/nonebot/internal/adapter/message.py b/nonebot/internal/adapter/message.py\n--- a/nonebot/internal/adapter/message.py\n+++ b/nonebot/internal/adapter/message.py\n@@ -186,7 +186,7 @@\n         elif isinstance(other, Iterable):\n             self.extend(other)\n         else:\n-            raise ValueError(f\"Unsupported type: {type(other)}\")  # pragma: no cover\n+            raise TypeError(f\"Unsupported type {type(other)!r}\")\n         return self\n \n     @overload\n", "issue": "Bug: MessageTemplate\u65e0\u6cd5\u5bf9\u6570\u5b57\u5b57\u7b26\u7b49\u7c7b\u578b\u8fdb\u884c\u683c\u5f0f\u5316\n**\u63cf\u8ff0\u95ee\u9898\uff1a**\r\n\r\n\u4e0a\u6e38issue\uff1ahttps://github.com/mnixry/nonebot-plugin-gocqhttp/issues/281\r\n\r\n**\u5982\u4f55\u590d\u73b0\uff1f**\r\n\r\n\u5728\u4e00\u4e2a\u6d88\u606f\u6a21\u677f\u4e2d\u683c\u5f0f\u5316\u6570\u5b57\r\n\r\n**\u671f\u671b\u7684\u7ed3\u679c**\r\n\r\n\u4e0d\u62a5\u9519\r\n\r\n**\u6545\u969c\u539f\u56e0**\r\n\r\n\u63a8\u6d4b\u539f\u56e0\u5982\u4e0b\r\n\r\n\u5728\u51fd\u6570`Message.__iadd__`\u4e2d\uff0c\u5982\u679c\u76f8\u52a0\u7c7b\u578b\u9519\u8bef\u4f1a\u629b\u51fa`ValueError`\u5f02\u5e38\uff1a\r\nhttps://github.com/nonebot/nonebot2/blob/549a37b172ceeedac183fb48b58fe13a16eb56cd/nonebot/internal/adapter/message.py#L181-L190\r\n\r\n\u5728`MessageTemplate._add`\u4e2d\uff0c\u53ea\u5bf9\u4e00\u822c\u7c7b\u578b\u76f8\u52a0\u51fa\u9519\u7684`TypeError`\u505a\u4e86\u5904\u7406\uff1a\r\nhttps://github.com/nonebot/nonebot2/blob/549a37b172ceeedac183fb48b58fe13a16eb56cd/nonebot/internal/adapter/template.py#L180-L184\r\n\r\n\u56e0\u6b64\u5bfc\u81f4\u4e86\u8be5\u9519\u8bef\n", "before_files": [{"content": "import abc\nfrom copy import deepcopy\nfrom dataclasses import field, asdict, dataclass\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    Type,\n    Tuple,\n    Union,\n    Generic,\n    TypeVar,\n    Iterable,\n    Optional,\n    overload,\n)\n\nfrom pydantic import parse_obj_as\n\nfrom .template import MessageTemplate\n\nT = TypeVar(\"T\")\nTMS = TypeVar(\"TMS\", bound=\"MessageSegment\")\nTM = TypeVar(\"TM\", bound=\"Message\")\n\n\n@dataclass\nclass MessageSegment(abc.ABC, Generic[TM]):\n    \"\"\"\u6d88\u606f\u6bb5\u57fa\u7c7b\"\"\"\n\n    type: str\n    \"\"\"\u6d88\u606f\u6bb5\u7c7b\u578b\"\"\"\n    data: Dict[str, Any] = field(default_factory=dict)\n    \"\"\"\u6d88\u606f\u6bb5\u6570\u636e\"\"\"\n\n    @classmethod\n    @abc.abstractmethod\n    def get_message_class(cls) -> Type[TM]:\n        \"\"\"\u83b7\u53d6\u6d88\u606f\u6570\u7ec4\u7c7b\u578b\"\"\"\n        raise NotImplementedError\n\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        \"\"\"\u8be5\u6d88\u606f\u6bb5\u6240\u4ee3\u8868\u7684 str\uff0c\u5728\u547d\u4ee4\u5339\u914d\u90e8\u5206\u4f7f\u7528\"\"\"\n        raise NotImplementedError\n\n    def __len__(self) -> int:\n        return len(str(self))\n\n    def __ne__(self: T, other: T) -> bool:\n        return not self == other\n\n    def __add__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        return self.get_message_class()(self) + other\n\n    def __radd__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        return self.get_message_class()(other) + self\n\n    @classmethod\n    def __get_validators__(cls):\n        yield cls._validate\n\n    @classmethod\n    def _validate(cls, value):\n        if isinstance(value, cls):\n            return value\n        if not isinstance(value, dict):\n            raise ValueError(f\"Expected dict for MessageSegment, got {type(value)}\")\n        if \"type\" not in value:\n            raise ValueError(\n                f\"Expected dict with 'type' for MessageSegment, got {value}\"\n            )\n        return cls(type=value[\"type\"], data=value.get(\"data\", {}))\n\n    def get(self, key: str, default: Any = None):\n        return asdict(self).get(key, default)\n\n    def keys(self):\n        return asdict(self).keys()\n\n    def values(self):\n        return asdict(self).values()\n\n    def items(self):\n        return asdict(self).items()\n\n    def copy(self: T) -> T:\n        return deepcopy(self)\n\n    @abc.abstractmethod\n    def is_text(self) -> bool:\n        \"\"\"\u5f53\u524d\u6d88\u606f\u6bb5\u662f\u5426\u4e3a\u7eaf\u6587\u672c\"\"\"\n        raise NotImplementedError\n\n\nclass Message(List[TMS], abc.ABC):\n    \"\"\"\u6d88\u606f\u6570\u7ec4\n\n    \u53c2\u6570:\n        message: \u6d88\u606f\u5185\u5bb9\n    \"\"\"\n\n    def __init__(\n        self,\n        message: Union[str, None, Iterable[TMS], TMS] = None,\n    ):\n        super().__init__()\n        if message is None:\n            return\n        elif isinstance(message, str):\n            self.extend(self._construct(message))\n        elif isinstance(message, MessageSegment):\n            self.append(message)\n        elif isinstance(message, Iterable):\n            self.extend(message)\n        else:\n            self.extend(self._construct(message))  # pragma: no cover\n\n    @classmethod\n    def template(cls: Type[TM], format_string: Union[str, TM]) -> MessageTemplate[TM]:\n        \"\"\"\u521b\u5efa\u6d88\u606f\u6a21\u677f\u3002\n\n        \u7528\u6cd5\u548c `str.format` \u5927\u81f4\u76f8\u540c, \u4f46\u662f\u53ef\u4ee5\u8f93\u51fa\u6d88\u606f\u5bf9\u8c61, \u5e76\u4e14\u652f\u6301\u4ee5 `Message` \u5bf9\u8c61\u4f5c\u4e3a\u6d88\u606f\u6a21\u677f\n\n        \u5e76\u4e14\u63d0\u4f9b\u4e86\u62d3\u5c55\u7684\u683c\u5f0f\u5316\u63a7\u5236\u7b26, \u53ef\u4ee5\u7528\u9002\u7528\u4e8e\u8be5\u6d88\u606f\u7c7b\u578b\u7684 `MessageSegment` \u7684\u5de5\u5382\u65b9\u6cd5\u521b\u5efa\u6d88\u606f\n\n        \u53c2\u6570:\n            format_string: \u683c\u5f0f\u5316\u6a21\u677f\n\n        \u8fd4\u56de:\n            \u6d88\u606f\u683c\u5f0f\u5316\u5668\n        \"\"\"\n        return MessageTemplate(format_string, cls)\n\n    @classmethod\n    @abc.abstractmethod\n    def get_segment_class(cls) -> Type[TMS]:\n        \"\"\"\u83b7\u53d6\u6d88\u606f\u6bb5\u7c7b\u578b\"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        return \"\".join(str(seg) for seg in self)\n\n    @classmethod\n    def __get_validators__(cls):\n        yield cls._validate\n\n    @classmethod\n    def _validate(cls, value):\n        if isinstance(value, cls):\n            return value\n        elif isinstance(value, Message):\n            raise ValueError(f\"Type {type(value)} can not be converted to {cls}\")\n        elif isinstance(value, str):\n            pass\n        elif isinstance(value, dict):\n            value = parse_obj_as(cls.get_segment_class(), value)\n        elif isinstance(value, Iterable):\n            value = [parse_obj_as(cls.get_segment_class(), v) for v in value]\n        else:\n            raise ValueError(\n                f\"Expected str, dict or iterable for Message, got {type(value)}\"\n            )\n        return cls(value)\n\n    @staticmethod\n    @abc.abstractmethod\n    def _construct(msg: str) -> Iterable[TMS]:\n        \"\"\"\u6784\u9020\u6d88\u606f\u6570\u7ec4\"\"\"\n        raise NotImplementedError\n\n    def __add__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        result = self.copy()\n        result += other\n        return result\n\n    def __radd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        result = self.__class__(other)\n        return result + self\n\n    def __iadd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        if isinstance(other, str):\n            self.extend(self._construct(other))\n        elif isinstance(other, MessageSegment):\n            self.append(other)\n        elif isinstance(other, Iterable):\n            self.extend(other)\n        else:\n            raise ValueError(f\"Unsupported type: {type(other)}\")  # pragma: no cover\n        return self\n\n    @overload\n    def __getitem__(self: TM, __args: str) -> TM:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u6d88\u606f\u6bb5\u7c7b\u578b\n\n        \u8fd4\u56de:\n            \u6240\u6709\u7c7b\u578b\u4e3a `__args` \u7684\u6d88\u606f\u6bb5\n        \"\"\"\n\n    @overload\n    def __getitem__(self, __args: Tuple[str, int]) -> TMS:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u6d88\u606f\u6bb5\u7c7b\u578b\u548c\u7d22\u5f15\n\n        \u8fd4\u56de:\n            \u7c7b\u578b\u4e3a `__args[0]` \u7684\u6d88\u606f\u6bb5\u7b2c `__args[1]` \u4e2a\n        \"\"\"\n\n    @overload\n    def __getitem__(self: TM, __args: Tuple[str, slice]) -> TM:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u6d88\u606f\u6bb5\u7c7b\u578b\u548c\u5207\u7247\n\n        \u8fd4\u56de:\n            \u7c7b\u578b\u4e3a `__args[0]` \u7684\u6d88\u606f\u6bb5\u5207\u7247 `__args[1]`\n        \"\"\"\n\n    @overload\n    def __getitem__(self, __args: int) -> TMS:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u7d22\u5f15\n\n        \u8fd4\u56de:\n            \u7b2c `__args` \u4e2a\u6d88\u606f\u6bb5\n        \"\"\"\n\n    @overload\n    def __getitem__(self: TM, __args: slice) -> TM:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u5207\u7247\n\n        \u8fd4\u56de:\n            \u6d88\u606f\u5207\u7247 `__args`\n        \"\"\"\n\n    def __getitem__(\n        self: TM,\n        args: Union[\n            str,\n            Tuple[str, int],\n            Tuple[str, slice],\n            int,\n            slice,\n        ],\n    ) -> Union[TMS, TM]:\n        arg1, arg2 = args if isinstance(args, tuple) else (args, None)\n        if isinstance(arg1, int) and arg2 is None:\n            return super().__getitem__(arg1)\n        elif isinstance(arg1, slice) and arg2 is None:\n            return self.__class__(super().__getitem__(arg1))\n        elif isinstance(arg1, str) and arg2 is None:\n            return self.__class__(seg for seg in self if seg.type == arg1)\n        elif isinstance(arg1, str) and isinstance(arg2, int):\n            return [seg for seg in self if seg.type == arg1][arg2]\n        elif isinstance(arg1, str) and isinstance(arg2, slice):\n            return self.__class__([seg for seg in self if seg.type == arg1][arg2])\n        else:\n            raise ValueError(\"Incorrect arguments to slice\")  # pragma: no cover\n\n    def index(self, value: Union[TMS, str], *args) -> int:\n        if isinstance(value, str):\n            first_segment = next((seg for seg in self if seg.type == value), None)\n            if first_segment is None:\n                raise ValueError(f\"Segment with type {value} is not in message\")\n            return super().index(first_segment, *args)\n        return super().index(value, *args)\n\n    def get(self: TM, type_: str, count: Optional[int] = None) -> TM:\n        if count is None:\n            return self[type_]\n\n        iterator, filtered = (\n            seg for seg in self if seg.type == type_\n        ), self.__class__()\n        for _ in range(count):\n            seg = next(iterator, None)\n            if seg is None:\n                break\n            filtered.append(seg)\n        return filtered\n\n    def count(self, value: Union[TMS, str]) -> int:\n        return len(self[value]) if isinstance(value, str) else super().count(value)\n\n    def append(self: TM, obj: Union[str, TMS]) -> TM:\n        \"\"\"\u6dfb\u52a0\u4e00\u4e2a\u6d88\u606f\u6bb5\u5230\u6d88\u606f\u6570\u7ec4\u672b\u5c3e\u3002\n\n        \u53c2\u6570:\n            obj: \u8981\u6dfb\u52a0\u7684\u6d88\u606f\u6bb5\n        \"\"\"\n        if isinstance(obj, MessageSegment):\n            super().append(obj)\n        elif isinstance(obj, str):\n            self.extend(self._construct(obj))\n        else:\n            raise ValueError(f\"Unexpected type: {type(obj)} {obj}\")  # pragma: no cover\n        return self\n\n    def extend(self: TM, obj: Union[TM, Iterable[TMS]]) -> TM:\n        \"\"\"\u62fc\u63a5\u4e00\u4e2a\u6d88\u606f\u6570\u7ec4\u6216\u591a\u4e2a\u6d88\u606f\u6bb5\u5230\u6d88\u606f\u6570\u7ec4\u672b\u5c3e\u3002\n\n        \u53c2\u6570:\n            obj: \u8981\u6dfb\u52a0\u7684\u6d88\u606f\u6570\u7ec4\n        \"\"\"\n        for segment in obj:\n            self.append(segment)\n        return self\n\n    def copy(self: TM) -> TM:\n        return deepcopy(self)\n\n    def extract_plain_text(self) -> str:\n        \"\"\"\u63d0\u53d6\u6d88\u606f\u5185\u7eaf\u6587\u672c\u6d88\u606f\"\"\"\n\n        return \"\".join(str(seg) for seg in self if seg.is_text())\n\n\n__autodoc__ = {\n    \"MessageSegment.__str__\": True,\n    \"MessageSegment.__add__\": True,\n    \"Message.__getitem__\": True,\n    \"Message._construct\": True,\n}\n", "path": "nonebot/internal/adapter/message.py"}], "after_files": [{"content": "import abc\nfrom copy import deepcopy\nfrom dataclasses import field, asdict, dataclass\nfrom typing import (\n    Any,\n    Dict,\n    List,\n    Type,\n    Tuple,\n    Union,\n    Generic,\n    TypeVar,\n    Iterable,\n    Optional,\n    overload,\n)\n\nfrom pydantic import parse_obj_as\n\nfrom .template import MessageTemplate\n\nT = TypeVar(\"T\")\nTMS = TypeVar(\"TMS\", bound=\"MessageSegment\")\nTM = TypeVar(\"TM\", bound=\"Message\")\n\n\n@dataclass\nclass MessageSegment(abc.ABC, Generic[TM]):\n    \"\"\"\u6d88\u606f\u6bb5\u57fa\u7c7b\"\"\"\n\n    type: str\n    \"\"\"\u6d88\u606f\u6bb5\u7c7b\u578b\"\"\"\n    data: Dict[str, Any] = field(default_factory=dict)\n    \"\"\"\u6d88\u606f\u6bb5\u6570\u636e\"\"\"\n\n    @classmethod\n    @abc.abstractmethod\n    def get_message_class(cls) -> Type[TM]:\n        \"\"\"\u83b7\u53d6\u6d88\u606f\u6570\u7ec4\u7c7b\u578b\"\"\"\n        raise NotImplementedError\n\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        \"\"\"\u8be5\u6d88\u606f\u6bb5\u6240\u4ee3\u8868\u7684 str\uff0c\u5728\u547d\u4ee4\u5339\u914d\u90e8\u5206\u4f7f\u7528\"\"\"\n        raise NotImplementedError\n\n    def __len__(self) -> int:\n        return len(str(self))\n\n    def __ne__(self: T, other: T) -> bool:\n        return not self == other\n\n    def __add__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        return self.get_message_class()(self) + other\n\n    def __radd__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        return self.get_message_class()(other) + self\n\n    @classmethod\n    def __get_validators__(cls):\n        yield cls._validate\n\n    @classmethod\n    def _validate(cls, value):\n        if isinstance(value, cls):\n            return value\n        if not isinstance(value, dict):\n            raise ValueError(f\"Expected dict for MessageSegment, got {type(value)}\")\n        if \"type\" not in value:\n            raise ValueError(\n                f\"Expected dict with 'type' for MessageSegment, got {value}\"\n            )\n        return cls(type=value[\"type\"], data=value.get(\"data\", {}))\n\n    def get(self, key: str, default: Any = None):\n        return asdict(self).get(key, default)\n\n    def keys(self):\n        return asdict(self).keys()\n\n    def values(self):\n        return asdict(self).values()\n\n    def items(self):\n        return asdict(self).items()\n\n    def copy(self: T) -> T:\n        return deepcopy(self)\n\n    @abc.abstractmethod\n    def is_text(self) -> bool:\n        \"\"\"\u5f53\u524d\u6d88\u606f\u6bb5\u662f\u5426\u4e3a\u7eaf\u6587\u672c\"\"\"\n        raise NotImplementedError\n\n\nclass Message(List[TMS], abc.ABC):\n    \"\"\"\u6d88\u606f\u6570\u7ec4\n\n    \u53c2\u6570:\n        message: \u6d88\u606f\u5185\u5bb9\n    \"\"\"\n\n    def __init__(\n        self,\n        message: Union[str, None, Iterable[TMS], TMS] = None,\n    ):\n        super().__init__()\n        if message is None:\n            return\n        elif isinstance(message, str):\n            self.extend(self._construct(message))\n        elif isinstance(message, MessageSegment):\n            self.append(message)\n        elif isinstance(message, Iterable):\n            self.extend(message)\n        else:\n            self.extend(self._construct(message))  # pragma: no cover\n\n    @classmethod\n    def template(cls: Type[TM], format_string: Union[str, TM]) -> MessageTemplate[TM]:\n        \"\"\"\u521b\u5efa\u6d88\u606f\u6a21\u677f\u3002\n\n        \u7528\u6cd5\u548c `str.format` \u5927\u81f4\u76f8\u540c, \u4f46\u662f\u53ef\u4ee5\u8f93\u51fa\u6d88\u606f\u5bf9\u8c61, \u5e76\u4e14\u652f\u6301\u4ee5 `Message` \u5bf9\u8c61\u4f5c\u4e3a\u6d88\u606f\u6a21\u677f\n\n        \u5e76\u4e14\u63d0\u4f9b\u4e86\u62d3\u5c55\u7684\u683c\u5f0f\u5316\u63a7\u5236\u7b26, \u53ef\u4ee5\u7528\u9002\u7528\u4e8e\u8be5\u6d88\u606f\u7c7b\u578b\u7684 `MessageSegment` \u7684\u5de5\u5382\u65b9\u6cd5\u521b\u5efa\u6d88\u606f\n\n        \u53c2\u6570:\n            format_string: \u683c\u5f0f\u5316\u6a21\u677f\n\n        \u8fd4\u56de:\n            \u6d88\u606f\u683c\u5f0f\u5316\u5668\n        \"\"\"\n        return MessageTemplate(format_string, cls)\n\n    @classmethod\n    @abc.abstractmethod\n    def get_segment_class(cls) -> Type[TMS]:\n        \"\"\"\u83b7\u53d6\u6d88\u606f\u6bb5\u7c7b\u578b\"\"\"\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        return \"\".join(str(seg) for seg in self)\n\n    @classmethod\n    def __get_validators__(cls):\n        yield cls._validate\n\n    @classmethod\n    def _validate(cls, value):\n        if isinstance(value, cls):\n            return value\n        elif isinstance(value, Message):\n            raise ValueError(f\"Type {type(value)} can not be converted to {cls}\")\n        elif isinstance(value, str):\n            pass\n        elif isinstance(value, dict):\n            value = parse_obj_as(cls.get_segment_class(), value)\n        elif isinstance(value, Iterable):\n            value = [parse_obj_as(cls.get_segment_class(), v) for v in value]\n        else:\n            raise ValueError(\n                f\"Expected str, dict or iterable for Message, got {type(value)}\"\n            )\n        return cls(value)\n\n    @staticmethod\n    @abc.abstractmethod\n    def _construct(msg: str) -> Iterable[TMS]:\n        \"\"\"\u6784\u9020\u6d88\u606f\u6570\u7ec4\"\"\"\n        raise NotImplementedError\n\n    def __add__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        result = self.copy()\n        result += other\n        return result\n\n    def __radd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        result = self.__class__(other)\n        return result + self\n\n    def __iadd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:\n        if isinstance(other, str):\n            self.extend(self._construct(other))\n        elif isinstance(other, MessageSegment):\n            self.append(other)\n        elif isinstance(other, Iterable):\n            self.extend(other)\n        else:\n            raise TypeError(f\"Unsupported type {type(other)!r}\")\n        return self\n\n    @overload\n    def __getitem__(self: TM, __args: str) -> TM:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u6d88\u606f\u6bb5\u7c7b\u578b\n\n        \u8fd4\u56de:\n            \u6240\u6709\u7c7b\u578b\u4e3a `__args` \u7684\u6d88\u606f\u6bb5\n        \"\"\"\n\n    @overload\n    def __getitem__(self, __args: Tuple[str, int]) -> TMS:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u6d88\u606f\u6bb5\u7c7b\u578b\u548c\u7d22\u5f15\n\n        \u8fd4\u56de:\n            \u7c7b\u578b\u4e3a `__args[0]` \u7684\u6d88\u606f\u6bb5\u7b2c `__args[1]` \u4e2a\n        \"\"\"\n\n    @overload\n    def __getitem__(self: TM, __args: Tuple[str, slice]) -> TM:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u6d88\u606f\u6bb5\u7c7b\u578b\u548c\u5207\u7247\n\n        \u8fd4\u56de:\n            \u7c7b\u578b\u4e3a `__args[0]` \u7684\u6d88\u606f\u6bb5\u5207\u7247 `__args[1]`\n        \"\"\"\n\n    @overload\n    def __getitem__(self, __args: int) -> TMS:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u7d22\u5f15\n\n        \u8fd4\u56de:\n            \u7b2c `__args` \u4e2a\u6d88\u606f\u6bb5\n        \"\"\"\n\n    @overload\n    def __getitem__(self: TM, __args: slice) -> TM:\n        \"\"\"\n        \u53c2\u6570:\n            __args: \u5207\u7247\n\n        \u8fd4\u56de:\n            \u6d88\u606f\u5207\u7247 `__args`\n        \"\"\"\n\n    def __getitem__(\n        self: TM,\n        args: Union[\n            str,\n            Tuple[str, int],\n            Tuple[str, slice],\n            int,\n            slice,\n        ],\n    ) -> Union[TMS, TM]:\n        arg1, arg2 = args if isinstance(args, tuple) else (args, None)\n        if isinstance(arg1, int) and arg2 is None:\n            return super().__getitem__(arg1)\n        elif isinstance(arg1, slice) and arg2 is None:\n            return self.__class__(super().__getitem__(arg1))\n        elif isinstance(arg1, str) and arg2 is None:\n            return self.__class__(seg for seg in self if seg.type == arg1)\n        elif isinstance(arg1, str) and isinstance(arg2, int):\n            return [seg for seg in self if seg.type == arg1][arg2]\n        elif isinstance(arg1, str) and isinstance(arg2, slice):\n            return self.__class__([seg for seg in self if seg.type == arg1][arg2])\n        else:\n            raise ValueError(\"Incorrect arguments to slice\")  # pragma: no cover\n\n    def index(self, value: Union[TMS, str], *args) -> int:\n        if isinstance(value, str):\n            first_segment = next((seg for seg in self if seg.type == value), None)\n            if first_segment is None:\n                raise ValueError(f\"Segment with type {value} is not in message\")\n            return super().index(first_segment, *args)\n        return super().index(value, *args)\n\n    def get(self: TM, type_: str, count: Optional[int] = None) -> TM:\n        if count is None:\n            return self[type_]\n\n        iterator, filtered = (\n            seg for seg in self if seg.type == type_\n        ), self.__class__()\n        for _ in range(count):\n            seg = next(iterator, None)\n            if seg is None:\n                break\n            filtered.append(seg)\n        return filtered\n\n    def count(self, value: Union[TMS, str]) -> int:\n        return len(self[value]) if isinstance(value, str) else super().count(value)\n\n    def append(self: TM, obj: Union[str, TMS]) -> TM:\n        \"\"\"\u6dfb\u52a0\u4e00\u4e2a\u6d88\u606f\u6bb5\u5230\u6d88\u606f\u6570\u7ec4\u672b\u5c3e\u3002\n\n        \u53c2\u6570:\n            obj: \u8981\u6dfb\u52a0\u7684\u6d88\u606f\u6bb5\n        \"\"\"\n        if isinstance(obj, MessageSegment):\n            super().append(obj)\n        elif isinstance(obj, str):\n            self.extend(self._construct(obj))\n        else:\n            raise ValueError(f\"Unexpected type: {type(obj)} {obj}\")  # pragma: no cover\n        return self\n\n    def extend(self: TM, obj: Union[TM, Iterable[TMS]]) -> TM:\n        \"\"\"\u62fc\u63a5\u4e00\u4e2a\u6d88\u606f\u6570\u7ec4\u6216\u591a\u4e2a\u6d88\u606f\u6bb5\u5230\u6d88\u606f\u6570\u7ec4\u672b\u5c3e\u3002\n\n        \u53c2\u6570:\n            obj: \u8981\u6dfb\u52a0\u7684\u6d88\u606f\u6570\u7ec4\n        \"\"\"\n        for segment in obj:\n            self.append(segment)\n        return self\n\n    def copy(self: TM) -> TM:\n        return deepcopy(self)\n\n    def extract_plain_text(self) -> str:\n        \"\"\"\u63d0\u53d6\u6d88\u606f\u5185\u7eaf\u6587\u672c\u6d88\u606f\"\"\"\n\n        return \"\".join(str(seg) for seg in self if seg.is_text())\n\n\n__autodoc__ = {\n    \"MessageSegment.__str__\": True,\n    \"MessageSegment.__add__\": True,\n    \"Message.__getitem__\": True,\n    \"Message._construct\": True,\n}\n", "path": "nonebot/internal/adapter/message.py"}]}