From 9564cb2858833fb8de442123226fe7a46f743fe6 Mon Sep 17 00:00:00 2001 From: GLGDLY Date: Thu, 16 Jun 2022 21:44:26 +0800 Subject: [PATCH 01/19] =?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/19] =?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/19] =?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/19] =?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/19] =?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/19] =?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/19] =?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/19] =?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/19] =?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/19] =?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: """ 该接口用于获取子频道下的帖子列表。 From 2609dd35eb5197633ce36018c5848761081570cc 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: Tue, 21 Jun 2022 18:07:55 +0800 Subject: [PATCH 11/19] =?UTF-8?q?feat:=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/ext/{converrt_color => convert_color}/__init__.py | 0 botpy/interaction.py | 1 - 2 files changed, 1 deletion(-) rename botpy/ext/{converrt_color => convert_color}/__init__.py (100%) diff --git a/botpy/ext/converrt_color/__init__.py b/botpy/ext/convert_color/__init__.py similarity index 100% rename from botpy/ext/converrt_color/__init__.py rename to botpy/ext/convert_color/__init__.py diff --git a/botpy/interaction.py b/botpy/interaction.py index 6be5973..7871362 100644 --- a/botpy/interaction.py +++ b/botpy/interaction.py @@ -7,7 +7,6 @@ class Interaction: def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: interaction.InteractionPayload): self._api = api - # self._ctx = ctx self.id = data.get("id") self.type = data.get("type") From 5e7f5985f34f6f3885c4f132ac1aec52417fa9e1 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: Thu, 23 Jun 2022 17:43:37 +0800 Subject: [PATCH 12/19] =?UTF-8?q?fix:=20=E5=B8=96=E5=AD=90api=E4=B8=ADrout?= =?UTF-8?q?e=E6=96=B9=E5=BC=8F=E9=94=99=E8=AF=AF=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/api.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/botpy/api.py b/botpy/api.py index 08e69c4..df139cb 100644 --- a/botpy/api.py +++ b/botpy/api.py @@ -1233,7 +1233,7 @@ async def post_thread(self, channel_id: str, title: str, content: str, format: f """ route = Route( "PUT", - "PUT /channels/{channel_id}/threads", + "/channels/{channel_id}/threads", channel_id=channel_id, ) @@ -1252,6 +1252,6 @@ async def delete_thread(self, channel_id: str, thread_id: str) -> str: 成功返回空字符串。 """ route = Route( - "DELETE", "DELETE /channels/{channel_id}/threads/{thread_id}", channel_id=channel_id, thread_id=thread_id + "DELETE", "/channels/{channel_id}/threads/{thread_id}", channel_id=channel_id, thread_id=thread_id ) return await self._http.request(route) From 3db66acd32512e7dc9b5ffe9a605e794147f30bb 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, 24 Jun 2022 00:19:17 +0800 Subject: [PATCH 13/19] =?UTF-8?q?feat:=20=E8=A1=A5=E9=BD=90=E9=A2=91?= =?UTF-8?q?=E9=81=93=E6=88=90=E5=91=98=E4=B8=AD=E7=9A=84=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E9=A2=91=E9=81=93=E6=88=90=E5=91=98api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/api.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/botpy/api.py b/botpy/api.py index df139cb..8b77f21 100644 --- a/botpy/api.py +++ b/botpy/api.py @@ -194,6 +194,37 @@ async def get_guild_member(self, guild_id: str, user_id: str) -> user.Member: ) return await self._http.request(route) + async def get_delete_member( + self, + guild_id: str, + user_id: str, + add_blacklist: bool = False, + delete_history_msg_days: int = 0 + ) -> str: + """ + 删除频道成员 + + Args: + guild_id (str): 频道ID + user_id (str): 用户ID + add_blacklist (bool): 是否同时添加黑名单 + delete_history_msg_days (int): 用于撤回该成员的消息,可以指定撤回消息的时间范围 + + Returns: + 成功执行返回`None`。成功执行返回空字符串 + """ + # 注:消息撤回时间范围仅支持固定的天数:3,7,15,30。 特殊的时间范围:-1: 撤回全部消息。默认值为0不撤回任何消息。 + if delete_history_msg_days not in (3, 7, 15, 30, 0, -1): + delete_history_msg_days = 0 + params = {'add_blacklist': str(add_blacklist).lower(), 'delete_history_msg_days': delete_history_msg_days} + route = Route( + "DELETE", + "/guilds/{guild_id}/members/{user_id}", + guild_id=guild_id, + user_id=user_id, + ) + return await self._http.request(route, params=params) + async def get_guild_members(self, guild_id: str, after: str = "0", limit: int = 1) -> List[user.Member]: """ 获取成员列表。 From 460ba102fccd57a696c78bddf2db4ea3a52747ce 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, 24 Jun 2022 21:24:22 +0800 Subject: [PATCH 14/19] =?UTF-8?q?feat:=20=E6=9B=B4=E6=96=B0=E6=96=87?= =?UTF-8?q?=E6=A1=A3=E5=B9=B6=E6=96=B0=E5=A2=9E=E5=AE=9A=E6=97=B6=E6=A1=86?= =?UTF-8?q?=E6=9E=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 40 ++++++++++++++++++--------- botpy/api.py | 2 +- botpy/ext/cog_apscheduler/__init__.py | 13 +++++++++ requirements.txt | 3 +- setup.py | 2 +- 5 files changed, 44 insertions(+), 16 deletions(-) create mode 100644 botpy/ext/cog_apscheduler/__init__.py diff --git a/README.md b/README.md index 285fcef..9270103 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,25 @@ -# botpy +
-**botpy** 是基于[机器人开放平台API](https://bot.q.qq.com/wiki/develop/api/) 实现的机器人框架,目的提供一个易使用、开发效率高的开发框架。 +![botpy](https://socialify.git.ci/tencent-connect/botpy/image?description=1&font=Source%20Code%20Pro&forks=1&issues=1&language=1&logo=https%3A%2F%2Fgithub.com%2Ftencent-connect%2Fbot-docs%2Fblob%2Fmain%2Fdocs%2F.vuepress%2Fpublic%2Ffavicon-64px.png%3Fraw%3Dtrue&owner=1&pattern=Circuit%20Board&pulls=1&stargazers=1&theme=Light) +[![Language](https://img.shields.io/badge/language-python-green.svg?style=plastic)](https://www.python.org/) +[![License](https://img.shields.io/badge/license-MIT-orange.svg?style=plastic)](https://github.com/tencent-connect/botpy/blob/master/LICENSE) +![Python](https://img.shields.io/badge/python-3.8+-blue) ![PyPI](https://img.shields.io/pypi/v/qq-botpy) [![BK Pipelines Status](https://api.bkdevops.qq.com/process/api/external/pipelines/projects/qq-guild-open/p-713959939bdc4adca0eea2d4420eef4b/badge?X-DEVOPS-PROJECT-ID=qq-guild-open)](https://devops.woa.com/process/api-html/user/builds/projects/qq-guild-open/pipelines/p-713959939bdc4adca0eea2d4420eef4b/latestFinished?X-DEVOPS-PROJECT-ID=qq-guild-open) +_✨ 基于 [机器人开放平台API](https://bot.q.qq.com/wiki/develop/api/) 实现的机器人框架 ✨_ + +_✨ 为开发者提供一个易使用、开发效率高的开发框架 ✨_ + +[文档](https://bot.q.qq.com/wiki/develop/pythonsdk/) +· +[下载](https://github.com/tencent-connect/botpy/tags) +· +[安装](https://bot.q.qq.com/wiki/develop/pythonsdk/#sdk-安装) + +
+ ## 准备工作 ### 安装 @@ -43,12 +58,9 @@ import botpy ```python import botpy -from botpy.types.message import Message +from botpy.message import Message class MyClient(botpy.Client): - async def on_ready(self): - print(f"robot 「{self.robot.name}」 on_ready!") - async def on_at_message_create(self, message: Message): await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}") ``` @@ -61,7 +73,7 @@ class MyClient(botpy.Client): ```python import botpy -from botpy.types.message import Message +from botpy.message import Message class MyClient(botpy.Client): async def on_at_message_create(self, message: Message): @@ -89,7 +101,7 @@ intents.public_guild_messages=True ```python import botpy -from botpy.types.message import Message +from botpy.message import Message class MyClient(botpy.Client): async def on_at_message_create(self, message: Message): @@ -132,8 +144,6 @@ class MyClient(botpy.Client): ```python from botpy import logging - -logger = logging.get_logger() ``` 或者通过`botpy.logger`也可以获取logger对象 @@ -141,7 +151,10 @@ logger = logging.get_logger() 然后就可以愉快地使用 logger 进行打印。例如: ```python +from botpy import logger + logger.info("hello world!") + ``` ### 日志设置 @@ -159,7 +172,6 @@ botpy.Client( ext_handlers=False, log_config="log_config.json" ) - ``` ### log_level @@ -271,9 +283,11 @@ pytest ## 致谢 -感谢参与内测、开发和提出宝贵意见的开发者们(排名不分先后): +感谢感谢以下开发者对 `botpy` 作出的贡献: -[小念](https://github.com/ReadSmall), [Neutron](https://github.com/Huang1220), [晚柒载](https://github.com/wqzai) + + + # 加入官方社区 diff --git a/botpy/api.py b/botpy/api.py index 8b77f21..bad1cd2 100644 --- a/botpy/api.py +++ b/botpy/api.py @@ -268,7 +268,7 @@ async def get_voice_members(self, channel_id: str) -> List[user.Member]: # 子频道相关接口 async def get_channel(self, channel_id: str) -> channel.ChannelPayload: """ - 它获取频道信息。 + 获取频道信息 Args: channel_id (str): 子频道 ID。 diff --git a/botpy/ext/cog_apscheduler/__init__.py b/botpy/ext/cog_apscheduler/__init__.py new file mode 100644 index 0000000..150109f --- /dev/null +++ b/botpy/ext/cog_apscheduler/__init__.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +from botpy import logging + +from apscheduler.schedulers.asyncio import AsyncIOScheduler + +_log = logging.get_logger() + +scheduler = AsyncIOScheduler() +scheduler.configure({"apscheduler.timezone": "Asia/Shanghai"}) + +scheduler.start() +_log.debug("[加载插件] APScheduler 定时任务") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index f30b1d0..4efafea 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ pre-commit PyYAML -aiohttp>=3.7.4,<4 \ No newline at end of file +aiohttp>=3.7.4,<4 +APScheduler \ No newline at end of file diff --git a/setup.py b/setup.py index 8750746..0175b17 100644 --- a/setup.py +++ b/setup.py @@ -17,7 +17,7 @@ # 执照 license="Tencent", # 安装依赖 - install_requires=["aiohttp>=3.7.4,<4", "PyYAML"], + install_requires=["aiohttp>=3.7.4,<4", "PyYAML", "APScheduler"], # 分类 classifiers=[ # 发展时期,常见的如下 From 406944f7bba7b932d4e3529b9ac5ee3ffb281f22 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, 25 Jun 2022 10:52:02 +0800 Subject: [PATCH 15/19] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DMember=E6=9E=84?= =?UTF-8?q?=E5=BB=BA=E7=9A=84=E9=83=A8=E5=88=86=E5=AD=97=E6=AE=B5=E5=8F=96?= =?UTF-8?q?=E5=80=BC=E9=94=99=E8=AF=AF=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/user.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/botpy/user.py b/botpy/user.py index bf53311..47e9a8a 100644 --- a/botpy/user.py +++ b/botpy/user.py @@ -23,7 +23,7 @@ def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: user.GuildMemberPa class _User: def __init__(self, data): - self.id = data.get("user") + self.id = data.get("id") self.username = data.get("username") self.avatar = data.get("avatar") self.bot = data.get("bot") From 81d53f7f942c2bd58fdf9fa1a1e5b331df8e199d 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, 25 Jun 2022 11:24:32 +0800 Subject: [PATCH 16/19] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0botpy=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 119 ------------------------------------- README.rst | 158 -------------------------------------------------- botpy/user.py | 9 +-- 3 files changed, 1 insertion(+), 285 deletions(-) delete mode 100644 README.rst diff --git a/README.md b/README.md index 9270103..2eaa08f 100644 --- a/README.md +++ b/README.md @@ -134,125 +134,6 @@ class MyClient(botpy.Client): ├── demo_recall.py # 机器人消息撤回示例 ├── demo_schedule.py # 机器人日程相关示例 -## 日志打印 - -基于自带的 logging 模块封装的日志模块,提供了日志写入以及美化了打印格式,并支持调整打印级别(默认打印级别为 `INFO`)。 - -### 使用方法 - -引用模块,并获取 `logger` 实例: - -```python -from botpy import logging -``` - -或者通过`botpy.logger`也可以获取logger对象 - -然后就可以愉快地使用 logger 进行打印。例如: - -```python -from botpy import logger - -logger.info("hello world!") - -``` - -### 日志设置 - -SDK的日志设置集成在`bot.Client`的实例化阶段,也可通过[`logging.configure_logging`](botpy/logging.py)修改(均为可选) - -```python -import botpy - -# 示例,非默认值 -botpy.Client( - log_level=10, - log_format="new format", - bot_log=None, - ext_handlers=False, - log_config="log_config.json" -) -``` - -### log_level - -日志级别,默认为`INFO` - -命令行启动py可增加参数`-d` 或 `--debug`快捷打开debug日志 - -```bash -python3 demo_at_reply.py -d -``` - -几个可选取值(参考了[logging模块的取值](https://docs.python.org/3/library/logging.html#levels)): - -| Level | 取值 | -| -------- | --- | -| CRITICAL | 50 | -| ERROR | 40 | -| WARNING | 30 | -| INFO | 20 | -| DEBUG | 10 | -| NOTSET | 0 | - -### log_format - -日志控制台输出格式,默认为 `"\033[1;33m[%(levelname)s]\t(%(filename)s:%(lineno)s)%(funcName)s\t\033[0m%(message)s"` - -### bot_log - -是否启用`botpy`日志,默认为`True` - -`True` 启用 -`None` 禁用 拓展 -`False` 禁用 拓展+控制台输出 - -### ext_handlers - -日志Handler拓展,为`True`使用默认拓展,`False`不添加拓展,可用list添加多个拓展。默认为`True` - -[默认拓展](./botpy/logging.py) - -```python -import os -import logging -from logging.handlers import TimedRotatingFileHandler - -DEFAULT_FILE_HANDLER = { - # 要实例化的Handler - "handler": TimedRotatingFileHandler, - # 可选 Default to DEFAULT_FILE_FORMAT - "format": "%(asctime)s\t[%(levelname)s]\t(%(filename)s:%(lineno)s)%(funcName)s\t%(message)s", - # 可选 Default to DEBUG - "level": logging.DEBUG, - # 以下是Handler相关参数 - "when": "D", - "backupCount": 7, - "encoding": "utf-8", - # *特殊* 对于filename参数,其中如有 %(name)s 会在实例化阶段填入相应的日志name - "filename": os.path.join(os.getcwd(), "%(name)s.log"), -} -``` - -#### 修改默认拓展 - -```python -import os -import botpy -from botpy.logging import DEFAULT_FILE_HANDLER - -# 修改日志路径 -DEFAULT_FILE_HANDLER["filename"] = os.path.join(os.getcwd(), "log", "%(name)s.log") -# 修改日志格式 -DEFAULT_FILE_HANDLER["format"] = "new format" - -botpy.Client(ext_handlers=DEFAULT_FILE_HANDLER) -``` - -### log_config - -该参数将传入`logging.config.dictConfig`(内置logging而非botpy.logging),如果为.json/.yaml文件路径将从文件中读取配置,无默认值 - # 参与开发 ## 环境配置 diff --git a/README.rst b/README.rst deleted file mode 100644 index 9d27c18..0000000 --- a/README.rst +++ /dev/null @@ -1,158 +0,0 @@ -.. role:: raw-html-m2r(raw) - :format: html - - -botpy -===== - -**botpy** 是基于\ `机器人开放平台API `_ 实现的机器人框架,目的提供一个易使用、开发效率高的开发框架。 - - -.. image:: https://img.shields.io/pypi/v/qq-botpy - :target: https://img.shields.io/pypi/v/qq-botpy - :alt: PyPI - - -.. image:: https://api.bkdevops.qq.com/process/api/external/pipelines/projects/qq-guild-open/p-713959939bdc4adca0eea2d4420eef4b/badge?X-DEVOPS-PROJECT-ID=qq-guild-open - :target: https://devops.woa.com/process/api-html/user/builds/projects/qq-guild-open/pipelines/p-713959939bdc4adca0eea2d4420eef4b/latestFinished?X-DEVOPS-PROJECT-ID=qq-guild-open - :alt: BK Pipelines Status - - -准备工作 --------- - -安装 -^^^^ - -.. code-block:: bash - - pip install qq-botpy - -更新包的话需要添加 ``--upgrade`` ``注:需要python3.7+`` - -使用 -^^^^ - -需要使用的地方\ ``import botpy`` - -.. code-block:: python - - import botpy - -兼容提示 -^^^^^^^^ - -.. - - 原机器人的老版本\ ``qq-bot``\ 仍然可以使用,但新接口的支持上会逐渐暂停,此次升级不会影响线上使用的机器人 - - -使用方式 --------- - -快速入门 -^^^^^^^^ - -步骤1 -~~~~~ - -通过继承实现\ ``bot.Client``\ , 实现自己的机器人Client - -步骤2 -~~~~~ - -实现机器人相关事件的处理方法,如 ``on_at_message_create``\ , 详细的事件监听列表,请参考 `事件监听.md <./docs/事件监听.md>`_ - -如下,是定义机器人被@的后自动回复: - -.. code-block:: python - - import botpy - from botpy.types.message import Message - - class MyClient(botpy.Client): - async def on_ready(self): - print(f"robot 「{self.robot.name}」 on_ready!") - - async def on_at_message_create(self, message: Message): - await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}") - -``注意:每个事件会下发具体的数据对象,如`message`相关事件是`message.Message`的对象 (部分事件透传了后台数据,暂未实现对象缓存)`` - -步骤3 -~~~~~ - -设置机器人需要监听的事件通道,并启动\ ``client`` - -.. code-block:: python - - import botpy - from botpy.types.message import Message - - class MyClient(botpy.Client): - async def on_at_message_create(self, message: Message): - await self.api.post_message(channel_id=message.channel_id, content="content") - - intents = botpy.Intents(public_guild_messages=True) - client = MyClient(intents=intents) - client.run(appid="12345", token="xxxx") - -备注 -^^^^ - -也可以通过预设置的类型,设置需要监听的事件通道 - -.. code-block:: python - - import botpy - - intents = botpy.Intents.none() - intents.public_guild_messages=True - -使用API -^^^^^^^ - -如果要使用\ ``api``\ 方法,可以参考如下方式: - -.. code-block:: python - - import botpy - from botpy.types.message import Message - - class MyClient(botpy.Client): - async def on_at_message_create(self, message: Message): - await self.api.post_message(channel_id=message.channel_id, content="content") - -示例机器人 ----------- - -`\ ``examples`` <./examples/>`_ 目录下存放示例机器人,具体使用可参考\ `\ ``Readme.md`` <./examples/README.md>`_ - -.. code-block:: - - examples/ - . - ├── README.md - ├── config.example.yaml # 示例配置文件(需要修改为config.yaml) - ├── demo_announce.py # 机器人公告API使用示例 - ├── demo_api_permission.py # 机器人授权查询API使用示例 - ├── demo_at_reply.py # 机器人at被动回复async示例 - ├── demo_at_reply_ark.py # 机器人at被动回复ark消息示例 - ├── demo_at_reply_embed.py # 机器人at被动回复embed消息示例 - ├── demo_at_reply_command.py # 机器人at被动使用Command指令装饰器回复消息示例 - ├── demo_at_reply_file_data.py # 机器人at被动回复本地图片消息示例 - ├── demo_at_reply_keyboard.py # 机器人at被动回复md带内嵌键盘的示例 - ├── demo_at_reply_markdown.py # 机器人at被动回复md消息示例 - ├── demo_at_reply_reference.py # 机器人at被动回复消息引用示例 - ├── demo_dms_reply.py # 机器人私信被动回复示例 - ├── demo_get_reaction_users.py # 机器人获取表情表态成员列表示例 - ├── demo_guild_member_event.py # 机器人频道成员变化事件示例 - ├── demo_interaction.py # 机器人互动事件示例(未启用) - ├── demo_pins_message.py # 机器人消息置顶示例 - ├── demo_recall.py # 机器人消息撤回示例 - ├── demo_schedule.py # 机器人日程相关示例 - -更多功能 --------- -更多功能请参考: [https://github.com/tencent-connect/botpy] - diff --git a/botpy/user.py b/botpy/user.py index 47e9a8a..9fe6ade 100644 --- a/botpy/user.py +++ b/botpy/user.py @@ -3,14 +3,7 @@ class Member: - __slots__ = ( - "_api", - "_ctx", - "user", - "nick", - "roles", - "joined_at", - "event_id") + __slots__ = ("_api", "_ctx", "user", "nick", "roles", "joined_at", "event_id") def __init__(self, api: BotAPI, ctx: gateway.WsContext, data: user.GuildMemberPayload): self._api = api From ecf69885f3edd7458020040f337f6256db681457 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, 25 Jun 2022 13:13:27 +0800 Subject: [PATCH 17/19] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E9=A2=91=E9=81=93=E6=88=90=E5=91=98API=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E6=8B=89=E9=BB=91=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/api.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/botpy/api.py b/botpy/api.py index bad1cd2..ab5a697 100644 --- a/botpy/api.py +++ b/botpy/api.py @@ -216,14 +216,14 @@ async def get_delete_member( # 注:消息撤回时间范围仅支持固定的天数:3,7,15,30。 特殊的时间范围:-1: 撤回全部消息。默认值为0不撤回任何消息。 if delete_history_msg_days not in (3, 7, 15, 30, 0, -1): delete_history_msg_days = 0 - params = {'add_blacklist': str(add_blacklist).lower(), 'delete_history_msg_days': delete_history_msg_days} + payload = {"add_blacklist": add_blacklist, "delete_history_msg_days": delete_history_msg_days} route = Route( "DELETE", "/guilds/{guild_id}/members/{user_id}", guild_id=guild_id, user_id=user_id, ) - return await self._http.request(route, params=params) + return await self._http.request(route, json=payload) async def get_guild_members(self, guild_id: str, after: str = "0", limit: int = 1) -> List[user.Member]: """ From de80c3561f650a4ba29c201002865e324ad29827 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, 25 Jun 2022 22:00:23 +0800 Subject: [PATCH 18/19] =?UTF-8?q?fix:=20rst=E6=96=87=E4=BB=B6=E5=9B=9E?= =?UTF-8?q?=E6=BB=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.rst | 158 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 README.rst diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..976cd7d --- /dev/null +++ b/README.rst @@ -0,0 +1,158 @@ +.. role:: raw-html-m2r(raw) + :format: html + + +botpy +===== + +**botpy** 是基于\ `机器人开放平台API `_ 实现的机器人框架,目的提供一个易使用、开发效率高的开发框架。 + + +.. image:: https://img.shields.io/pypi/v/qq-botpy + :target: https://img.shields.io/pypi/v/qq-botpy + :alt: PyPI + + +.. image:: https://api.bkdevops.qq.com/process/api/external/pipelines/projects/qq-guild-open/p-713959939bdc4adca0eea2d4420eef4b/badge?X-DEVOPS-PROJECT-ID=qq-guild-open + :target: https://devops.woa.com/process/api-html/user/builds/projects/qq-guild-open/pipelines/p-713959939bdc4adca0eea2d4420eef4b/latestFinished?X-DEVOPS-PROJECT-ID=qq-guild-open + :alt: BK Pipelines Status + + +准备工作 +-------- + +安装 +^^^^ + +.. code-block:: bash + + pip install qq-botpy + +更新包的话需要添加 ``--upgrade`` ``注:需要python3.7+`` + +使用 +^^^^ + +需要使用的地方\ ``import botpy`` + +.. code-block:: python + + import botpy + +兼容提示 +^^^^^^^^ + +.. + + 原机器人的老版本\ ``qq-bot``\ 仍然可以使用,但新接口的支持上会逐渐暂停,此次升级不会影响线上使用的机器人 + + +使用方式 +-------- + +快速入门 +^^^^^^^^ + +步骤1 +~~~~~ + +通过继承实现\ ``bot.Client``\ , 实现自己的机器人Client + +步骤2 +~~~~~ + +实现机器人相关事件的处理方法,如 ``on_at_message_create``\ , 详细的事件监听列表,请参考 `事件监听.md <./docs/事件监听.md>`_ + +如下,是定义机器人被@的后自动回复: + +.. code-block:: python + + import botpy + from botpy.types.message import Message + + class MyClient(botpy.Client): + async def on_ready(self): + print(f"robot 「{self.robot.name}」 on_ready!") + + async def on_at_message_create(self, message: Message): + await message.reply(content=f"机器人{self.robot.name}收到你的@消息了: {message.content}") + +``注意:每个事件会下发具体的数据对象,如`message`相关事件是`message.Message`的对象 (部分事件透传了后台数据,暂未实现对象缓存)`` + +步骤3 +~~~~~ + +设置机器人需要监听的事件通道,并启动\ ``client`` + +.. code-block:: python + + import botpy + from botpy.types.message import Message + + class MyClient(botpy.Client): + async def on_at_message_create(self, message: Message): + await self.api.post_message(channel_id=message.channel_id, content="content") + + intents = botpy.Intents(public_guild_messages=True) + client = MyClient(intents=intents) + client.run(appid="12345", token="xxxx") + +备注 +^^^^ + +也可以通过预设置的类型,设置需要监听的事件通道 + +.. code-block:: python + + import botpy + + intents = botpy.Intents.none() + intents.public_guild_messages=True + +使用API +^^^^^^^ + +如果要使用\ ``api``\ 方法,可以参考如下方式: + +.. code-block:: python + + import botpy + from botpy.types.message import Message + + class MyClient(botpy.Client): + async def on_at_message_create(self, message: Message): + await self.api.post_message(channel_id=message.channel_id, content="content") + +示例机器人 +---------- + +`\ ``examples`` <./examples/>`_ 目录下存放示例机器人,具体使用可参考\ `\ ``Readme.md`` <./examples/README.md>`_ + +.. code-block:: + + examples/ + . + ├── README.md + ├── config.example.yaml # 示例配置文件(需要修改为config.yaml) + ├── demo_announce.py # 机器人公告API使用示例 + ├── demo_api_permission.py # 机器人授权查询API使用示例 + ├── demo_at_reply.py # 机器人at被动回复async示例 + ├── demo_at_reply_ark.py # 机器人at被动回复ark消息示例 + ├── demo_at_reply_embed.py # 机器人at被动回复embed消息示例 + ├── demo_at_reply_command.py # 机器人at被动使用Command指令装饰器回复消息示例 + ├── demo_at_reply_file_data.py # 机器人at被动回复本地图片消息示例 + ├── demo_at_reply_keyboard.py # 机器人at被动回复md带内嵌键盘的示例 + ├── demo_at_reply_markdown.py # 机器人at被动回复md消息示例 + ├── demo_at_reply_reference.py # 机器人at被动回复消息引用示例 + ├── demo_dms_reply.py # 机器人私信被动回复示例 + ├── demo_get_reaction_users.py # 机器人获取表情表态成员列表示例 + ├── demo_guild_member_event.py # 机器人频道成员变化事件示例 + ├── demo_interaction.py # 机器人互动事件示例(未启用) + ├── demo_pins_message.py # 机器人消息置顶示例 + ├── demo_recall.py # 机器人消息撤回示例 + ├── demo_schedule.py # 机器人日程相关示例 + +更多功能 +-------- +更多功能请参考: [https://github.com/tencent-connect/botpy] + From dc10a76b2d4679b7395c4fe2bfd91333959bf582 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: Mon, 27 Jun 2022 12:21:35 +0800 Subject: [PATCH 19/19] =?UTF-8?q?feat:=20=E4=B8=BAhttp=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E6=88=90=E5=8A=9F=E6=B7=BB=E5=8A=A0trace=5Fid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- botpy/http.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/botpy/http.py b/botpy/http.py index ec22d30..e60b81b 100644 --- a/botpy/http.py +++ b/botpy/http.py @@ -28,7 +28,7 @@ async def _handle_response(url, response: ClientResponse) -> Union[Dict[str, Any except (KeyError, JSONDecodeError): data = None if response.status in HTTP_OK_STATUS: - _log.debug(f"[botpy] 请求成功, 请求连接: {url}, 返回内容: {data}") + _log.debug(f"[botpy] 请求成功, 请求连接: {url}, 返回内容: {data}, trace_id:{response.headers.get(X_TPS_TRACE_ID)}") return data else: _log.error(