-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
396 lines (360 loc) · 13 KB
/
bot.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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
const { Octokit } = require('octokit');
const { Client, EmbedBuilder, GatewayIntentBits } = require('discord.js');
const btoa = require('btoa');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const express = require('express');
const app = express();
require('dotenv').config();
app.use(express.json());
const octokit = new Octokit({
auth: process.env.GH_AUTH,
});
if (
process.env.TOKEN === undefined ||
process.env.GH_USER === undefined ||
process.env.GH_AUTH === undefined ||
process.env.ANNOTATOR_REPO === undefined ||
process.env.BOLT_REPO === undefined ||
process.env.DATA_PIPE_REPO === undefined ||
process.env.PROJECTS_REPO === undefined ||
process.env.PAYMENT_REPO === undefined ||
process.env.KAYA_REPO === undefined ||
process.env.ADMIN_REPO === undefined ||
process.env.PLAYGROUND_REPO === undefined ||
process.env.PROFILES_REPO === undefined ||
process.env.CHANNEL_ID === undefined ||
process.env.PORT === undefined
) {
console.error('ERROR: Invalid process.environmental variables');
process.exit(1);
}
// ? This is an object to assign colours to each embed depending on what repo it's from
const repoList = {
[process.env.BOLT_REPO] : { colour: '#0000FF', PRs: [], amplify: true, pr_preview: 'https://test-pr-previews.dl5eewox9qmvx.amplifyapp.com/' },
[process.env.KAYA_REPO] : { colour: '#DA33FF', PRs: [], amplify: true, pr_preview: 'https://test-pr-previews.dk2lbhfysm2ic.amplifyapp.com/' },
[process.env.ADMIN_REPO] : { colour: '#9333FF', PRs: [], amplify: true, pr_preview: 'https://test.d1itkb6pz56lpp.amplifyapp.com/' },
[process.env.ANNOTATOR_REPO] : { colour: '#FF0000', PRs: [], amplify: false },
[process.env.DATA_PIPE_REPO] : { colour: '#00FF00', PRs: [], amplify: false },
[process.env.PROJECTS_REPO] : { colour: '#33FFF9', PRs: [], amplify: false },
[process.env.PAYMENT_REPO] : { colour: '#FFA833', PRs: [], amplify: false },
[process.env.PLAYGROUND_REPO] : { colour: '#E0FF33', PRs: [], amplify: false },
[process.env.PROFILES_REPO] : { colour: '#33FF33', PRs: [], amplify: false },
};
// ?- Function to check if message is already present in the chat, if so don't upload another one
const checkIfPresent = async (channel, prURL) => {
await channel.messages.fetch({ limit: 100 }).then((messages) => {
messages.forEach((message) => {
if (message.embeds.length === 0) {
return false;
}
if (message.embeds[0].data.url === prURL) {
return true;
}
});
});
return false;
};
const getAmplify = async (repo, prNum, prRewviewURL) => {
let amplifyLink = '\`PR Link:\` ';
const regex = /https:\/\/pr\-[^\s]+/;
const responses = await octokit.request(`GET /repos/${repo}/issues/${prNum}/comments`, {
owner: 'Supahands',
repo: repo.slice('/'),
pull_number: prNum,
});
for (const response of responses.data) {
if (response.user.login === 'aws-amplify-us-west-2[bot]') {
console.log('PR LINK:', response.body.match(regex)[0]);
amplifyLink += await response.body.match(regex)[0];
amplifyLink += `\n\n \`Test link to login first with:\` ${prRewviewURL}/`;
amplifyLink += '\n\n<@795488563038912523> <@877389011965063168> <@169346852364222464>';
}
}
return amplifyLink;
};
// ? - Modify this, to accept the repo name as well, to assign colours to it
const createEmbed = async (repo, pr, channel) => {
if (await checkIfPresent(channel, pr.html_url)) {
return;
}
const { number, title, commits } = pr;
const { avatar_url, login } = pr.user;
if (repoList[repo].amplify) {
const amplifyFieldData = await getAmplify(repo, number, repoList[repo].pr_preview);
const Embed = new EmbedBuilder()
.setColor(repoList[repo].colour)
.setTitle(`${number}: ${title}`)
.setURL(pr.html_url)
.setAuthor({ name: login, iconURL: null, url: pr.user.html_url })
.setThumbnail(avatar_url)
.addFields({
name: 'Repo',
value: `${repo}`,
},
{
name: 'Amplify details',
value: `${await amplifyFieldData}`,
})
.setDescription(
`${await amplifyFieldData === '\`PR Link:\` ' ? `Merge ${commits} commits into \`${pr.base.ref}\` from \`${pr.head.ref}\` ` : `Merge ${commits} commits into \`${pr.base.ref}\` from \`${pr.head.ref}\` <@&795488563038912523> <@877389011965063168> <@169346852364222464>`}`,
);
channel.send({ embeds: [Embed] });
}
else {
const Embed = new EmbedBuilder()
.setColor(repoList[repo].colour)
.setTitle(`${number}: ${title}`)
.setURL(pr.html_url)
.setAuthor({ name: login, iconURL: null, url: pr.user.html_url })
.setThumbnail(avatar_url)
.addFields({
name: 'Repo',
value: `${repo}`,
})
.setDescription(
`Merge ${commits} commits into \`${pr.base.ref}\` from \`${pr.head.ref}\` <@&795488563038912523>`,
);
channel.send({ embeds: [Embed] });
}
};
// ? - Search through all messages, compare embed url with arguement URL, then delete message if it's the same
const deleteMessage = async (channel, prURL) => {
channel.messages.fetch({ limit: 100 }).then((messages) => {
messages.forEach(async (message) => {
if (message.embeds[0].url === prURL) {
message.delete();
}
});
});
};
// ? - Updates all the reactions on the embeds
const updateEmbed = async (channel, state, prURL) => {
channel.messages.fetch({ limit: 100 }).then((messages) => {
messages.forEach(async (message) => {
// ? - Switch statement for different message types, reaction for each different type
if (message.embeds[0].url === prURL) {
console.log('Review left for', prURL, ': ', state);
const approve1Reaction = '<:approve1:1081046953212776528>';
const approve2Reaction = '<:approve2:1081047016039252018>';
const messageReactions = [];
message.reactions.cache.forEach(async (reaction) => {
messageReactions.push(await reaction.emoji.name);
});
// ? - if action === submitted
console.log('Reactions for current message:', await messageReactions);
switch (state) {
case 'APPROVED':
try {
if (await messageReactions.includes('approve1') && await messageReactions.includes('approve2')) {
console.log('APPROVED');
break;
}
if (await !messageReactions.includes('approve1')) {
console.log('Adding approve1 reaction');
await message.react(approve1Reaction);
break;
}
if (await messageReactions.includes('approve1')) {
console.log('Approve 2 reaction');
await message.react(approve2Reaction);
break;
}
break;
}
catch (error) {
console.log(error);
break;
}
case 'CHANGES_REQUESTED':
await message.react('❌');
break;
case 'COMMENTED':
await message.react('💬');
break;
// ! Haven't found a way to remove a specific reaction only once from a message, only remove all (https://discordjs.guide/popular-topics/reactions.html#removing-reactions)
case 'dismissed':
break;
}
}
});
});
};
// ? - Retrieves all PR data from each specified repo
const getAllPRs = async () => {
for (const repo in repoList) {
const childObject = repoList[repo];
const repoName = repo.slice('/');
console.log('fetching repo: ', repo);
try {
const { data } = await octokit.request(`GET /repos/${repo}/pulls`, {
owner: 'supahands',
repo: repoName.slice('/'),
state: 'opened',
});
childObject.PRs = data;
}
catch (error) {
console.error(`Error fetching PRs for ${repo}: ${error.message}`);
}
}
};
/*
TODO: compare all embeds with all open PR's from the repo where the pull request came from
? - If pr is open and does not match any of the channel emebds url, create new embed and add to channel
TODO: Look through messages in channel and update accordingly
? - If message is not an embed, delete it
? - If the PR attached to an embed is closed, delete the message
*/
const updateChannel = async (channel) => {
const chatEmbeds = [];
// ? - Update all repo objects with PR data
await getAllPRs();
const channelMessages = await channel.messages.fetch({ limit: 100 });
for (const message of channelMessages) {
if (message[1].embeds.length === 0) {
break;
}
chatEmbeds.push(message[1].embeds[0]);
}
// ? - Check through all PR's of each repo to see if any are not displayed atm
for (const repoItem in repoList) {
const repoData = repoList[repoItem];
const prs = repoData.PRs;
// ? - If the PR is open and does not match any of the channel emebds url, create new embed and add to channel
for (const pr of prs) {
const prInChat = chatEmbeds.find(embed => embed.data.url === pr.html_url);
if (prInChat === undefined && pr.draft === false) {
await createEmbed(repoItem, pr, channel);
}
}
}
// ? - Go through channel and delete all irrelevant messages
await channel.messages.fetch({ limit: 100 }).then((messages) => {
messages.every(async (message) => {
if (message.embeds.length === 0) {
return false;
}
// ? - If the message is not an embed, delete it
if (message.embeds === 0) {
message.delete();
return;
}
const messageEmbed = message.embeds[0];
const prNum = messageEmbed.data.title.split(':')[0];
const repo = messageEmbed.data.fields[0].value;
const prURL = messageEmbed.data.url;
// ? - If the PR attached to an embed is closed, delete the message
const prInfo = await fetch(
`https://api.github.com/repos/${repo}/pulls/${prNum}`,
{
method: 'GET',
headers: {
Authorization: `Basic ${btoa(
`${process.env.GH_USER}:${process.env.GH_AUTH}`,
)}`,
},
},
).then((data) => data.json());
if (prInfo.state === 'closed') {
message.delete();
return;
}
// ? - Update the reactions on the messages
const reviews = await octokit.request(`GET /repos/${repo}/pulls/${prNum}/reviews`, {
owner: 'Supahands',
repo: repo.slice('/')[1],
pull_number: prNum,
});
for (const review of reviews.data) {
const { state } = review;
await updateEmbed(channel, state, prURL);
}
});
});
};
app.post('/', async (req, res) => {
let channel = '';
let repoName = '';
let action = '';
let pr = '';
try {
channel = client.channels.cache.get(process.env.CHANNEL_ID);
repoName = req.body.repository.full_name;
action = req.body.action;
pr = req.body.pull_request;
}
catch (error) {
console.log('Error:', error);
res.status(400).send(error);
return;
}
// ! Check for invalid repo
if (repoList[repoName] === undefined) {
console.error('Unsupported repo, please check that you spelt the repo correctly: ', repoName);
res.status(400).send('Unsupported repo, please check that you spelt the repo correctly: ' + repoName);
return;
}
// TODO: Set conditions for each of these actions:
/*
TODO: Add for creation and deletion of embeds
? List of base pull request actions:
* - opened : new pr request opened (Add that pr to chat + check if any other PR's are open)
* - closed : pr closed (Delete specfied pr from chat)
* - converted_to_draft : pr converted to draft (remove that from chat, also need to add condition in update to ignore it, until it is opened)
! - Can put logic in to ignore the ones below
* - review_requested : fired each time you request a review from someone (so this happens alot)
* - review_request_removed
* - assigned: fired when a user is assigned to a pull request
* - unassigned: fired when a user is unassigned from a pull request
*/
/*
TODO: Add for update functionality
? List of pull_request_review actions:
* - submitted : review submitted
* - edited: review edited
* - dismissed: review dismissed
* - resolved: Review comment dispute had been resolved
! - Look at the state key under the review object to see what sort of review it is
* - approved: review approved
* - changes_requested: asks for code changes
* - dismissed: review dismissed by owner
? There is also pull_request_comment or known as issue_comment, this uses the exact same syntax as review
*/
// >
if (action === 'opened') {
await createEmbed(repoName, pr, channel);
updateChannel(channel, repoName);
res.status(200).send('Updated and uploaded');
}
else if (action === 'closed' || action === 'converted_to_draft') {
await deleteMessage(channel, pr.html_url);
res.status(200).send('Deleted');
}
// ? - Updating review
else if (action === 'submitted') {
const reviewState = req.body.review.state.toUpperCase();
await updateEmbed(channel, reviewState, pr.html_url);
res.status(200).send(`Reacted: ${reviewState}`);
}
// ? - Updating comments
else if (action === 'created') {
const state = 'COMMENTED';
await updateEmbed(channel, state, pr.html_url);
res.status(200).send('Commented');
}
else {
res.status(400).send('Unsupported action, please check that you spelt the action correctly: ' + action);
}
});
// ? - Specify port for server to listen on
app.listen(process.env.PORT || 3000, () => {
console.log(`Listening on port ${process.env.PORT || 3000}`);
});
// ? - Listen for when bot is connected to Discord (i.e. logged in)
client.on('ready', () => {
console.log(
`Logged in as ${client.user ? client.user.tag : 'no user defined'}`,
);
});
// ? - Proceed with connecting to Discord (login)
client.login(process.env.TOKEN);