This repository was archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
186 lines (166 loc) · 5 KB
/
Copy pathapp.js
File metadata and controls
186 lines (166 loc) · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Description
// Responses or archives unused channels.
//
// Commands:
// @APPID list ([0-9]+)days - returns unused channels
// @APPID kill ([0-9]+)days - archives unused channels
//
// Author:
// tyage <namatyage@gmail.com>
const { App } = require('@slack/bolt');
require('dotenv').config();
const fs = require('fs');
const cacheFile = 'cache.json';
let cachedData = null;
const readCache = () => {
if (!cachedData) {
try {
const buf = fs.readFileSync(cacheFile);
cachedData = JSON.parse(buf);
} catch (_) {
// do nothing if the file is broken
}
}
return cachedData;
};
const writeCache = (data) => {
const buf = JSON.stringify(data);
fs.writeFileSync(cacheFile, buf);
cachedData = data;
};
const findAllChannels = async (app, cursor = '') => {
const { channels, response_metadata: { next_cursor: nextCursor } } = await app.client.conversations.list({
token: process.env.SLACK_BOT_TOKEN,
cursor,
exclude_archived: true,
types: 'public_channel',
limit: 1000
});
if (nextCursor && nextCursor !== '') {
const nextChannels = await findAllChannels(app, nextCursor);
return [...channels, ...nextChannels];
} else {
return channels;
}
};
const joinChannel = async (app, channel) => {
await app.client.conversations.join({
token: process.env.SLACK_BOT_TOKEN,
channel
});
};
const isChannelDisused = async (app, channel, threshold) => {
const isMessageOld = (message, threshold) => {
const messageTime = new Date(message.ts * 1000);
const now = new Date();
const thresholdMillSec = threshold * 24 * 60 * 60 * 1000;
const isDisused = (now - messageTime) > thresholdMillSec;
return isDisused;
};
const cachedChannels = readCache() || {};
const cachedChannel = cachedChannels[channel];
// if cached data is still new, return and do not update information
if (cachedChannel && !isMessageOld(cachedChannel.lastMessage, threshold)) {
return false;
}
let messages;
try {
const data = await app.client.conversations.history({
token: process.env.SLACK_BOT_TOKEN,
channel,
limit: 10 // check last 10 messages
});
messages = data.messages;
} catch (_) {
// failed to fetch history
return false;
}
let i = 0;
let lastMessage = messages[0];
// if the last message is join event, take next message so that we can ignore join event
while (lastMessage && lastMessage.subtype === 'channel_join') {
i++;
lastMessage = messages[i];
}
// if there is no message, ignore this channel
if (!lastMessage) {
return false;
}
// update cache
cachedChannels[channel] = {
lastMessage
};
writeCache(cachedChannels);
return isMessageOld(lastMessage, threshold);
};
const findDisusedChannels = async (app, threshold) => {
const channels = await findAllChannels(app);
const disusedChannels = [];
for (let channel of channels) {
console.log(`check ${channel.name}`);
// join if not a member
if (!channel.is_member) {
await joinChannel(app, channel.id);
}
if (await isChannelDisused(app, channel.id, threshold)) {
disusedChannels.push(channel.id);
}
}
return disusedChannels;
};
const archiveChannel = async (app, channel) => {
await app.client.conversations.archive({
token: process.env.SLACK_BOT_TOKEN,
channel
});
};
const app = new App({
logLevel: 'debug',
token: process.env.SLACK_BOT_TOKEN,
appToken: process.env.SLACK_APP_TOKEN,
socketMode: true
});
app.event('app_mention', async ({ event, say }) => {
const message = event.text;
const listPattern = /list ([0-9]+)days/;
const archivePattern = /archive ([0-9]+)days/;
// list
if (message.match(listPattern)) {
await say('ちょっとまってね');
const matches = message.match(listPattern);
const day = +matches[1];
const channels = await findDisusedChannels(app, day);
const formattedChannels = channels.map(channel => `<#${channel}>`).join(',');
await say(`channels disused for ${day}days: ${formattedChannels}`);
// archive
} else if (message.match(archivePattern)) {
await say('ちょっとまってね');
const matches = message.match(archivePattern);
const day = +matches[1];
if (day < 30) {
return await say(`${day}日は短くない?`);
}
const channels = await findDisusedChannels(app, day);
const formattedChannels = channels.map(channel => `<#${channel}>`).join(',');
await say(`archiving channels disused for ${day}days: ${formattedChannels}`);
for (let channel of channels) {
await archiveChannel(app, channel);
}
} else {
await say('???');
}
});
// join channel if created or unarchived
app.event('channel_created', async ({ event }) => {
const channel = event.channel;
await joinChannel(app, channel.id);
});
app.event('channel_unarchive', async ({ event }) => {
const channelId = event.channel;
await joinChannel(app, channelId);
});
(async () => {
await app.start();
console.log('⚡️ Bolt app started');
// await findDisusedChannels(app, 100);
})();