Search code examples
botsslackslack-apibolts-framework

How to get a thread reply's content from reaction_added event?


I'm building a slack FAQ app that uses message reactions to gather the best answers to questions. My plan is to save any Slack messages with positive reactions by using the reaction_added event to get the TS attribute and then the conversations.history method to get the message's content.

This works well for parent-level or non-threaded messages, however it doesn't work for reply messages inside threads. For some reason the conversations.history method returns an unrelated message when using the TS of a thread reply.

I've checked the Slack API conversations.history method documentation to see if replies are handled in any special way. I reviewed conversations.replies method to see if it might be helpful, but since reaction_added event simply provides a TS id for the message and no thread_ts value that can be used with the conversations.replies method.

I'm using bolt framework. Here's a snippet of the code that tries to use the reaction_added event with conversations.history method to get the message content:

app.event('reaction_added', async ({ event, context, say }) => {
  try {
    const result = await app.client.conversations.history({
      token: process.env.SLACK_USER_TOKEN,
      channel: event.item.channel,
      latest: event.item.ts,
      limit: 1,
      inclusive: true
    });
    save(`${result.messages[0].text}`);
  }
  catch (error) {
    console.error(error);
  }
});

Expected result: Message contents of thread reply that a reaction is posted for

Actual result: Message contents of the latest message in the slack channel


Solution

  • I'm not sure if it changed recently or I misread the documentation, but conversations.replies API endpoint does not require a thread_ts value containing the parent thread timestamp in order to retrieve a thread reply.

    The event.item.ts value provided by the reaction_added event is sufficient to retrieve the message contents of the reply where a reaction was added.

    So to get the message contents of a message where a reaction was added, you can update the code in my original question to:

    app.event('reaction_added', async ({ event, context, say }) => {
      try {
        const result = await app.client.conversations.replies({
          token: process.env.SLACK_USER_TOKEN,
          channel: event.item.channel,
          ts: event.item.ts
        });
        save(`${result.messages[0].text}`);
      }
      catch (error) {
        console.error(error);
      }
    });