You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python slack_sdk从Slack的reaction_added事件获取消息event_id?

解决Slack机器人消息反应记录中获取消息event_id的方案

核心思路

机器人发送消息时主动存储每条消息的ts(时间戳)与event_id的映射关系——Slack的ts是消息的唯一标识,reaction_added事件的payload里能拿到被反应消息的ts和所在频道channel,用这两个字段即可关联到预先存储的event_id。

具体实现步骤

  1. 发送消息时记录映射
    调用chat.postMessage(或同类发送接口)后,响应结果的message对象里包含该消息的ts和event_id。用字典、数据库(如Redis、SQLite)存储(channel, ts)到event_id的键值对即可。
    示例代码:

    from slack_sdk import WebClient
    from slack_sdk.errors import SlackApiError
    
    client = WebClient(token="YOUR_BOT_TOKEN")
    # 生产环境建议用持久化存储替代内存字典
    message_map = {}
    
    def send_bot_message(channel, text):
        try:
            response = client.chat_postMessage(channel=channel, text=text)
            msg_data = response["message"]
            # 存储频道、时间戳与event_id的映射
            message_map[(channel, msg_data["ts"])] = msg_data["event_id"]
            return response
        except SlackApiError as e:
            print(f"消息发送失败: {e.response['error']}")
    
  2. 处理reaction_added事件时关联event_id
    从reaction_added事件的item字段中提取channel和ts,用这两个值查询存储的映射表,就能拿到对应的event_id,同时可获取反应用户user和表情reaction。
    示例代码:

    def handle_reaction_added(event):
        item = event["item"]
        channel = item["channel"]
        msg_ts = item["ts"]
        reacting_user = event["user"]
        reaction = event["reaction"]
    
        # 查询映射表获取event_id
        key = (channel, msg_ts)
        if key in message_map:
            event_id = message_map[key]
            # 记录所需信息
            print(f"用户 {reacting_user} 对消息(event_id: {event_id})添加了表情 {reaction}")
        else:
            # 处理未找到的情况(如消息已删除、机器人重启丢失存储)
            print(f"未找到对应消息的event_id,频道:{channel},消息ts:{msg_ts}")
    
  3. 持久化存储建议
    若机器人可能重启,内存字典会丢失数据,推荐用Redis(适合键值对存储,可设置过期时间匹配消息保留时长)或SQLite(适合小型应用)来持久化映射关系。

补充说明

  • Slack官方认可ts作为消息的唯一关联标识,比event_id更稳定可靠;若需要消息具体内容,也可通过channels.history(对应频道类型的接口)用channel和ts拉取详情,无需依赖event_id。

内容的提问来源于stack exchange,提问作者Eric Pereira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:25:21