Skip to content

Commit

Permalink
♻️ Message (part I)
Browse files Browse the repository at this point in the history
  • Loading branch information
j1g5awi committed Feb 17, 2024
1 parent 61ef4f4 commit 76d371d
Show file tree
Hide file tree
Showing 5 changed files with 216 additions and 97 deletions.
2 changes: 0 additions & 2 deletions example/mention.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""
@某个用户的示例
本示例所涉及的 Entity 在将在下个版本重构
"""

from typing import Union
Expand Down
39 changes: 39 additions & 0 deletions example/sendxxx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import asyncio

from nonebot import on_command
from nonebot.adapters.telegram import Bot
from nonebot.adapters.telegram.event import MessageEvent
from nonebot.adapters.telegram.message import Message, MessageSegment


@on_command("location").handle()
async def _(bot: Bot, event: MessageEvent):
await bot.send(event, MessageSegment.location(31.2001033, 121.4326496))


@on_command("venue").handle()
async def _(bot: Bot, event: MessageEvent):
await bot.send(
event,
MessageSegment.venue(31.2001033, 121.4326496, "NoneBot 研讨会", "上海交通大学"),
)


@on_command("poll").handle()
async def _(bot: Bot, event: MessageEvent):
await bot.send(
event,
MessageSegment.poll("NoneBot 3.0?", ["Breaking!", "No!", "DDL!DDL!DDL!"]),
)


@on_command("dice").handle()
async def _(bot: Bot, event: MessageEvent):
await bot.send(event, MessageSegment.dice())


@on_command("chat_action").handle()
async def _(bot: Bot, event: MessageEvent):
await bot.send(event, MessageSegment.chat_action("typing"))
await asyncio.sleep(1)
await bot.send(event, "Typing complete!")
1 change: 1 addition & 0 deletions nonebot/adapters/telegram/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ async def process_input_file(file: Union[InputFile, str]) -> Optional[str]:
"sendAnimation",
"sendVoice",
"sendVideoNote",
"sendSticker",
):
type = api[4:].lower()
for key in (type, "thumbnail"):
Expand Down
59 changes: 24 additions & 35 deletions nonebot/adapters/telegram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from uuid import uuid4
from functools import partial
from typing_extensions import override
from typing import Any, List, Union, Optional, Sequence, cast
from typing import Any, Union, Optional, cast

from pydantic import TypeAdapter
from nonebot.message import handle_event
Expand All @@ -13,7 +13,7 @@
from .api import API
from .config import BotConfig
from .exception import ApiNotAvailable
from .model import InputMedia, MessageEntity, ReplyParameters
from .model import InputMedia, ReplyParameters
from .message import File, Entity, Message, UnCombinFile, MessageSegment
from .event import (
Event,
Expand Down Expand Up @@ -109,29 +109,6 @@ def __getattribute__(self, __name: str) -> Any:
return partial(self.call_api, __name)
return object.__getattribute__(self, __name)

def __build_entities_form_msg(
self, message: Sequence[MessageSegment]
) -> Optional[List[MessageEntity]]:
return (
(
[
MessageEntity(
type=entity.type, # type: ignore
offset=sum(map(len, message[:i])),
length=len(entity.data["text"]),
url=entity.data.get("url"),
user=entity.data.get("user"),
language=entity.data.get("language"),
)
for i, entity in enumerate(message)
if entity.is_text() and entity.type != "text"
]
or None
)
if message
else None
)

# TODO 重构
async def send_to(
self,
Expand All @@ -141,7 +118,7 @@ async def send_to(
disable_notification: Optional[bool] = None,
protect_content: Optional[bool] = None,
reply_to_message_id: Optional[int] = None, # Deprecated
allow_sending_without_reply: Optional[bool] = None,
allow_sending_without_reply: Optional[bool] = None, # Deprecated
media_group_caption_index: int = 0, # 非 Telegram 原生参数
**kwargs,
):
Expand Down Expand Up @@ -176,7 +153,7 @@ async def send_to(
chat_id=chat_id,
message_thread_id=message_thread_id,
text=str(message),
entities=self.__build_entities_form_msg([message]),
entities=Entity.build_telegram_entities([message]),
**kwargs,
)

Expand Down Expand Up @@ -206,17 +183,17 @@ async def send_to(
reply_parameters = ReplyParameters(**message["reply", 0].data)
message = message.exclude("reply")

entities = [x for x in message if isinstance(x, Entity)]
files = [
entities = Message(x for x in message if isinstance(x, Entity))
files = Message(
x
for x in message
if isinstance(x, File) and not isinstance(x, UnCombinFile)
]
others = [
)
others = Message(
x
for x in message
if not (isinstance(x, (Entity, File))) or isinstance(x, UnCombinFile)
]
)

if others:
# 如果只能单独发送的消息段和其他消息段在一起,那么抛出错误
Expand All @@ -238,13 +215,16 @@ async def send_to(
chat_id=chat_id,
message_thread_id=message_thread_id,
text=str(message),
entities=self.__build_entities_form_msg(message),
entities=Entity.build_telegram_entities(entities),

Check failure on line 218 in nonebot/adapters/telegram/bot.py

View workflow job for this annotation

GitHub Actions / Pyright Lint

Argument of type "Message" cannot be assigned to parameter "entities" of type "List[Entity]" in function "build_telegram_entities"   "Message" is incompatible with "List[Entity]"     Type parameter "_T@list" is invariant, but "MessageSegment" is not the same as "Entity"     Consider switching from "list" to "Sequence" which is covariant (reportArgumentType)
reply_parameters=reply_parameters,
**kwargs,
)

# 发送带文件的消息
if len(files) > 1:
# animation 和 voice 不能组合发送
if any(file.type in ("voice", "animation") for file in files):
raise ApiNotAvailable
# 多个文件
medias = [
TypeAdapter(InputMedia).validate_python(
Expand All @@ -263,7 +243,7 @@ async def send_to(
media_will_edit = medias[0]

media_will_edit.caption = str(entities) if entities else None
media_will_edit.caption_entities = self.__build_entities_form_msg(entities)
media_will_edit.caption_entities = Entity.build_telegram_entities(entities)

Check failure on line 246 in nonebot/adapters/telegram/bot.py

View workflow job for this annotation

GitHub Actions / Pyright Lint

Argument of type "Message" cannot be assigned to parameter "entities" of type "List[Entity]" in function "build_telegram_entities"   "Message" is incompatible with "List[Entity]"     Type parameter "_T@list" is invariant, but "MessageSegment" is not the same as "Entity"     Consider switching from "list" to "Sequence" which is covariant (reportArgumentType)

return await self.send_media_group(
chat_id=chat_id,
Expand All @@ -282,7 +262,7 @@ async def send_to(
**{
file.type: file.data.get("file"),
"caption": str(entities) if entities else None,
"caption_entities": self.__build_entities_form_msg(entities),
"caption_entities": Entity.build_telegram_entities(entities),

Check failure on line 265 in nonebot/adapters/telegram/bot.py

View workflow job for this annotation

GitHub Actions / Pyright Lint

Argument of type "Message" cannot be assigned to parameter "entities" of type "List[Entity]" in function "build_telegram_entities"   "Message" is incompatible with "List[Entity]"     Type parameter "_T@list" is invariant, but "MessageSegment" is not the same as "Entity"     Consider switching from "list" to "Sequence" which is covariant (reportArgumentType)
},
reply_parameters=reply_parameters,
**kwargs,
Expand All @@ -293,11 +273,20 @@ async def send(
self,
event: Event,
message: Union[str, Message, MessageSegment],
disable_notification: Optional[bool] = None,
protect_content: Optional[bool] = None,
**kwargs,
) -> Any:
if not isinstance(event, EventWithChat):
raise ApiNotAvailable

kwargs.update(
{
"disable_notification": disable_notification,
"protect_content": protect_content,
},
)

message_thread_id = cast(
Optional[int],
getattr(event, "message_thread_id", None),
Expand Down
Loading

0 comments on commit 76d371d

Please sign in to comment.