author avatar

amber.srivastava

Thu Nov 07 2024

SEND SLACK MESSAGE AS A THREAD

To send a message as a thread in Slack using the Slack API, we can use the chat.postMessage method with the thread_ts parameter. This parameter specifies the timestamp (ts) of the parent message you want to reply to, creating a thread.

Here’s how to send a threaded message:
1. Get the ts (timestamp) of the Parent Message
• If you’re replying to a specific message, you’ll need its ts value. You can retrieve it by fetching messages in the channel, or from the response of a previously sent message.
2. Send a Threaded Message Using thread_ts
• Use thread_ts in the chat.postMessage payload to post your message as a reply in the thread.
Example:-


import { WebClient } from "@slack/web-api";

const client = new WebClient("YOUR_SLACK_BOT_TOKEN");

async function sendThreadedMessage(channel: string, parent_ts: string, message: string) {
  try {
    // Post a new message as a reply in the thread
    const response = await client.chat.postMessage({
      channel,
      text: message,
      thread_ts: parent_ts, // This makes it a threaded message
    });
  } catch (error) {
    console.error("Error sending threaded message:", error);
  }
}

// Usage example
sendThreadedMessage("C123456789", "1688852910.123456", "This is a reply in the thread.");


If we don't have any parent message then,we can first send a message and then use its ts as the thread_ts for replies:


async function sendMessageWithThread(channel: string, message: string, replyMessage: string) {
  try {
    // Send the parent message
    const parentMessage = await client.chat.postMessage({
      channel,
      text: message,
    });

    // Reply to the message in a thread
    await client.chat.postMessage({
      channel,
      text: replyMessage,
      thread_ts: parentMessage.ts,
    });
  } catch (error) {
    console.error("Error sending messages:", error);
  }
}

// Usage example
sendMessageWithThread("C123456789", "This is the main message", "This is a reply in the thread.");


#C04A9DMK81E #slack #slackapi #thread