nonebot2/nonebot/adapters/ding/event.py

85 lines
2.3 KiB
Python
Raw Normal View History

2020-12-06 02:30:19 +08:00
from typing import Union, Optional
from typing_extensions import Literal
from pydantic import BaseModel, validator, parse_obj_as
from pydantic.fields import ModelField
2020-12-06 02:30:19 +08:00
2020-12-07 00:06:09 +08:00
from nonebot.adapters import Event as BaseEvent
from nonebot.utils import escape_tag
2020-12-03 00:59:32 +08:00
from .message import Message
from .model import MessageModel, PrivateMessageModel, GroupMessageModel, ConversationType, TextMessage
2020-12-03 00:59:32 +08:00
class Event(BaseEvent):
"""
钉钉 协议 Event 适配继承属性参考 `BaseEvent <./#class-baseevent>`_ 。
"""
message: Message = None
2020-12-03 00:59:32 +08:00
def __init__(self, **data):
super().__init__(**data)
2020-12-03 12:08:04 +08:00
# 其实目前钉钉机器人只能接收到 text 类型的消息
message: Union[TextMessage] = getattr(self, self.msgtype, None)
self.message = parse_obj_as(Message, message)
2020-12-03 00:59:32 +08:00
def get_type(self) -> Literal["message"]:
2020-12-03 00:59:32 +08:00
"""
- 类型: ``str``
- 说明: 事件类型
"""
return "message"
def get_event_name(self) -> str:
detail_type = self.conversationType.name
return self.get_type() + "." + detail_type
2020-12-03 00:59:32 +08:00
def get_event_description(self) -> str:
return (f'Message[{self.msgtype}] {self.msgId} from {self.senderId} "' +
"".join(
map(
lambda x: escape_tag(str(x))
if x.is_text() else f"<le>{escape_tag(str(x))}</le>",
self.message,
)) + '"')
2020-12-03 00:59:32 +08:00
def get_user_id(self) -> str:
return self.senderId
2020-12-03 00:59:32 +08:00
def get_session_id(self) -> str:
2020-12-03 00:59:32 +08:00
"""
- 类型: ``str``
- 说明: 消息 ID
2020-12-03 00:59:32 +08:00
"""
return self.msgId
2020-12-03 00:59:32 +08:00
def get_message(self) -> "Message":
2020-12-03 00:59:32 +08:00
"""
- 类型: ``Message``
- 说明: 消息内容
2020-12-03 00:59:32 +08:00
"""
return self.message
2020-12-03 00:59:32 +08:00
def get_plaintext(self) -> str:
2020-12-03 00:59:32 +08:00
"""
- 类型: ``str``
- 说明: 纯文本消息内容
2020-12-03 00:59:32 +08:00
"""
return self.message.extract_plain_text().strip() if self.message else ""
2020-12-03 00:59:32 +08:00
class MessageEvent(MessageModel, Event):
pass
2020-12-03 00:59:32 +08:00
class PrivateMessageEvent(PrivateMessageModel, Event):
2020-12-03 00:59:32 +08:00
def is_tome(self) -> bool:
return True
2020-12-03 00:59:32 +08:00
class GroupMessageEvent(GroupMessageModel, Event):
2020-12-03 00:59:32 +08:00
def is_tome(self) -> bool:
return self.isInAtList