Search code examples
node.jsslack-api

slack get message sender name for messages return from conversation.history api


I am calling slack API(conversations.history) to get channel messages. I want to retrieve sender name in message response. how can i get it?

below is my message response:

{  "client_msg_id": "0e19ca7d-1072-4f73-a932-9ec7fa9956de",
          "type": "message",
          "text": "Yeah good edge case, I would agree, just mentioning \" no data found\"",
          "user": "U01JW9D10PQ",
          "ts": "1642216920.001100",
          "team": "T01K38V9Q7M", blocks:[]}

Solution

  • The conversations.history API doesn't return user information (just user id), you may need to fetch each user from the channel history, see an example code:

    Get Slack channel history users                                                                                 Run in Fusebit
    const channelId = 'C02TSNCQ2Q2';
    const channelHistory = await client.conversations.history({
      channel: channelId,
    });
    
    // Get the user ids from the history and populate an array with the user details
    const userList = [];
    for await (let message of channelHistory.messages) {
      const userAdded = userList.find(user => user.id === message.user);
      if (!userAdded) {
        const response = await slackClient.users.info({
          user: message.user,
        });
    
        if (response.ok) {
          const { id, name, real_name, profile, is_bot } = response.user;
          userList.push({ id, name, real_name, profile, is_bot });
        }
      }
    }
    
    console.log(`There are ${userList.length} users in the channel conversation:\n${userList.map(user => `${(user.is_bot ? '🤖' : '👤')} ${user.name}`).join('\n')}`);