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

Slack API:如何通过临时消息按钮更新用户消息

解决Slack临时消息按钮点击后更新原用户消息的问题

问题核心在于:当点击临时消息(ephemeral message)中的按钮时,body.container.message_ts获取到的是临时消息的时间戳,而非触发该临时消息的原用户消息的时间戳。要解决这个问题,我们需要在发送临时消息时,将原消息的时间戳存入按钮的自定义字段中,点击按钮时再读取这个字段来更新原消息。

以下是修改后的完整代码,关键变更已标注:

const { WebClient } = require("@slack/web-api");
const slack_bot_token = process.env.SLACK_BOT_TOKEN;
const signing_secret = process.env.SLACK_SIGNING_SECRET;
const webClient = new WebClient(process.env.SLACK_BOT_TOKEN);

const { App } = require("@slack/bolt");
const app = new App({
  token: slack_bot_token,
  signingSecret: signing_secret,
});


app.message("hi", async ({ message, channel, say }) => {
  // Respond to action with an ephemeral message
  let channelID = message.channel;
  let userID = message.user;
  let originalMsgTs = message.timestamp; // 保存原消息的时间戳
  await webClient.chat.postEphemeral({
    channel: channelID,
    user: userID,
    text: `👋 Hi <@${message.user}>`,
    blocks: [
      {
        type: "section",
        text: {
          type: "mrkdwn",
          text: `👋 Hey <@${message.user}>`,
        },
        accessory: {
          type: "button",
          text: {
            type: "plain_text",
            text: "Click me",
            emoji: true,
          },
          action_id: "click",
          value: originalMsgTs // 将原消息时间戳存入按钮的value字段
        },
      },
    ],
  });
});

// 点击按钮后删除临时消息并更新原用户消息
app.action("click", async ({ ack, body, client, respond }) => {
  // 先确认动作请求
  await ack();
  
  // 删除原临时消息
  respond({
    response_type: "ephemeral",
    text: "",
    delete_original: true,
  });
  
  // 从按钮的value中获取原消息的时间戳
  const originalMsgTs = body.actions[0].value;
  
  // 更新原用户消息为"goodbye"
  await client.chat.update({
    channel: body.channel.id,
    ts: originalMsgTs,
    text: "goodbye"
  });
});

(async () => {
  // 启动应用
  await app.start(process.env.PORT || 3000);
  console.log("⚡️ Bolt app is running!!");
})();

关键修改点:

  1. 存储原消息时间戳:在发送临时消息时,将原用户消息的timestamp赋值给按钮的value属性,这样点击事件就能携带这个关键信息。
  2. 读取正确的时间戳:在按钮点击事件中,通过body.actions[0].value获取原消息的时间戳,替代原本错误的body.container.message_ts。
  3. 修正chat.update参数:移除了无效的replace_original和delete_original参数(这两个参数仅适用于动作响应,而非消息更新接口)。

内容的提问来源于stack exchange,提问作者Julien.h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:20:53