Slack下一代平台如何监听用户与应用的IM聊天消息?
在Slack下一代平台中监听用户与应用的一对一聊天消息
我正在使用Slack下一代平台开发机器人,需要接收用户与应用聊天的消息并转发到指定频道,但每个用户对应的一对一聊天(IM)频道ID都不同,无法在事件触发器中指定固定的channel_ids。想知道如何在Slack下一代平台中实现类似Bolt里监听所有消息并判断channel_type为im的功能?
原触发器代码中需要指定Channel ID,但IM频道无法预先确定:
const triggerResponse = await client.workflows.triggers.create< typeof SendMessageWorkflow.definition >({ type: TriggerTypes.Event, name: "Event On bot app chat", description: "responds to user when they chat with bot", workflow: `#/workflows/${SendMessageWorkflow.definition.callback_id}`, event: { event_type: TriggerEventTypes.MessagePosted, channel_ids: ["Your channel ID"], // 无法为用户与应用的聊天频道分配固定ID filter: { version: 1, root: { statement: "{{data.text}} CONTAINS help", }, }, }, inputs: { channel: { value: channel, }, message: { value: TriggerContextData.Event.MessagePosted.text, }, user: { value: TriggerContextData.Event.MessagePosted.user_id, }, }, });
在Bolt中可以通过监听所有消息并判断channel_type实现:
app.message( async ({ message, say, event, client, context, logger }) => { if ( event.channel_type === "im" ) { try { // 执行任务逻辑 } catch (error) { await say(`Bot is not working, Please!`); } } });
解决方法:使用事件过滤器匹配频道类型
在Slack下一代平台中,你不需要指定固定的channel_ids,而是可以通过事件过滤器直接筛选出channel_type为im的消息(即用户与应用的一对一聊天)。修改触发器的配置如下:
const triggerResponse = await client.workflows.triggers.create< typeof SendMessageWorkflow.definition >({ type: TriggerTypes.Event, name: "Event On bot app chat", description: "responds to user when they chat with bot", workflow: `#/workflows/${SendMessageWorkflow.definition.callback_id}`, event: { event_type: TriggerEventTypes.MessagePosted, // 移除固定channel_ids配置 filter: { version: 1, root: { // 同时匹配channel_type为im,且文本包含help statement: "{{data.channel_type}} == 'im' AND {{data.text}} CONTAINS 'help'", }, }, }, inputs: { // 动态获取触发事件的频道ID channel: { value: "{{data.channel_id}}", }, message: { value: "{{data.text}}", }, user: { value: "{{data.user_id}}", }, }, });
关键说明:
- 移除
channel_ids:不需要预先指定任何频道ID,让触发器监听所有message_posted事件。 - 过滤器逻辑:通过
{{data.channel_type}} == 'im'筛选出用户与应用的一对一聊天消息,再结合原有的文本包含help的条件,用AND连接实现多条件匹配。 - 动态输入参数:将
channel的输入值改为{{data.channel_id}},这样就能获取到当前触发事件的IM频道ID,用于后续的消息转发等操作。
这种方式和Bolt中判断channel_type的逻辑等价,都是通过筛选频道类型来捕获目标消息,且不需要提前知道所有用户的IM频道ID。
内容的提问来源于stack exchange,提问作者F.Abdullah
相关产品推荐
相关产品推荐

