-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathclose-issue-channel.js
161 lines (155 loc) ยท 4.74 KB
/
close-issue-channel.js
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
import { startBot, getNArg } from './common.js';
startBot(async (client) => {
console.log(`Logged in as ${client.user.tag}`);
const issueNumber = getNArg(2);
console.log(`Closing issue ${issueNumber}`);
const success = await closeIssueChannel(client, issueNumber, /*dev=*/ false);
client.destroy();
console.log(`Success: ${success}`);
process.exit(success ? 0 : 1);
});
/**
* # Close Issue Channel Script
*
* ## Command Line Usage
*
* 1. Make sure your environment variables are defined.
* 1. Run the following command.
*
* ```bash
* node scripts/close-issue-channel.js 180
* ```
*
* ## GitHub Workflow Usage
*
* ```yaml
* - run: node scripts/close-issue-channel.js ${{ github.event.issue.number }}
* env:
* DISCORD_BOT_TOKEN: ${{ secrets.DISCORD_BOT_TOKEN }}
* GUILD_ID: ${{ secrets.GUILD_ID }}
* ARCHIVE_CHANNEL_ID: ${{ secrets.ARCHIVE_CHANNEL_ID }}
* ```
*
* See `.github/workflows/close_issue_channel.yaml`.
*/
const closeIssueChannel = async (client, issueNumber, dev = false) => {
let success = false;
try {
await client.guilds.fetch();
const { channels } = client.guilds.cache.get(process.env.GUILD_ID);
const archiveChannel = [...channels.cache.values()].find(
(ch) => ch.id === process.env.ARCHIVE_CHANNEL_ID
);
if (archiveChannel === undefined) {
console.log(`No archive channel found.`);
return false;
}
const oldChannels = [...channels.cache.values()].filter(
(ch) =>
ch.parentId === archiveChannel.parentId && ch.name.includes(`website-issue-${issueNumber}`)
);
for (const oldChannel of oldChannels) {
const timestamp = formatRFC882PST(new Date());
const title = `โญ
โ __/__/_
โ __/__/_ ${oldChannel.name}
โ / /
โ
โฐโ archived ${timestamp}`;
const footer = `โญ${'โ'.repeat(timestamp.length + 11)}โฎ
โ archived ${timestamp} โ
โฐ${'โ'.repeat(timestamp.length + 11)}โฏ`;
const allMessages = await fetchAllMessages(oldChannel);
const fileContent =
title + '\n\n' + allMessages.map(formatMessage).join('\n') + '\n\n' + footer;
if (dev) {
console.log(fileContent);
return true;
}
const attachment = Buffer.from(fileContent);
const message = await archiveChannel.send({
files: [{ name: `${oldChannel.name}.txt`, attachment }],
});
await message.pin();
await oldChannel.delete();
}
success = true;
} catch (error) {
console.log(error);
}
return success;
};
const fetchAllMessages = async (channel, limit = 2e3) => {
const result = [];
const softLimit = 100;
let lastId;
// eslint-disable-next-line no-constant-condition
while (true) {
const options = { limit: softLimit };
if (lastId) options.before = lastId;
const messages = await channel.messages.fetch(options);
if (messages === undefined) break;
result.push(...messages.values());
lastId = messages.last().id;
if (messages.size != softLimit || result >= limit) break;
}
return result.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
};
const formatMessage = (msg) => {
const lines = [];
for (const line of msg.content.split('\n')) {
lines.push(...wrapText(line, 72));
}
const topLeft = `โญ${msg.author.tag} โ ${formatRFC882PST(msg.createdAt)}`;
const longestLine = lines.reduce(
(record, line) => (line.length > record ? line.length : record),
0
);
const width = Math.max(longestLine + 3, topLeft.length);
const topRight = 'โ'.repeat(width - topLeft.length) + 'โฎ';
const content = lines
.map((line) => {
const padding = width - line.length - 3;
return `โ ${line}${' '.repeat(padding)} โ`;
})
.join('\n');
const bottom = `โฐ${'โ'.repeat(width - 1)}โฏ`;
const result = topLeft + topRight + '\n' + content + '\n' + bottom;
return result;
};
const wrapText = (text, width = 72) => {
const lines = [];
while (text.length > width) {
const index = text.lastIndexOf(' ', width);
if (index === -1) {
lines.push(text.substring(0, width));
text = text.substring(width);
} else {
lines.push(text.substring(0, index));
text = text.substring(index + 1);
}
}
lines.push(text);
return lines;
};
const formatRFC882PST = (date) => {
const [month, day, year, time, amPm] = date
.toLocaleDateString('en-US', {
day: '2-digit',
month: 'short',
year: '2-digit',
hour: '2-digit',
minute: '2-digit',
timeZone: 'America/Los_Angeles',
})
.replace(/,/g, '')
.split(' ');
const timezone = Intl.DateTimeFormat('en-US', {
timeZoneName: 'short',
timeZone: 'America/Los_Angeles',
})
.format(date)
.split(' ')
.at(-1);
return `${day} ${month} ${year} ${time} ${amPm} ${timezone}`;
};