Skip to content

Commit

Permalink
feat: 增加消息按钮组件 (#69)
Browse files Browse the repository at this point in the history
* feat: 增加消息按钮组件

* feat: 增加消息按钮组件

* feat: 增加消息按钮组件

* feat: 增加消息按钮组件
  • Loading branch information
DaiJiChen committed May 19, 2022
1 parent f7ff686 commit 3dce1a7
Show file tree
Hide file tree
Showing 5 changed files with 165 additions and 0 deletions.
74 changes: 74 additions & 0 deletions examples/demo_at_reply_keyboard_buttons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
import os.path

import qqbot
from qqbot.core.util.yaml_util import YamlUtil
from qqbot.model.inline_keyboard import RenderData, Action, Permission, Button, InlineKeyboardRow, InlineKeyboard
from qqbot.model.message import MessageMarkdown, MessageKeyboard
from qqbot.model.ws_context import WsContext

test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml"))


async def _message_handler(context: WsContext, message: qqbot.Message):
"""
发送带消息按钮的 markdown 消息。(消息按钮只能和 markdown 一起使用)
:param context: WsContext 对象,包含 event_type 和 event_id
:param message: 事件对象(如监听消息是Message对象)
"""
await send_template_keyboard(message.channel_id, message.id)
await send_self_defined_keyboard(message.channel_id, message.id)


async def send_template_keyboard(channel_id, msg_id):
msg_api = qqbot.AsyncMessageAPI(t_token, False)

markdown = MessageMarkdown(content="# 123 \n 今天是个好天气")
keyword: MessageKeyboard = MessageKeyboard(id='62')
send = qqbot.MessageSendRequest(markdown=markdown, msg_id=msg_id, keyboard=keyword)
# 通过api发送回复消息
await msg_api.post_message(channel_id, send)


async def send_self_defined_keyboard(channel_id, msg_id):
msg_api = qqbot.AsyncMessageAPI(t_token, False)

markdown = MessageMarkdown(content="# 标题 \n## 简介 \n内容")
keyboard: MessageKeyboard = build_a_demo_keyboard()
send = qqbot.MessageSendRequest(markdown=markdown, msg_id=msg_id, keyboard=keyboard)
# 通过api发送回复消息
await msg_api.post_message(channel_id, send)


def build_a_demo_keyboard() -> MessageKeyboard:
"""
创建一个只有一行且该行只有一个 button 的键盘
"""
button1 = Button(
'1',
RenderData(
"button",
"BUTTON",
0
),
Action(
2,
Permission(2, specify_role_ids=["1"]),
10,
"/搜索",
True
)
)
row1 = InlineKeyboardRow([button1])
inline_keyboard = InlineKeyboard([row1])
return MessageKeyboard(content=inline_keyboard)


if __name__ == "__main__":
# async的异步接口的使用示例
t_token = qqbot.Token(test_config["token"]["appid"], test_config["token"]["token"])
qqbot_handler = qqbot.Handler(qqbot.HandlerType.AT_MESSAGE_EVENT_HANDLER, _message_handler)
qqbot.async_listen_events(t_token, False, qqbot_handler)
15 changes: 15 additions & 0 deletions qqbot/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
DirectMessageGuild,
MessagesPager,
MessageGet,
MessageKeyboard,
)
from qqbot.model.mute import MuteOption, MultiMuteOption, UserIds
from qqbot.model.pins_message import PinsMessage
Expand All @@ -64,6 +65,7 @@
ReactionUsersPager,
)


def listen_events(t_token: Token, is_sandbox: bool, *handlers: Handler):
"""
注册并监听频道相关事件
Expand Down Expand Up @@ -446,6 +448,19 @@ def recall_message(self, channel_id: str, message_id: str, hide_tip: bool = Fals
response = self.http.delete(url, params={"hidetip": str(hide_tip)})
return response.status_code == HttpStatus.OK

def post_keyboard_message(self, channel_id: str, keyboard: MessageKeyboard) -> Message:
"""
发送含有消息按钮组件的消息
:param channel_id: 子频道ID
:param keyboard: MessageKeyboard对象
:return: Message对象
"""
url = get_url(APIConstant.messagesURI, self.is_sandbox).format(channel_id=channel_id)
request_json = JsonUtil.obj2json_serialize(keyboard)
response = self.http.post(url, request_json)
return json.loads(response.content, object_hook=Message)


class DmsAPI(APIBase):
"""私信消息"""
Expand Down
14 changes: 14 additions & 0 deletions qqbot/async_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
DirectMessageGuild,
MessagesPager,
MessageGet,
MessageKeyboard,
)
from qqbot.model.mute import (
MuteOption,
Expand Down Expand Up @@ -463,6 +464,19 @@ async def recall_message(self, channel_id: str, message_id: str, hide_tip: bool
response = await self.http_async.delete(url, params={"hidetip": str(hide_tip)})
return response == ""

async def post_keyboard_message(self, channel_id: str, keyboard: MessageKeyboard) -> Message:
"""
发送含有消息按钮组件的消息
:param channel_id: 子频道ID
:param keyboard: MessageKeyboard对象
:return: Message对象
"""
url = get_url(APIConstant.messagesURI, self.is_sandbox).format(channel_id=channel_id)
request_json = JsonUtil.obj2json_serialize(keyboard)
response = await self.http_async.post(url, request_json)
return json.loads(response, object_hook=Message)


class AsyncDmsAPI(AsyncAPIBase):
"""私信消息"""
Expand Down
46 changes: 46 additions & 0 deletions qqbot/model/inline_keyboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import List


class Permission:
def __init__(self, type: int, specify_role_ids: List[str] = None, specify_user_ids: List[str] = None):
if type:
self.type = type
if specify_role_ids:
self.specify_role_ids = specify_role_ids
if specify_user_ids:
self.specify_user_ids = specify_user_ids


class RenderData:
def __init__(self, label: str, visited_label: str, style: int):
self.label = label
self.visited_label = visited_label
self.style = style


class Action:
def __init__(self, type: int, permission: Permission, click_limit: int, data: str, at_bot_show_channel_list: bool):
self.type = type
self.permission = permission
self.click_limit = click_limit
self.data = data
self.at_bot_show_channel_list = at_bot_show_channel_list


class Button:
def __init__(self, id: str, render_data: RenderData, action: Action):
self.id = id
self.render_data = render_data
self.action = action


class InlineKeyboardRow:
def __init__(self, buttons: List[Button]):
self.buttons = buttons


class InlineKeyboard:
def __init__(self, rows: List[InlineKeyboardRow]):
self.rows = rows


16 changes: 16 additions & 0 deletions qqbot/model/message.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from typing import List

from qqbot.model.inline_keyboard import InlineKeyboard
from qqbot.model.member import User, Member


Expand Down Expand Up @@ -160,6 +161,17 @@ def __init__(self, data=None, message_id: str = "", ignore_get_message_error: bo
self.__dict__ = data


class MessageKeyboard:
"""
id 和 content 两个参数互斥,都传值将返回错误
"""
def __init__(self, id: str = None, content: InlineKeyboard = None):
if id:
self.id = id
if content:
self.content = content


class MessageSendRequest:
def __init__(
self,
Expand All @@ -170,6 +182,7 @@ def __init__(
image: str = "",
message_reference: MessageReference = None,
markdown: MessageMarkdown = None,
keyboard: MessageKeyboard = None
):
"""
机器人发送消息时所传的数据对象
Expand All @@ -180,6 +193,8 @@ def __init__(
:param ark: ark 消息
:param image: 图片url地址
:param message_reference: 引用消息
:param markdown: markdown 消息
:param keyboard: markdown 消息内的按钮
"""

self.content = content
Expand All @@ -189,6 +204,7 @@ def __init__(
self.msg_id = msg_id
self.message_reference = message_reference
self.markdown = markdown
self.keyboard = keyboard


class DirectMessageGuild:
Expand Down

0 comments on commit 3dce1a7

Please sign in to comment.