如何使用slack_bolt在Slack App中发送带单选按钮的跟进消息?
问题:为Slack机器人添加带单选按钮的跟进提问
我正在构建一个Slack App机器人,用于回答用户提出的问题。希望配置一个带单选按钮(Yes/No)的跟进问题,示例如下:
User: What is the event date?
Bot: 22nd Feb, 2023
(回答后机器人触发带单选按钮的跟进问题)
Bot: Does this answer your query?
- Yes
- No
我的代码如下:
import asyncio from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler from slack_bolt.async_app import AsyncApp from slack_sdk import WebClient client = WebClient(token=SLACK_BOT_TOKEN) app = AsyncApp(token=SLACK_BOT_TOKEN) # This event will be executed when User sends the message @app.message('') async def in_message(say, message): if 'event' in message['text']: response = '22nd Feb, 2023' block = [] await say(text=response, blocks=block)
我尝试在响应中追加跟进消息并通过ACK更新,但更新无法处理格式,消息会被当作纯文本。
解决方案
Slack的交互式元素(如单选按钮)必须通过Blocks结构定义,不能用纯文本格式实现。以下是修改后的代码,实现先发送回答,再发送带单选按钮的跟进提问,并处理用户的选择:
import asyncio from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler from slack_bolt.async_app import AsyncApp from slack_sdk import WebClient # 替换为你的实际令牌 SLACK_BOT_TOKEN = "your-bot-token" SLACK_APP_TOKEN = "your-app-token" client = WebClient(token=SLACK_BOT_TOKEN) app = AsyncApp(token=SLACK_BOT_TOKEN) # 处理用户消息,返回事件日期并发送跟进提问 @app.message('') async def in_message(say, message): if 'event' in message['text'].lower(): # 先发送事件日期回答 await say(text='22nd Feb, 2023') # 构建包含单选按钮的Blocks结构 follow_up_blocks = [ { "type": "section", "text": { "type": "mrkdwn", "text": "*Does this answer your query?*" } }, { "type": "actions", "elements": [ { "type": "radio_buttons", "options": [ { "text": {"type": "plain_text", "text": "Yes"}, "value": "feedback_yes" }, { "text": {"type": "plain_text", "text": "No"}, "value": "feedback_no" } ], "action_id": "feedback_radio_btn" } ] } ] # 发送带单选按钮的跟进提问 await say(blocks=follow_up_blocks, text="Does this answer your query?") # 处理用户点击单选按钮的反馈 @app.action("feedback_radio_btn") async def handle_feedback(ack, body, say): await ack() # 必须确认Slack的请求 selected_option = body["actions"][0]["selected_option"]["value"] if selected_option == "feedback_yes": await say("Great to hear that! 😊") else: await say("Sorry that didn't help. Could you tell me what more you need to know?") async def main(): handler = AsyncSocketModeHandler(app, SLACK_APP_TOKEN) await handler.start() if __name__ == "__main__": asyncio.run(main())
关键说明
- Blocks结构:用
section块展示提问文本,actions块包含radio_buttons交互式元素,每个选项对应唯一的value和统一的action_id,用于后续识别用户选择。 - 分消息发送:先发送纯文本回答,再发送带Blocks的跟进提问,避免内容混杂。
- Action处理:添加
@app.action装饰器监听单选按钮的点击事件,必须先调用ack()确认请求,再根据用户选择返回对应回复。 - 令牌替换:记得将代码中的
SLACK_BOT_TOKEN和SLACK_APP_TOKEN替换为你自己的Slack令牌。
内容的提问来源于stack exchange,提问作者Sociopath
相关产品推荐
相关产品推荐

