0

List Slack channels, last message date, and whether it contains external members

by
Published Mar 21, 2024

This script interacts with the Slack API to retrieve information about all channels within a Slack workspace, including the date of the last message and whether each channel contains external members (based on email domain).

Script slack Verified

The script

Submitted by hugo989 Bun
Verified 20 days ago
1
import { WebClient as SlackWebClient } from "@slack/web-api";
2

3
type Slack = {
4
  token: string
5

6
}
7

8
// Needed scopes are: users:read ; users:read.email ; channels:read ; channels:history
9

10
export async function main(slackResource: Slack, companyDomain: string) {
11
  
12
  // Initialize the Slack WebClient with the provided token
13
  const slackClient = new SlackWebClient(slackResource.token);
14

15
  try {
16
    // Call the conversations.list method to get all channels
17
    const listResult = await slackClient.conversations.list();
18

19
    // Check if the listResult was successful and channels are present
20
    if (listResult.ok && listResult.channels) {
21
      // Initialize an array to hold the channels with their last message date and external member status
22
      const channelsInfo = [];
23

24
      // Iterate over each channel to fetch the last message's date, check for external members
25
      for (const channel of listResult.channels) {
26
        // Initialize external as false
27
        let external = false;
28

29
        // Call the conversations.members method to get all members of the channel
30
        const membersResult = await slackClient.conversations.members({
31
          channel: channel.id,
32
        });
33

34
        // Check if the membersResult was successful and members are present
35
        if (membersResult.ok && membersResult.members) {
36
          // Iterate over each member to fetch their user info
37
          for (const memberId of membersResult.members) {
38
            const userInfo = await slackClient.users.info({ user: memberId });
39

40
            // Check if the userInfo was successful and user info is present
41
            if (userInfo.ok && userInfo.user) {
42
              if (userInfo.user.profile && userInfo.user.profile.email) {
43
                // Check if the email domain is not windmill.dev
44
                if (!userInfo.user.profile.email.endsWith(companyDomain)) {
45
                  external = true;
46
                }
47
              } else {
48
                // Assume external if the email is not available
49
                external = true;
50
              }
51
            }
52
          }
53
        }
54

55
        // Call the conversations.history method to get the last message of the channel
56
        const historyResult = await slackClient.conversations.history({
57
          channel: channel.id,
58
          limit: 1, // We only need the last message
59
        });
60

61
        // Initialize the lastMessageDate
62
        let lastMessageDate = "No messages found";
63

64
        // Check if the historyResult was successful and messages are present
65
        if (
66
          historyResult.ok && historyResult.messages &&
67
          historyResult.messages.length > 0
68
        ) {
69
          // Convert the timestamp to a Date object
70
          const date = new Date(
71
            parseFloat(historyResult.messages[0].ts) * 1000,
72
          );
73

74
          // Format the Date object to "YYYYMMDD"
75
          const year = date.getFullYear();
76
          const month = (date.getMonth() + 1).toString().padStart(2, "0"); // Pad with zero if needed
77
          const day = date.getDate().toString().padStart(2, "0"); // Pad with zero if needed
78

79
          lastMessageDate = `${year}${month}${day}`;
80
        }
81

82
        // Add the channel info to the array
83
        channelsInfo.push({
84
          id: channel.id,
85
          name: channel.name,
86
          lastMessageDate: lastMessageDate,
87
          external: external
88
        });
89
      }
90

91
      // Return the list of channels with the date of the last message, external member status
92
      return channelsInfo;
93
    } else {
94
      // Return an error message if the listResult was not successful or channels are not present
95
      return "Failed to retrieve channels or no channels found.";
96
    }
97
  } catch (error) {
98
    // Return the error if the API call fails
99
    return `Error retrieving channels: ${error}`;
100
  }
101
}
Other submissions
  • Submitted by henri186 Deno
    Created 412 days ago
    1
    import { WebClient as SlackWebClient } from "npm:@slack/web-api";
    2
    
    
    3
    type Slack = {
    4
      token: string
    5
    
    
    6
    }
    7
    
    
    8
    // Needed scopes are: users:read ; users:read.email ; channels:read ; channels:history
    9
    
    
    10
    export async function main(slackResource: Slack, companyDomain: string) {
    11
      
    12
      // Initialize the Slack WebClient with the provided token
    13
      const slackClient = new SlackWebClient(slackResource.token);
    14
    
    
    15
      try {
    16
        // Call the conversations.list method to get all channels
    17
        const listResult = await slackClient.conversations.list();
    18
    
    
    19
        // Check if the listResult was successful and channels are present
    20
        if (listResult.ok && listResult.channels) {
    21
          // Initialize an array to hold the channels with their last message date and external member status
    22
          const channelsInfo = [];
    23
    
    
    24
          // Iterate over each channel to fetch the last message's date, check for external members
    25
          for (const channel of listResult.channels) {
    26
            // Initialize external as false
    27
            let external = false;
    28
    
    
    29
            // Call the conversations.members method to get all members of the channel
    30
            const membersResult = await slackClient.conversations.members({
    31
              channel: channel.id,
    32
            });
    33
    
    
    34
            // Check if the membersResult was successful and members are present
    35
            if (membersResult.ok && membersResult.members) {
    36
              // Iterate over each member to fetch their user info
    37
              for (const memberId of membersResult.members) {
    38
                const userInfo = await slackClient.users.info({ user: memberId });
    39
    
    
    40
                // Check if the userInfo was successful and user info is present
    41
                if (userInfo.ok && userInfo.user) {
    42
                  if (userInfo.user.profile && userInfo.user.profile.email) {
    43
                    // Check if the email domain is not windmill.dev
    44
                    if (!userInfo.user.profile.email.endsWith(companyDomain)) {
    45
                      external = true;
    46
                    }
    47
                  } else {
    48
                    // Assume external if the email is not available
    49
                    external = true;
    50
                  }
    51
                }
    52
              }
    53
            }
    54
    
    
    55
            // Call the conversations.history method to get the last message of the channel
    56
            const historyResult = await slackClient.conversations.history({
    57
              channel: channel.id,
    58
              limit: 1, // We only need the last message
    59
            });
    60
    
    
    61
            // Initialize the lastMessageDate
    62
            let lastMessageDate = "No messages found";
    63
    
    
    64
            // Check if the historyResult was successful and messages are present
    65
            if (
    66
              historyResult.ok && historyResult.messages &&
    67
              historyResult.messages.length > 0
    68
            ) {
    69
              // Convert the timestamp to a Date object
    70
              const date = new Date(
    71
                parseFloat(historyResult.messages[0].ts) * 1000,
    72
              );
    73
    
    
    74
              // Format the Date object to "YYYYMMDD"
    75
              const year = date.getFullYear();
    76
              const month = (date.getMonth() + 1).toString().padStart(2, "0"); // Pad with zero if needed
    77
              const day = date.getDate().toString().padStart(2, "0"); // Pad with zero if needed
    78
    
    
    79
              lastMessageDate = `${year}${month}${day}`;
    80
            }
    81
    
    
    82
            // Add the channel info to the array
    83
            channelsInfo.push({
    84
              id: channel.id,
    85
              name: channel.name,
    86
              lastMessageDate: lastMessageDate,
    87
              external: external
    88
            });
    89
          }
    90
    
    
    91
          // Return the list of channels with the date of the last message, external member status
    92
          return channelsInfo;
    93
        } else {
    94
          // Return an error message if the listResult was not successful or channels are not present
    95
          return "Failed to retrieve channels or no channels found.";
    96
        }
    97
      } catch (error) {
    98
        // Return the error if the API call fails
    99
        return `Error retrieving channels: ${error}`;
    100
      }
    101
    }