From 9564cb2858833fb8de442123226fe7a46f743fe6 Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Thu, 16 Jun 2022 21:44:26 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84ws=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E4=B8=ADMessage=E6=95=B0=E6=8D=AE=E7=9A=84=E6=9E=84?= =?UTF-8?q?=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/message.py | 25 ++++++++++++++++++++++--- botpy/types/gateway.py | 6 ++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/botpy/message.py b/botpy/message.py index e4126c0..543f236 100644 --- a/botpy/message.py +++ b/botpy/message.py @@ -11,6 +11,7 @@ class Message: "id", "guild_id", "member", + "message_reference", "mentions", "seq", "seq_in_channel", @@ -22,18 +23,36 @@ def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: gateway.MessagePay # TODO 创建一些实体类的数据缓存 @veehou self._api = api - self.author = data.get("author") + self.author = self._User(data.get("author")) self.channel_id = data.get("channel_id") self.id = data.get("id") self.content = data.get("content") self.guild_id = data.get("guild_id") - self.member = data.get("member") - self.mentions = data.get("mentions") + self.member = self._Member(data.get("member")) + self.message_reference = self._MessageRef(data.get("message_reference", {})) + self.mentions = [self._User(items) for items in data.get("mentions", {})] self.seq = data.get("seq") # 全局消息序号 self.seq_in_channel = data.get("seq_in_channel") # 子频道消息序号 self.timestamp = data.get("timestamp") self.event_id = ctx.get("id") + class _User: + def __init__(self, data): + self.id = data.get("id") + self.username = data.get("username") + self.bot = data.get("bot") + self.avatar = data.get("avatar") + + class _Member: + def __init__(self, data): + self.nick = data.get("nick", None) + self.roles = data.get("roles", None) + self.joined_at = data.get("joined_at", None) + + class _MessageRef: + def __init__(self, data): + self.message_id = data.get("message_id", None) + async def reply(self, **kwargs): return await self._api.post_message(channel_id=self.channel_id, msg_id=self.id, **kwargs) diff --git a/botpy/types/gateway.py b/botpy/types/gateway.py index 98b059d..d6d8355 100644 --- a/botpy/types/gateway.py +++ b/botpy/types/gateway.py @@ -12,6 +12,11 @@ class UserPayload(TypedDict): username: str bot: bool status: int + avatar: str + + +class MessageRefPayload(TypedDict): + message_id: str class ReadyEvent(TypedDict): @@ -32,6 +37,7 @@ class MessagePayload(TypedDict): guild_id: str id: str member: Member + message_reference: MessageRefPayload mentions: List[UserPayload] seq: int seq_in_channel: str From 109c74e8845ee0c91b0237a7bf427e9f4587cf47 Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Thu, 16 Jun 2022 21:54:04 +0800 Subject: [PATCH 02/10] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84ws=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E4=B8=ADUser-Member=E6=95=B0=E6=8D=AE=E7=9A=84?= =?UTF-8?q?=E6=9E=84=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/user.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/botpy/user.py b/botpy/user.py index 4635cac..bf53311 100644 --- a/botpy/user.py +++ b/botpy/user.py @@ -15,8 +15,17 @@ class Member: def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: user.GuildMemberPayload): self._api = api - self.user = data.get("user") + self.user = self._User(data.get("user")) self.nick = data.get("nick") self.roles = data.get("roles") self.joined_at = data.get("joined_at") self.event_id = ctx.get("id") + + class _User: + def __init__(self, data): + self.id = data.get("user") + self.username = data.get("username") + self.avatar = data.get("avatar") + self.bot = data.get("bot") + self.union_openid = data.get("union_openid", None) + self.union_user_account = data.get("union_user_account", None) From 26af7adc5fb193707023f3d6ebdc4f6b36936cff Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Thu, 16 Jun 2022 23:13:58 +0800 Subject: [PATCH 03/10] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84ws=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E4=B8=ADReaction=E3=80=81Audio=E3=80=81DirectMessage?= =?UTF-8?q?=20=E4=BB=A5=E5=8F=8A=20Forum=EF=BC=88Thread=E7=B1=BB=EF=BC=89?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E7=9A=84=E6=9E=84=E5=BB=BA=20feat:=20?= =?UTF-8?q?=E5=8E=BB=E9=99=A4EmbedField=E7=9A=84value=E9=A1=B9=EF=BC=88?= =?UTF-8?q?=E5=AE=9E=E9=99=85=E4=BB=85=E6=9C=89name=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/audio.py | 22 +++++++++ botpy/connection.py | 40 +++++++++------ botpy/forum.py | 108 +++++++++++++++++++++++++++++++++++++++++ botpy/message.py | 53 ++++++++++++++++++++ botpy/reaction.py | 34 +++++++++++++ botpy/types/gateway.py | 15 ++++++ botpy/types/message.py | 1 - 7 files changed, 258 insertions(+), 15 deletions(-) create mode 100644 botpy/audio.py create mode 100644 botpy/forum.py create mode 100644 botpy/reaction.py diff --git a/botpy/audio.py b/botpy/audio.py new file mode 100644 index 0000000..e3ece51 --- /dev/null +++ b/botpy/audio.py @@ -0,0 +1,22 @@ +from .api import BotAPI +from .types import gateway, audio + + +class Audio: + __slots__ = ( + "_api", + "_ctx", + "channel_id", + "guild_id", + "audio_url", + "text", + "event_id") + + def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: audio.AudioAction): + self._api = api + + self.channel_id = data.get("channel_id") + self.guild_id = data.get("guild_id") + self.audio_url = data.get("audio_url") + self.text = data.get("text") + self.event_id = ctx.get("id") diff --git a/botpy/connection.py b/botpy/connection.py index 91193d9..ada3a3b 100644 --- a/botpy/connection.py +++ b/botpy/connection.py @@ -5,8 +5,11 @@ from .channel import Channel from .guild import Guild from .interaction import Interaction -from .message import Message, MessageAudit +from .message import Message, DirectMessage, MessageAudit from .user import Member +from .reaction import Reaction +from .audio import Audio +from .forum import Forum from . import logging from .api import BotAPI @@ -135,18 +138,20 @@ def parse_message_delete(self, ctx: gateway.WsContext, data: gateway.MessagePayl # botpy.flags.Intents.guild_message_reactions def parse_message_reaction_add(self, ctx: gateway.WsContext, data: reaction.Reaction): - self._dispatch("message_reaction_add", data) + _reaction = Reaction(self.api, ctx, data) + self._dispatch("message_reaction_add", _reaction) def parse_message_reaction_remove(self, ctx: gateway.WsContext, data: reaction.Reaction): - self._dispatch("message_reaction_remove", data) + _reaction = Reaction(self.api, ctx, data) + self._dispatch("message_reaction_remove", _reaction) # botpy.flags.Intents.direct_message - def parse_direct_message_create(self, ctx: gateway.WsContext, data: gateway.MessagePayload): - _message = Message(self.api, ctx, data) + def parse_direct_message_create(self, ctx: gateway.WsContext, data: gateway.DirectMessagePayload): + _message = DirectMessage(self.api, ctx, data) self._dispatch("direct_message_create", _message) - def parse_direct_message_delete(self, ctx: gateway.WsContext, data: gateway.MessagePayload): - _message = Message(self.api, ctx, data) + def parse_direct_message_delete(self, ctx: gateway.WsContext, data: gateway.DirectMessagePayload): + _message = DirectMessage(self.api, ctx, data) self._dispatch("direct_message_delete", _message) # botpy.flags.Intents.interaction @@ -165,16 +170,20 @@ def parse_message_audit_reject(self, ctx: gateway.WsContext, data: gateway.Messa # botpy.flags.Intents.audio_action def parse_audio_start(self, ctx: gateway.WsContext, data): - self._dispatch("audio_start", data) + _audio = Audio(self.api, ctx, data) + self._dispatch("audio_start", _audio) def parse_audio_finish(self, ctx: gateway.WsContext, data): - self._dispatch("audio_finish", data) + _audio = Audio(self.api, ctx, data) + self._dispatch("audio_finish", _audio) def parse_on_mic(self, ctx: gateway.WsContext, data): - self._dispatch("on_mic", data) + _audio = Audio(self.api, ctx, data) + self._dispatch("on_mic", _audio) def parse_off_mic(self, ctx: gateway.WsContext, data): - self._dispatch("off_mic", data) + _audio = Audio(self.api, ctx, data) + self._dispatch("off_mic", _audio) # botpy.flags.Intents.public_guild_messages def parse_at_message_create(self, ctx: gateway.WsContext, data: gateway.MessagePayload): @@ -188,13 +197,16 @@ def parse_resumed(self, ctx: gateway.WsContext, data: gateway.ReadyEvent): self._dispatch("resumed") def parse_forum_thread_create(self, ctx: gateway.WsContext, data: forum.Thread): - self._dispatch("forum_thread_create", data) + _forum = Forum(self.api, ctx, data) + self._dispatch("forum_thread_create", _forum) def parse_forum_thread_update(self, ctx: gateway.WsContext, data: forum.Thread): - self._dispatch("forum_thread_update", data) + _forum = Forum(self.api, ctx, data) + self._dispatch("forum_thread_update", _forum) def parse_forum_thread_delete(self, ctx: gateway.WsContext, data: forum.Thread): - self._dispatch("forum_thread_delete", data) + _forum = Forum(self.api, ctx, data) + self._dispatch("forum_thread_delete", _forum) def parse_forum_post_create(self, ctx: gateway.WsContext, data: forum.Post): self._dispatch("forum_post_create", data) diff --git a/botpy/forum.py b/botpy/forum.py new file mode 100644 index 0000000..3b0cf50 --- /dev/null +++ b/botpy/forum.py @@ -0,0 +1,108 @@ +from json import loads + +from .api import BotAPI +from .types import gateway, forum + + +class _Text: + def __init__(self, data): + self.text = data.get("text", None) + + +class _Image: + def __init__(self, data): + self.plat_image = self._PlatImage(data.get("plat_image", {})) + + class _PlatImage: + def __init__(self, data): + self.url = data.get("url", None) + self.width = data.get("width", None) + self.height = data.get("height", None) + self.image_id = data.get("image_id", None) + + +class _Video: + def __init__(self, data): + self.plat_video = self._PlatVideo(data.get("plat_video", {})) + + class _PlatVideo: + def __init__(self, data): + self.url = data.get("url", None) + self.width = data.get("width", None) + self.height = data.get("height", None) + self.video_id = data.get("video_id", None) + self.cover = data.get("cover", {}) + + class _Cover: + def __init__(self, data): + self.url = data.get("url", None) + self.width = data.get("width", None) + self.height = data.get("height", None) + + +class _Url: + def __init__(self, data): + self.url = data.get("url", None) + self.desc = data.get("desc", None) + + +class Forum: + __slots__ = ( + "_api", + "_ctx", + "thread_info", + "channel_id", + "guild_id", + "author_id", + "event_id") + + def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: forum.Thread): + self._api = api + + self.author_id = data.get("author_id") + self.channel_id = data.get("channel_id") + self.guild_id = data.get("guild_id") + self.thread_info = self._ThreadInfo(data.get("thread_info")) + self.event_id = ctx.get("id") + + class _ThreadInfo: + def __init__(self, data): + self.title = self._Title(loads(data.get("title"))) + self.content = self._Content(loads(data.get("content"))) + self.thread_id = data.get("thread_id") + self.date_time = data.get("date_time") + + class _Title: + def __init__(self, data): + self.paragraphs = [self._Paragraphs(items) for items in data.get("paragraphs")] + + class _Paragraphs: + def __init__(self, data): + self.elems = [self._Elems(items) for items in data.get("elems")] + self.props = data.get("props") + + class _Elems: + def __init__(self, data): + self.type = data.get("type") + self.text = _Text(data.get("text", {})) + + class _Content: + def __init__(self, data): + self.paragraphs = [self._Paragraphs(items) for items in data.get("paragraphs")] + + class _Paragraphs: + def __init__(self, data): + self.elems = [self._Elems(items) for items in data.get("elems")] + self.props = data.get("props") + + class _Elems: + def __init__(self, data): + self.type = data.get("type") + if self.type == 1: + self.text = _Text(data.get("text", {})) + elif self.type == 2: + self.image = _Image(data.get("image", {})) + elif self.type == 3: + self.video = _Video(data.get("video", {})) + elif self.type == 4: + self.url = _Url(data.get("url", {})) diff --git a/botpy/message.py b/botpy/message.py index 543f236..c813226 100644 --- a/botpy/message.py +++ b/botpy/message.py @@ -57,6 +57,59 @@ async def reply(self, **kwargs): return await self._api.post_message(channel_id=self.channel_id, msg_id=self.id, **kwargs) +class DirectMessage: + __slots__ = ( + "_api", + "author", + "content", + "direct_message", + "channel_id", + "id", + "guild_id", + "member", + "message_reference", + "seq", + "seq_in_channel", + "src_guild_id", + "timestamp", + "event_id" + ) + + def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: gateway.DirectMessagePayload): + self._api = api + + self.author = self._User(data.get("author")) + self.channel_id = data.get("channel_id") + self.id = data.get("id") + self.content = data.get("content") + self.direct_message = data.get("direct_message") + self.guild_id = data.get("guild_id") + self.member = self._Member(data.get("member")) + self.message_reference = self._MessageRef(data.get("message_reference", {})) + self.seq = data.get("seq") # 全局消息序号 + self.seq_in_channel = data.get("seq_in_channel") # 子频道消息序号 + self.src_guild_id = data.get("src_guild_id") + self.timestamp = data.get("timestamp") + self.event_id = ctx.get("id") + + class _User: + def __init__(self, data): + self.id = data.get("id") + self.username = data.get("username") + self.avatar = data.get("avatar") + + class _Member: + def __init__(self, data): + self.joined_at = data.get("joined_at", None) + + class _MessageRef: + def __init__(self, data): + self.message_id = data.get("message_id", None) + + async def reply(self, **kwargs): + return await self._api.post_message(channel_id=self.channel_id, msg_id=self.id, **kwargs) + + class MessageAudit: __slots__ = ( "_api", diff --git a/botpy/reaction.py b/botpy/reaction.py new file mode 100644 index 0000000..7ecfca2 --- /dev/null +++ b/botpy/reaction.py @@ -0,0 +1,34 @@ +from .api import BotAPI +from .types import gateway, reaction + + +class Reaction: + __slots__ = ( + "_api", + "_ctx", + "user_id", + "channel_id", + "guild_id", + "emoji", + "target", + "event_id") + + def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: reaction.Reaction): + self._api = api + + self.user_id = data.get("user_id") + self.channel_id = data.get("channel_id") + self.guild_id = data.get("guild_id") + self.emoji = self._Emoji(data.get("emoji")) + self.target = self._Target(data.get("target")) + self.event_id = ctx.get("id") + + class _Emoji: + def __init__(self, data): + self.id = data.get("id") + self.type = data.get("type") + + class _Target: + def __init__(self, data): + self.id = data.get("id") + self.type = data.get("type") # 0: 消息 1: 帖子 2: 评论 3: 回复 diff --git a/botpy/types/gateway.py b/botpy/types/gateway.py index d6d8355..46b64d5 100644 --- a/botpy/types/gateway.py +++ b/botpy/types/gateway.py @@ -44,6 +44,21 @@ class MessagePayload(TypedDict): timestamp: str +class DirectMessagePayload(TypedDict): + author: UserPayload + channel_id: str + content: str + direct_message: bool + guild_id: str + id: str + member: Member + message_reference: MessageRefPayload + seq: int + seq_in_channel: str + src_guild_id: str + timestamp: str + + class MessageAuditPayload(TypedDict): audit_id: str message_id: str diff --git a/botpy/types/message.py b/botpy/types/message.py index 88c5f9c..cd77591 100644 --- a/botpy/types/message.py +++ b/botpy/types/message.py @@ -16,7 +16,6 @@ class Thumbnail(TypedDict): class EmbedField(TypedDict): name: str - value: str class Embed(TypedDict, total=False): From 6cc4e6dfc595f5158771e5ab7f9fcc04a55e4769 Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Fri, 17 Jun 2022 16:50:59 +0800 Subject: [PATCH 04/10] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84ws=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E4=B8=AD=E7=9B=91=E5=90=AC=E6=96=87=E6=A1=A3=E5=B9=B6?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=A0=BC=E5=BC=8F=20refactor:=20=E4=BC=98?= =?UTF-8?q?=E5=8C=96forum=20thread=E7=9A=84=E4=BA=8B=E4=BB=B6=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/forum.py | 2 +- ...13\344\273\266\347\233\221\345\220\254.md" | 227 ++++++++++-------- 2 files changed, 133 insertions(+), 96 deletions(-) diff --git a/botpy/forum.py b/botpy/forum.py index 3b0cf50..7da172d 100644 --- a/botpy/forum.py +++ b/botpy/forum.py @@ -46,7 +46,7 @@ def __init__(self, data): self.desc = data.get("desc", None) -class Forum: +class Thread: __slots__ = ( "_api", "_ctx", diff --git "a/docs/\344\272\213\344\273\266\347\233\221\345\220\254.md" "b/docs/\344\272\213\344\273\266\347\233\221\345\220\254.md" index 55f99a9..85f657c 100644 --- "a/docs/\344\272\213\344\273\266\347\233\221\345\220\254.md" +++ "b/docs/\344\272\213\344\273\266\347\233\221\345\220\254.md" @@ -3,23 +3,24 @@ **本文档概述[botpy的事件监听](https://github.com/tencent-connect/botpy/blob/feature/botpy_1.0/botpy/flags.py)** ## 目录 -- [准备](#准备) -- [使用方式](#使用方式) -- [监听的事件](#监听的事件) - + [公域消息事件的监听](#公域消息事件的监听) - + [消息事件的监听](#消息事件的监听) - + [私信事件的监听](#私信事件的监听) - + [消息相关互动事件的监听](#消息相关互动事件的监听) - + [频道事件的监听](#频道事件的监听) - + [频道成员事件的监听](#频道成员事件的监听) - + [互动事件的监听](#互动事件的监听) - + [消息审核事件的监听](#消息审核事件的监听) - + [论坛事件的监听](#论坛事件的监听) - + [音频事件的监听](#音频事件的监听) -- [订阅事件的方法](#订阅事件的方法) +- [准备](#准备) +- [使用方式](#使用方式) +- [监听的事件](#监听的事件) + - [公域消息事件的监听](#公域消息事件的监听) + - [消息事件的监听](#消息事件的监听) + - [私信事件的监听](#私信事件的监听) + - [消息相关互动事件的监听](#消息相关互动事件的监听) + - [频道事件的监听](#频道事件的监听) + - [频道成员事件的监听](#频道成员事件的监听) + - [互动事件的监听](#互动事件的监听) + - [消息审核事件的监听](#消息审核事件的监听) + - [论坛事件的监听](#论坛事件的监听) + - [音频事件的监听](#音频事件的监听) +- [订阅事件的方法](#订阅事件的方法) ## 准备 + ```python import botpy ``` @@ -45,12 +46,13 @@ intents = botpy.Intents(public_guild_messages=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_at_message_create(self, message: Message) | 当收到@机器人的消息时 | -| on_public_message_delete(self, message: Message) | 当频道的消息被删除时 | +| 对应函数 | 说明 | +| ------------------------------------------------ | ----------- | +| on_at_message_create(self, message: Message) | 当收到@机器人的消息时 | +| on_public_message_delete(self, message: Message) | 当频道的消息被删除时 | + +- **注:需要引入`Message`** -- **注:需要引入`Message`** ```python from botpy.message import Message ``` @@ -69,9 +71,7 @@ class MyClient(botpy.Client): ### 消息事件的监听 - -- **仅 私域 机器人能够设置此 intents** - +- **仅 私域 机器人能够设置此 intents** 首先需要订阅事件`guild_messages` @@ -80,12 +80,13 @@ intents = botpy.Intents(guild_messages=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | +| 对应函数 | 说明 | +| ----------------------------------------- | -------------------------------------------------------------- | | on_message_create(self, message: Message) | 发送消息事件,代表频道内的全部消息,而不只是 at 机器人的消息。
内容与 AT_MESSAGE_CREATE 相同 | -| on_message_delete(self, message: Message) | 删除(撤回)消息事件 | +| on_message_delete(self, message: Message) | 删除(撤回)消息事件 | + +- **注:需要引入`Message`** -- **注:需要引入`Message`** ```python from botpy.message import Message ``` @@ -111,23 +112,24 @@ intents = botpy.Intents(direct_message=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_direct_message_create(self, message: Message) | 当收到用户发给机器人的私信消息时 | -| on_direct_message_delete(self, message: Message) | 删除(撤回)消息事件 | +| 对应函数 | 说明 | +| ------------------------------------------------------ | ---------------- | +| on_direct_message_create(self, message: DirectMessage) | 当收到用户发给机器人的私信消息时 | +| on_direct_message_delete(self, message: DirectMessage) | 删除(撤回)消息事件 | + +- **注:需要引入`DirectMessage`** -- **注:需要引入`Message`** ```python -from botpy.message import Message +from botpy.message import DirectMessage ``` ```python class MyClient(botpy.Client): - async def on_direct_message_create(self, message: Message): + async def on_direct_message_create(self, message: DirectMessage): """ 此处为处理该事件的代码 """ - async def on_direct_message_delete(self, message: Message): + async def on_direct_message_delete(self, message: DirectMessage): """ 此处为处理该事件的代码 """ @@ -142,14 +144,15 @@ intents = botpy.Intents(guild_message_reactions=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_message_reaction_add(self, reaction: Reaction) | 为消息添加表情表态 | +| 对应函数 | 说明 | +| ---------------------------------------------------- | --------- | +| on_message_reaction_add(self, reaction: Reaction) | 为消息添加表情表态 | | on_message_reaction_remove(self, reaction: Reaction) | 为消息删除表情表态 | -- **注:需要引入`Reaction`** +- **注:需要引入`Reaction`** + ```python -from botpy.types.reaction import Reaction +from botpy.reaction import Reaction ``` ```python @@ -173,17 +176,17 @@ intents = botpy.Intents(guilds=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_guild_create(self, guild: Guild) | 当机器人加入新guild时 | -| on_guild_update(self, guild: Guild) | 当guild资料发生变更时 | -| on_guild_delete(self, guild: Guild) | 当机器人退出guild时 | -| on_channel_create(self, channel: Channel) | 当channel被创建时 | -| on_channel_update(self, channel: Channel) | 当channel被更新时 | -| on_channel_delete(self, channel: Channel) | 当channel被删除时 | +| 对应函数 | 说明 | +| ----------------------------------------- | ------------- | +| on_guild_create(self, guild: Guild) | 当机器人加入新guild时 | +| on_guild_update(self, guild: Guild) | 当guild资料发生变更时 | +| on_guild_delete(self, guild: Guild) | 当机器人退出guild时 | +| on_channel_create(self, channel: Channel) | 当channel被创建时 | +| on_channel_update(self, channel: Channel) | 当channel被更新时 | +| on_channel_delete(self, channel: Channel) | 当channel被删除时 | +- **注:需要引入`Guild`和`Channel`** -- **注:需要引入`Guild`和`Channel`** ```python from botpy.guild import Guild from botpy.channel import Channel @@ -226,28 +229,29 @@ intents = botpy.Intents(guild_members=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_guild_member_add(self, member: GuildMember) | 当成员加入时 | -| on_guild_member_update(self, member: GuildMember) | 当成员资料变更时 | -| on_guild_member_remove(self, member: GuildMember) | 当成员被移除时 | +| 对应函数 | 说明 | +| -------------------------------------------- | -------- | +| on_guild_member_add(self, member: Member) | 当成员加入时 | +| on_guild_member_update(self, member: Member) | 当成员资料变更时 | +| on_guild_member_remove(self, member: Member) | 当成员被移除时 | + +- **注:需要引入`GuildMember`** -- **注:需要引入`GuildMember`** ```python -from botpy.types.guild import GuildMember +from botpy.user import Member ``` ```python class MyClient(botpy.Client): - async def on_guild_member_add(self, member: GuildMember): + async def on_guild_member_add(self, member: Member): """ 此处为处理该事件的代码 """ - async def on_guild_member_update(self, member: GuildMember): + async def on_guild_member_update(self, member: Member): """ 此处为处理该事件的代码 """ - async def on_guild_member_remove(self, member: GuildMember): + async def on_guild_member_remove(self, member: Member): """ 此处为处理该事件的代码 """ @@ -262,11 +266,12 @@ intents = botpy.Intents(interaction=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | +| 对应函数 | 说明 | +| ----------------------------------------------------- | ---------------- | | on_interaction_create(self, interaction: Interaction) | 当收到用户发给机器人的私信消息时 | -- **注:需要引入`Interaction`** +- **注:需要引入`Interaction`** + ```python from botpy.interaction import Interaction ``` @@ -288,12 +293,13 @@ intents = botpy.Intents(message_audit=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_message_audit_pass(self, message: MessageAudit) | 消息审核通过 | +| 对应函数 | 说明 | +| ---------------------------------------------------- | ------- | +| on_message_audit_pass(self, message: MessageAudit) | 消息审核通过 | | on_message_audit_reject(self, message: MessageAudit) | 消息审核不通过 | -- **注:需要引入`MessageAudit`** +- **注:需要引入`MessageAudit`** + ```python from botpy.message import MessageAudit ``` @@ -312,9 +318,7 @@ class MyClient(botpy.Client): ### 论坛事件的监听 - -- **仅 私域 机器人能够设置此 intents** - +- **仅 私域 机器人能够设置此 intents** 首先需要订阅事件`forums` @@ -323,20 +327,22 @@ intents = botpy.Intents(forums=True) client = MyClient(intents=intents) ``` -|对应函数| 说明 | -| --------- | ---- | -| on_forum_thread_create(self, thread: Thread) | 当用户创建主题时 | -| on_forum_thread_update(self, thread: Thread) | 当用户更新主题时 | -| on_forum_thread_delete(self, thread: Thread) | 当用户删除主题时 | -| on_forum_post_create(self, post: Post) | 当用户创建帖子时 | -| on_forum_post_delete(self, post: Post) | 当用户删除帖子时 | -| on_forum_reply_create(self, reply: Reply) | 当用户回复评论时 | -| on_forum_reply_delete(self, reply: Reply) | 当用户删除评论时 | +| 对应函数 | 说明 | +| ------------------------------------------------------------- | ---------- | +| on_forum_thread_create(self, thread: Thread) | 当用户创建主题时 | +| on_forum_thread_update(self, thread: Thread) | 当用户更新主题时 | +| on_forum_thread_delete(self, thread: Thread) | 当用户删除主题时 | +| on_forum_post_create(self, post: Post) | 当用户创建帖子时 | +| on_forum_post_delete(self, post: Post) | 当用户删除帖子时 | +| on_forum_reply_create(self, reply: Reply) | 当用户回复评论时 | +| on_forum_reply_delete(self, reply: Reply) | 当用户删除评论时 | | on_forum_publish_audit_result(self, auditresult: AuditResult) | 当用户发表审核通过时 | -- **注:需要引入`Thread`、`Post`、`Reply`和`AuditResult`** +- **注:需要引入`Thread`、`Post`、`Reply`和`AuditResult`** + ```python -from botpy.types.forum import Thread, Post, Reply, AuditResult +from botpy.forum import Thread +from botpy.types.forum import Post, Reply, AuditResult ``` ```python @@ -384,8 +390,38 @@ intents = botpy.Intents(audio_action=True) client = MyClient(intents=intents) ``` -@TODO 完善audio_action(Huang1220(neutron)) +| 对应函数 | 说明 | +| ------------------------------------ | ------- | +| on_audio_start(self, audio: Audio) | 音频开始播放时 | +| on_audio_finish(self, audio: Audio) | 音频播放结束时 | +| on_audio_on_mic(self, audio: Audio) | 上麦时 | +| on_audio_off_mic(self, audio: Audio) | 下麦时 | + +- **注:需要引入`Audio`** + +```python +from botpy.audio import Audio +``` +```python +class MyClient(botpy.Client): + async def on_audio_start(self, audio: Audio): + """ + 此处为处理该事件的代码 + """ + async def on_audio_finish(self, audio: Audio): + """ + 此处为处理该事件的代码 + """ + async def on_audio_on_mic(self, audio: Audio): + """ + 此处为处理该事件的代码 + """ + async def on_audio_off_mic(self, audio: Audio): + """ + 此处为处理该事件的代码 + """ +``` ## 订阅事件的方法 @@ -418,32 +454,33 @@ intents.direct_message=True intents.guilds=True ``` -- **说明** +- **说明** 方法二对应的快捷订阅方式为 -1. 订阅所有事件 +1. 订阅所有事件 ```python intents = botpy.Intents.all() ``` -2. 订阅所有的公域事件 +2. 订阅所有的公域事件 ```python intents = botpy.Intents.default() ``` #### 参数列表 -| 参数 | 含义 | -| ---- | ---- | -| public_guild_messages | 公域消息事件 | -| guild_messages | 消息事件 **(仅 `私域` 机器人能够设置此 intents)** | -| direct_message | 私信事件 | -| guild_message_reactions | 消息相关互动事件 | -| guilds | 频道事件 | -| guild_members | 频道成员事件 | -| interaction | 互动事件 | -| message_audit | 消息审核事件 | -| forums | 论坛事件 **(仅 `私域` 机器人能够设置此 intents)** | -| audio_action | 音频事件 | + +| 参数 | 含义 | +| ----------------------- | ---------------------------------- | +| public_guild_messages | 公域消息事件 | +| guild_messages | 消息事件 **(仅 `私域` 机器人能够设置此 intents)** | +| direct_message | 私信事件 | +| guild_message_reactions | 消息相关互动事件 | +| guilds | 频道事件 | +| guild_members | 频道成员事件 | +| interaction | 互动事件 | +| message_audit | 消息审核事件 | +| forums | 论坛事件 **(仅 `私域` 机器人能够设置此 intents)** | +| audio_action | 音频事件 | From 840ae515c613974a67a2f61c78d0dc61527d3d18 Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Fri, 17 Jun 2022 16:53:23 +0800 Subject: [PATCH 05/10] =?UTF-8?q?fix:=20forum=20thread=E7=9A=84=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E6=95=B0=E6=8D=AE=E5=90=8D=E7=A7=B0=E6=9B=B4=E5=8F=98?= =?UTF-8?q?=E5=90=8E=E5=90=8C=E6=AD=A5=E6=95=B0=E6=8D=AE=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E5=88=B0=E5=85=B6=E4=BB=96=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/connection.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/botpy/connection.py b/botpy/connection.py index ada3a3b..440f6f4 100644 --- a/botpy/connection.py +++ b/botpy/connection.py @@ -9,7 +9,7 @@ from .user import Member from .reaction import Reaction from .audio import Audio -from .forum import Forum +from .forum import Thread from . import logging from .api import BotAPI @@ -197,15 +197,15 @@ def parse_resumed(self, ctx: gateway.WsContext, data: gateway.ReadyEvent): self._dispatch("resumed") def parse_forum_thread_create(self, ctx: gateway.WsContext, data: forum.Thread): - _forum = Forum(self.api, ctx, data) + _forum = Thread(self.api, ctx, data) self._dispatch("forum_thread_create", _forum) def parse_forum_thread_update(self, ctx: gateway.WsContext, data: forum.Thread): - _forum = Forum(self.api, ctx, data) + _forum = Thread(self.api, ctx, data) self._dispatch("forum_thread_update", _forum) def parse_forum_thread_delete(self, ctx: gateway.WsContext, data: forum.Thread): - _forum = Forum(self.api, ctx, data) + _forum = Thread(self.api, ctx, data) self._dispatch("forum_thread_delete", _forum) def parse_forum_post_create(self, ctx: gateway.WsContext, data: forum.Post): From 9b92ad5621ee220a3b2aa6b772d5519a9cce38a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=BF=B5=E5=90=8C=E5=AD=A6?= <2660422452@qq.com> Date: Fri, 17 Jun 2022 20:54:06 +0800 Subject: [PATCH 06/10] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96ext?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E6=89=A9=E5=B1=95=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/ext/__init__.py | 2 +- .../__init__.py} | 141 +++++++++--------- botpy/ext/cog_yaml/__init__.py | 16 ++ botpy/ext/color_util.py | 40 ----- botpy/ext/converrt_color/__init__.py | 38 +++++ botpy/ext/yaml_util.py | 16 -- examples/demo_announce.py | 6 +- examples/demo_api_permission.py | 8 +- examples/demo_at_reply.py | 7 +- examples/demo_at_reply_ark.py | 6 +- examples/demo_at_reply_command.py | 5 +- examples/demo_at_reply_embed.py | 14 +- examples/demo_at_reply_file_data.py | 9 +- examples/demo_at_reply_keyboard.py | 8 +- examples/demo_at_reply_markdown.py | 11 +- examples/demo_at_reply_reference.py | 7 +- examples/demo_dms_reply.py | 15 +- examples/demo_get_reaction_users.py | 8 +- examples/demo_guild_member_event.py | 14 +- examples/demo_interaction.py | 8 +- examples/demo_pins_message.py | 10 +- examples/demo_recall.py | 9 +- examples/demo_schedule.py | 9 +- tests/__init__.py | 4 +- 24 files changed, 204 insertions(+), 207 deletions(-) rename botpy/ext/{channel_jump_util.py => channel_jump/__init__.py} (96%) create mode 100644 botpy/ext/cog_yaml/__init__.py delete mode 100644 botpy/ext/color_util.py create mode 100644 botpy/ext/converrt_color/__init__.py delete mode 100644 botpy/ext/yaml_util.py diff --git a/botpy/ext/__init__.py b/botpy/ext/__init__.py index 7f428da..c94efe6 100644 --- a/botpy/ext/__init__.py +++ b/botpy/ext/__init__.py @@ -2,4 +2,4 @@ """ 这里放一些可用的工具 方便开发者调用 -""" \ No newline at end of file +""" diff --git a/botpy/ext/channel_jump_util.py b/botpy/ext/channel_jump/__init__.py similarity index 96% rename from botpy/ext/channel_jump_util.py rename to botpy/ext/channel_jump/__init__.py index 80fa85b..2ad7f3a 100644 --- a/botpy/ext/channel_jump_util.py +++ b/botpy/ext/channel_jump/__init__.py @@ -1,70 +1,71 @@ -""" -对子频道转跳进行操作(#name) -注意: -1、发送格式要求严格(#name ),自动添加的空格不能删除 -2、无法识别真假转跳 -3、当子频道重名时无法准确识别 -4、当提供子频道转跳字段时请弃用本模块 -""" - -__all__ = [ - "get_channel_jump", - "get_channel_jump_strict", - "escape_channel_jump" -] - -import re -from typing import List, Dict - -from botpy import BotAPI -from botpy.message import Message - - -def get_channel_jump(text: str = None, message: Message = None) -> List[str]: - """ - 识别文本中的子频道转跳(粗略) - :param message: 消息对象 - :param text: 文本,为空则message.content - :return: 子频道名称列表(不带#) - """ - channel_jump_re = re.compile(r"#(.{1,12}?)(?= )") - return channel_jump_re.findall(message.content if text is None else text) - - -async def get_channel_jump_strict(api: BotAPI, message: Message = None, text: str = None, - guild_id: str = None) -> Dict[str, str]: - """ - 识别文本中的子频道转跳(准确) - :param api: BotAPI - :param message: 消息对象 - :param text: 文本,为空则message.content - :param guild_id: 频道id,为空则message.guild_id - :return: {子频道名称(不带#):子频道id} (去重) - """ - channels = await api.get_channels(guild_id or message.guild_id) - text = message.content if text is None else text - jumps = {} - - for channel in channels: - if "#%s " % channel["name"] in text: - jumps[channel["name"]] = channel["id"] - - return jumps - - -async def escape_channel_jump(api: BotAPI, message: Message = None, text: str = None, guild_id: str = None) -> str: - """ - 转义子频道转跳 (#name -> <#id>) - :param api: BotAPI - :param message: 消息对象 - :param text: 文本,为空则message.content - :param guild_id: 频道id,为空则message.guild_id - :return: 转义后的文本 - """ - channels = await api.get_channels(guild_id or message.guild_id) - text = message.content if text is None else text - - for channel in channels: - text = text.replace("#%s " % channel["name"], "<#%s> " % channel["id"]) - - return text +# -*- coding: utf-8 -*- +""" +对子频道转跳进行操作(#name) +注意: +1、发送格式要求严格(#name ),自动添加的空格不能删除 +2、无法识别真假转跳 +3、当子频道重名时无法准确识别 +4、当提供子频道转跳字段时请弃用本模块 +""" + +__all__ = [ + "get_channel_jump", + "get_channel_jump_strict", + "escape_channel_jump" +] + +import re +from typing import List, Dict + +from botpy import BotAPI +from botpy.message import Message + + +def get_channel_jump(text: str = None, message: Message = None) -> List[str]: + """ + 识别文本中的子频道转跳(粗略) + :param message: 消息对象 + :param text: 文本,为空则message.content + :return: 子频道名称列表(不带#) + """ + channel_jump_re = re.compile(r"#(.{1,12}?)(?= )") + return channel_jump_re.findall(message.content if text is None else text) + + +async def get_channel_jump_strict(api: BotAPI, message: Message = None, text: str = None, + guild_id: str = None) -> Dict[str, str]: + """ + 识别文本中的子频道转跳(准确) + :param api: BotAPI + :param message: 消息对象 + :param text: 文本,为空则message.content + :param guild_id: 频道id,为空则message.guild_id + :return: {子频道名称(不带#):子频道id} (去重) + """ + channels = await api.get_channels(guild_id or message.guild_id) + text = message.content if text is None else text + jumps = {} + + for channel in channels: + if "#%s " % channel["name"] in text: + jumps[channel["name"]] = channel["id"] + + return jumps + + +async def escape_channel_jump(api: BotAPI, message: Message = None, text: str = None, guild_id: str = None) -> str: + """ + 转义子频道转跳 (#name -> <#id>) + :param api: BotAPI + :param message: 消息对象 + :param text: 文本,为空则message.content + :param guild_id: 频道id,为空则message.guild_id + :return: 转义后的文本 + """ + channels = await api.get_channels(guild_id or message.guild_id) + text = message.content if text is None else text + + for channel in channels: + text = text.replace("#%s " % channel["name"], "<#%s> " % channel["id"]) + + return text diff --git a/botpy/ext/cog_yaml/__init__.py b/botpy/ext/cog_yaml/__init__.py new file mode 100644 index 0000000..f552f6b --- /dev/null +++ b/botpy/ext/cog_yaml/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +import yaml + +from typing import Dict, Any + + +def read(yaml_path) -> Dict[str, Any]: + """ + 读取指定目录的yaml文件 + + :param yaml_path: 相对当前的yaml文件绝对路径 + :return: + """ + # 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况。 + with open(yaml_path, "r", encoding="utf-8") as f: + return yaml.safe_load(f) \ No newline at end of file diff --git a/botpy/ext/color_util.py b/botpy/ext/color_util.py deleted file mode 100644 index 4838321..0000000 --- a/botpy/ext/color_util.py +++ /dev/null @@ -1,40 +0,0 @@ -# -*- coding: utf-8 -*- - - -class ColorUtil: - @staticmethod - def convert(color: tuple or str): - """ - 将 RGB 值的元组或 HEX 值的字符串转换为单个整数 - - Args: - color (tuple or str): 输入RGB的三位tuple或HEX的sting颜色 - - Returns: - 颜色的 RGB 值。 - """ - colors = [] - if isinstance(color, tuple): - if len(color) == 3: - for items in color: - if not isinstance(items, int) or items > 255 or items < 0: - raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)") - colors.append(int(items)) - else: - raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)") - elif isinstance(color, str): - colour = color.replace("#", "") - if len(colour) == 6: - for items in [colour[:2], colour[2:4], colour[4:]]: - try: - local_colour = int(items, 16) - except ValueError: - raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确") - if local_colour > 255 or local_colour < 0: - raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确") - colors.append(local_colour) - else: - raise TypeError('HEX颜色应为一个 #加六位数字或字母 的string,如"#ffffff"') - else: - raise TypeError('颜色值应为RGB的三位tuple,如(255,255,255);或HEX的sting颜色,如"#ffffff"') - return colors[0] + 256 * colors[1] + 256 * 256 * colors[2] diff --git a/botpy/ext/converrt_color/__init__.py b/botpy/ext/converrt_color/__init__.py new file mode 100644 index 0000000..5979b94 --- /dev/null +++ b/botpy/ext/converrt_color/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + + +def start(color: tuple or str) -> int: + """ + 将 RGB 值的元组或 HEX 值的字符串转换为单个整数 + + Args: + color (tuple or str): 输入RGB的三位tuple或HEX的sting颜色 + + Returns: + 颜色的 RGB 值。 + """ + colors = [] + if isinstance(color, tuple): + if len(color) == 3: + for items in color: + if not isinstance(items, int) or items > 255 or items < 0: + raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)") + colors.append(int(items)) + else: + raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)") + elif isinstance(color, str): + colour = color.replace("#", "") + if len(colour) == 6: + for items in [colour[:2], colour[2:4], colour[4:]]: + try: + local_colour = int(items, 16) + except ValueError: + raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确") + if local_colour > 255 or local_colour < 0: + raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确") + colors.append(local_colour) + else: + raise TypeError('HEX颜色应为一个 #加六位数字或字母 的string,如"#ffffff"') + else: + raise TypeError('颜色值应为RGB的三位tuple,如(255,255,255);或HEX的sting颜色,如"#ffffff"') + return colors[0] + 256 * colors[1] + 256 * 256 * colors[2] \ No newline at end of file diff --git a/botpy/ext/yaml_util.py b/botpy/ext/yaml_util.py deleted file mode 100644 index a2b1822..0000000 --- a/botpy/ext/yaml_util.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -import yaml - - -class YamlUtil: - @staticmethod - def read(yaml_path): - """ - 读取指定目录的yaml文件 - - :param yaml_path: 相对当前的yaml文件绝对路径 - :return: - """ - # 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况。 - with open(yaml_path, "r", encoding="utf-8") as f: - return yaml.safe_load(f) \ No newline at end of file diff --git a/examples/demo_announce.py b/examples/demo_announce.py index 48c9739..60403cf 100644 --- a/examples/demo_announce.py +++ b/examples/demo_announce.py @@ -1,12 +1,14 @@ +# -*- coding: utf-8 -*- import os import botpy from botpy import logging + from botpy.message import Message from botpy.types.announce import AnnouncesType -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_api_permission.py b/examples/demo_api_permission.py index 653cc02..04fb8d7 100644 --- a/examples/demo_api_permission.py +++ b/examples/demo_api_permission.py @@ -1,14 +1,14 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import botpy from botpy import logging + from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil from botpy.types.permission import APIPermissionDemandIdentify +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_at_reply.py b/examples/demo_at_reply.py index 2668aeb..ba005f2 100644 --- a/examples/demo_at_reply.py +++ b/examples/demo_at_reply.py @@ -1,11 +1,13 @@ +# -*- coding: utf-8 -*- import os import botpy from botpy import logging + from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() @@ -15,6 +17,7 @@ async def on_ready(self): _log.info(f"robot 「{self.robot.name}」 on_ready!") async def on_at_message_create(self, message: Message): + _log.info(message.author.get("avatar")) await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}") diff --git a/examples/demo_at_reply_ark.py b/examples/demo_at_reply_ark.py index 6b5bda4..fbb55d9 100644 --- a/examples/demo_at_reply_ark.py +++ b/examples/demo_at_reply_ark.py @@ -1,12 +1,14 @@ +# -*- coding: utf-8 -*- import os import botpy from botpy import logging + from botpy.message import Message from botpy.types.message import Ark, ArkKv -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_at_reply_command.py b/examples/demo_at_reply_command.py index fbd9291..5bda7d5 100644 --- a/examples/demo_at_reply_command.py +++ b/examples/demo_at_reply_command.py @@ -3,11 +3,12 @@ import botpy from botpy import logging, BotAPI + from botpy.ext.command_util import Commands from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_at_reply_embed.py b/examples/demo_at_reply_embed.py index a2c3ee9..7cb52a9 100644 --- a/examples/demo_at_reply_embed.py +++ b/examples/demo_at_reply_embed.py @@ -1,12 +1,14 @@ +# -*- coding: utf-8 -*- import os import botpy from botpy import logging + from botpy.message import Message from botpy.types.message import Embed, EmbedField -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() @@ -21,8 +23,8 @@ async def on_at_message_create(self, message: Message): title="embed消息", prompt="消息透传显示", fields=[ - EmbedField(name="<@!1234>hello world", value="通知提醒"), - EmbedField(name="<@!1234>hello world", value="通知提醒"), + EmbedField(name="<@!1234>hello world"), + EmbedField(name="<@!1234>hello world"), ], ) @@ -30,8 +32,8 @@ async def on_at_message_create(self, message: Message): # "title": "embed消息", # "prompt": "消息透传显示", # "fields": [ - # {"name": "<@!1234>hello world", "value": "通知提醒"}, - # {"name": "<@!1234>hello world", "value": "标题"}, + # {"name": "<@!1234>hello world"}, + # {"name": "<@!1234>hello world"}, # ], # } diff --git a/examples/demo_at_reply_file_data.py b/examples/demo_at_reply_file_data.py index 47fd628..f73eb2e 100644 --- a/examples/demo_at_reply_file_data.py +++ b/examples/demo_at_reply_file_data.py @@ -1,16 +1,13 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -""" -上传本地文件DEMO -""" import os import botpy from botpy import logging + from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_at_reply_keyboard.py b/examples/demo_at_reply_keyboard.py index 16c1cc6..c5fc249 100644 --- a/examples/demo_at_reply_keyboard.py +++ b/examples/demo_at_reply_keyboard.py @@ -1,15 +1,15 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import botpy from botpy import BotAPI + from botpy.message import Message from botpy.types.inline import Keyboard, Button, RenderData, Action, Permission, KeyboardRow from botpy.types.message import MarkdownPayload, KeyboardPayload -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) class MyClient(botpy.Client): diff --git a/examples/demo_at_reply_markdown.py b/examples/demo_at_reply_markdown.py index c2d8560..926a0e4 100644 --- a/examples/demo_at_reply_markdown.py +++ b/examples/demo_at_reply_markdown.py @@ -1,17 +1,16 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import botpy from botpy import logging + from botpy.message import Message from botpy.types.message import MarkdownPayload, MessageMarkdownParams -from botpy.ext.yaml_util import YamlUtil - -_log = logging.get_logger() +from botpy.ext.cog_yaml import read +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +_log = logging.get_logger() class MyClient(botpy.Client): diff --git a/examples/demo_at_reply_reference.py b/examples/demo_at_reply_reference.py index e134f55..260a42f 100644 --- a/examples/demo_at_reply_reference.py +++ b/examples/demo_at_reply_reference.py @@ -1,15 +1,14 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- - import os import botpy from botpy import logging + from botpy.types.message import Reference from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_dms_reply.py b/examples/demo_dms_reply.py index 48171bf..386a358 100644 --- a/examples/demo_dms_reply.py +++ b/examples/demo_dms_reply.py @@ -1,18 +1,13 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -""" - -搁置 - -""" import os import botpy from botpy import logging -from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +from botpy.message import DirectMessage +from botpy.ext.cog_yaml import read + +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() @@ -21,7 +16,7 @@ class MyClient(botpy.Client): async def on_ready(self): _log.info(f"robot 「{self.robot.name}」 on_ready!") - async def on_direct_message_create(self, message: Message): + async def on_direct_message_create(self, message: DirectMessage): await self.api.post_dms( guild_id=message.guild_id, content=f"机器人{self.robot.name}收到你的私信了: {message.content}", diff --git a/examples/demo_get_reaction_users.py b/examples/demo_get_reaction_users.py index bf0c082..054e23f 100644 --- a/examples/demo_get_reaction_users.py +++ b/examples/demo_get_reaction_users.py @@ -1,15 +1,15 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os from typing import List import botpy + from botpy.message import Message from botpy.types import reaction from botpy.types.user import User -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) class MyClient(botpy.Client): diff --git a/examples/demo_guild_member_event.py b/examples/demo_guild_member_event.py index a49c93f..852a1e8 100644 --- a/examples/demo_guild_member_event.py +++ b/examples/demo_guild_member_event.py @@ -1,11 +1,13 @@ +# -*- coding: utf-8 -*- import os import botpy from botpy import logging -from botpy.types.user import Member -from botpy.ext.yaml_util import YamlUtil -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +from botpy.user import Member +from botpy.ext.cog_yaml import read + +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() @@ -15,13 +17,13 @@ async def on_ready(self): _log.info(f"robot 「{self.robot.name}」 on_ready!") async def on_guild_member_add(self, member: Member): - _log.info("%s 加入频道" % member["nick"]) + _log.info("%s 加入频道" % member.nick) async def on_guild_member_update(self, member: Member): - _log.info("%s 更新了资料" % member["nick"]) + _log.info("%s 更新了资料" % member.nick) async def on_guild_member_remove(self, member: Member): - _log.info("%s 退出了频道" % member["nick"]) + _log.info("%s 退出了频道" % member.nick) if __name__ == "__main__": diff --git a/examples/demo_interaction.py b/examples/demo_interaction.py index 3c94752..9eb69cd 100644 --- a/examples/demo_interaction.py +++ b/examples/demo_interaction.py @@ -1,15 +1,13 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import botpy from botpy import logging from botpy.interaction import Interaction -from botpy.ext.yaml_util import YamlUtil - -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "qq-bot/config.yaml")) +from botpy.ext.cog_yaml import read +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_pins_message.py b/examples/demo_pins_message.py index 8836ebf..25b50d9 100644 --- a/examples/demo_pins_message.py +++ b/examples/demo_pins_message.py @@ -1,15 +1,13 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import botpy - from botpy import logging -from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +from botpy.message import Message +from botpy.ext.cog_yaml import read +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_recall.py b/examples/demo_recall.py index 199f243..4756e5b 100644 --- a/examples/demo_recall.py +++ b/examples/demo_recall.py @@ -1,14 +1,13 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import botpy from botpy import logging -from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) +from botpy.message import Message +from botpy.ext.cog_yaml import read +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() diff --git a/examples/demo_schedule.py b/examples/demo_schedule.py index d844d0d..cd48476 100644 --- a/examples/demo_schedule.py +++ b/examples/demo_schedule.py @@ -1,14 +1,15 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import os.path +import os import time import botpy from botpy import logging + from botpy.message import Message -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read + +test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml")) -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml")) _log = logging.get_logger() CHANNEL_SCHEDULE_ID = "12333" # 修改为自己频道的日程子频道ID diff --git a/tests/__init__.py b/tests/__init__.py index ea74097..939041c 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -2,7 +2,7 @@ import os -from botpy.ext.yaml_util import YamlUtil +from botpy.ext.cog_yaml import read # github下修改 .test(demo).yaml 为 .test.yaml -test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), ".test.yaml")) +test_config = read(os.path.join(os.path.dirname(__file__), ".test.yaml")) From 8ec08748c1b8ebb8292d0374c1bc3adadf0f5bb2 Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Fri, 17 Jun 2022 23:23:39 +0800 Subject: [PATCH 07/10] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96ext?= =?UTF-8?q?=E7=9A=84convert=5Fcolor=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/ext/converrt_color/__init__.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/botpy/ext/converrt_color/__init__.py b/botpy/ext/converrt_color/__init__.py index 5979b94..8f689c0 100644 --- a/botpy/ext/converrt_color/__init__.py +++ b/botpy/ext/converrt_color/__init__.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- +from typing import Union -def start(color: tuple or str) -> int: +def start(color: Union[tuple, str]) -> int: """ 将 RGB 值的元组或 HEX 值的字符串转换为单个整数 @@ -15,24 +16,24 @@ def start(color: tuple or str) -> int: if isinstance(color, tuple): if len(color) == 3: for items in color: - if not isinstance(items, int) or items > 255 or items < 0: + if not isinstance(items, int) or items not in range(256): raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)") - colors.append(int(items)) + colors.append(items) else: raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)") elif isinstance(color, str): colour = color.replace("#", "") if len(colour) == 6: - for items in [colour[:2], colour[2:4], colour[4:]]: + for items in (colour[:2], colour[2:4], colour[4:]): try: - local_colour = int(items, 16) + items = int(items, 16) except ValueError: raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确") - if local_colour > 255 or local_colour < 0: + if items not in range(256): raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确") - colors.append(local_colour) + colors.append(items) else: raise TypeError('HEX颜色应为一个 #加六位数字或字母 的string,如"#ffffff"') else: raise TypeError('颜色值应为RGB的三位tuple,如(255,255,255);或HEX的sting颜色,如"#ffffff"') - return colors[0] + 256 * colors[1] + 256 * 256 * colors[2] \ No newline at end of file + return colors[0] + 256 * colors[1] + (256**2) * colors[2] From 15d2dc2732bc2a532e6280fa521d673dbbdd20fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=BF=B5=E5=90=8C=E5=AD=A6?= <2660422452@qq.com> Date: Sat, 18 Jun 2022 01:34:16 +0800 Subject: [PATCH 08/10] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96ext?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E6=89=A9=E5=B1=95=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/ext/command_util.py | 10 +++++++--- examples/demo_at_reply_command.py | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/botpy/ext/command_util.py b/botpy/ext/command_util.py index 3d30f78..7e7cb78 100644 --- a/botpy/ext/command_util.py +++ b/botpy/ext/command_util.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from functools import wraps +from typing import Union from botpy import BotAPI from botpy.message import Message @@ -8,10 +9,13 @@ class Commands: """ 指令装饰器 + + Args: + name (Union[tuple, str]): 字符串元组或单个字符串。 """ - def __init__(self, commands: tuple or str): - self.commands = commands + def __init__(self, name: Union[tuple, str]): + self.commands = name def __call__(self, func): @wraps(func) @@ -22,7 +26,7 @@ async def decorated(*args, **kwargs): for command in self.commands: if command in message.content: # 分割指令后面的指令参数 - params = message.content.split(self.commands)[1].strip() + params = message.content.split(command)[1].strip() return await func(api=api, message=message, params=params) elif self.commands in message.content: # 分割指令后面的指令参数 diff --git a/examples/demo_at_reply_command.py b/examples/demo_at_reply_command.py index 5bda7d5..7d4f441 100644 --- a/examples/demo_at_reply_command.py +++ b/examples/demo_at_reply_command.py @@ -13,7 +13,7 @@ _log = logging.get_logger() -@Commands("你好") +@Commands(commands=("你好", "hello")) async def hello(api: BotAPI, message: Message, params=None): _log.info(params) # 第一种用reply发送消息 From f802ef8204983a962109c870e38b0e1871c7811f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=BF=B5=E5=90=8C=E5=AD=A6?= <2660422452@qq.com> Date: Sat, 18 Jun 2022 01:34:34 +0800 Subject: [PATCH 09/10] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96ext?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E6=89=A9=E5=B1=95=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/demo_at_reply_command.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/demo_at_reply_command.py b/examples/demo_at_reply_command.py index 7d4f441..075cd77 100644 --- a/examples/demo_at_reply_command.py +++ b/examples/demo_at_reply_command.py @@ -13,7 +13,7 @@ _log = logging.get_logger() -@Commands(commands=("你好", "hello")) +@Commands(name=("你好", "hello")) async def hello(api: BotAPI, message: Message, params=None): _log.info(params) # 第一种用reply发送消息 From c485a4333e97c8642b2efa44bef4641c1aa164fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=BF=B5=E5=90=8C=E5=AD=A6?= <2660422452@qq.com> Date: Sun, 19 Jun 2022 03:15:20 +0800 Subject: [PATCH 10/10] =?UTF-8?q?docs:=20=E4=BF=AE=E6=94=B9=E4=B8=80?= =?UTF-8?q?=E5=A4=84=E8=A1=A8=E8=BF=B0=E4=B8=8D=E6=AD=A3=E7=A1=AE=E7=9A=84?= =?UTF-8?q?=E5=9C=B0=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/api.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/botpy/api.py b/botpy/api.py index 7f287f9..08e69c4 100644 --- a/botpy/api.py +++ b/botpy/api.py @@ -735,9 +735,9 @@ async def mute_member( self, guild_id: str, user_id: str, mute_end_timestamp: str = None, mute_seconds: str = None ) -> str: """ - 使频道中的所有成员禁言。 + 使频道中的指定成员禁言。 - 用于将频道的全体成员(非管理员)禁言。 + 用于将频道的指定成员(非管理员)禁言。 需要使用的 token 对应的用户具备管理员权限。如果是机器人,要求被添加为管理员。 Args: @@ -1181,6 +1181,7 @@ async def get_pins(self, channel_id: str) -> pins_message.PinsMessage: ) return await self._http.request(route) + # 帖子相关接口 async def get_threads(self, channel_id: str) -> forum.ForumRsp: """ 该接口用于获取子频道下的帖子列表。