1 | import { WebClient as SlackWebClient } from "npm:@slack/web-api"; |
2 |
|
3 | type Slack = { |
4 | token: string |
5 |
|
6 | } |
7 |
|
8 | |
9 |
|
10 | export async function main(slackResource: Slack, companyDomain: string) { |
11 | |
12 | |
13 | const slackClient = new SlackWebClient(slackResource.token); |
14 |
|
15 | try { |
16 | |
17 | const listResult = await slackClient.conversations.list(); |
18 |
|
19 | |
20 | if (listResult.ok && listResult.channels) { |
21 | |
22 | const channelsInfo = []; |
23 |
|
24 | |
25 | for (const channel of listResult.channels) { |
26 | |
27 | let external = false; |
28 |
|
29 | |
30 | const membersResult = await slackClient.conversations.members({ |
31 | channel: channel.id, |
32 | }); |
33 |
|
34 | |
35 | if (membersResult.ok && membersResult.members) { |
36 | |
37 | for (const memberId of membersResult.members) { |
38 | const userInfo = await slackClient.users.info({ user: memberId }); |
39 |
|
40 | |
41 | if (userInfo.ok && userInfo.user) { |
42 | if (userInfo.user.profile && userInfo.user.profile.email) { |
43 | |
44 | if (!userInfo.user.profile.email.endsWith(companyDomain)) { |
45 | external = true; |
46 | } |
47 | } else { |
48 | |
49 | external = true; |
50 | } |
51 | } |
52 | } |
53 | } |
54 |
|
55 | |
56 | const historyResult = await slackClient.conversations.history({ |
57 | channel: channel.id, |
58 | limit: 1, |
59 | }); |
60 |
|
61 | |
62 | let lastMessageDate = "No messages found"; |
63 |
|
64 | |
65 | if ( |
66 | historyResult.ok && historyResult.messages && |
67 | historyResult.messages.length > 0 |
68 | ) { |
69 | |
70 | const date = new Date( |
71 | parseFloat(historyResult.messages[0].ts) * 1000, |
72 | ); |
73 |
|
74 | |
75 | const year = date.getFullYear(); |
76 | const month = (date.getMonth() + 1).toString().padStart(2, "0"); |
77 | const day = date.getDate().toString().padStart(2, "0"); |
78 |
|
79 | lastMessageDate = `${year}${month}${day}`; |
80 | } |
81 |
|
82 | |
83 | channelsInfo.push({ |
84 | id: channel.id, |
85 | name: channel.name, |
86 | lastMessageDate: lastMessageDate, |
87 | external: external |
88 | }); |
89 | } |
90 |
|
91 | |
92 | return channelsInfo; |
93 | } else { |
94 | |
95 | return "Failed to retrieve channels or no channels found."; |
96 | } |
97 | } catch (error) { |
98 | |
99 | return `Error retrieving channels: ${error}`; |
100 | } |
101 | } |