-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.js
664 lines (597 loc) · 26.1 KB
/
app.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
const Discord = require('discord.js');
const nacl = require('tweetnacl');
const { DiscordInteractions } = require("slash-commands");
// initialize dotenv
require('dotenv').config();
var client = new Discord.Client();
client.login(process.env.BOT_TOKEN);
var newsChannel = null;
client.on('ready', () => {
console.log('Bot is ready');
fetchChannel();
});
// install with: npm install @octokit/webhooks
const { Webhooks } = require("@octokit/webhooks");
const { Octokit } = require("@octokit/core");
const { resolveOverwriteOptions } = require('discord.js/src/structures/PermissionOverwrites');
require('dotenv').config();
const webhooks = new Webhooks({
secret: process.env.WEBHOOK_TOKEN,
path: "/github"
});
const octokit = new Octokit({
auth: process.env.WEBHOOK_TOKEN
});
webhooks.onAny(async (m) => {
try {
if (newsChannel) {
if (m.name === "push") {
return;
if (!m.payload.commits.length) return;
const branch = m.payload.ref.replace("refs/heads/", "");
const message = m.payload.commits[0].message.slice(0, 70);
const link = m.payload.commits[0].url
if (m.payload.commits.length > 1) {
newsChannel.send(`${m.payload.pusher.name} pushed ${m.payload.commits.length} commits to ${branch}, including ${message}\n${link}`);
}
else {
newsChannel.send(`${m.payload.pusher.name} pushed commit to ${branch}: ${message}\n${link}`);
}
return;
}
if (m.name === "pull_request") {
const pr = m.payload.pull_request;
const user = pr.user;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setURL(pr.html_url);
embed.setThumbnail("https://img.icons8.com/ios/452/pull-request.png");
switch (m.payload.action) {
case "opened":
embed.setTitle("New Pull Request - " + pr.title);
embed.setDescription(`[\`#${pr.number}\`](${pr.html_url} 'View on github')\n\n${truncateString(pr.body, pr)}`);
break;
case "closed":
if (pr.merged) {
return; // The PR was merged. The discord github bot will take care of notifications.
}
embed.setTitle("PR Closed - " + pr.title);
embed.setDescription(`[\`${pr.number}\`](${pr.html_url} '${truncateString(pr.body, pr)}')`);
break;
case "reopened":
embed.setTitle("PR Reopened - " + pr.title);
embed.setDescription(`[\`/${pr.number}\`](${pr.html_url} '${truncateString(pr.body, pr)}')`);
break;
case "ready_for_review":
embed.setTitle("PR Ready for review - " + pr.title);
embed.setDescription(`[\`/${pr.number}\`](${pr.html_url} '${truncateString(pr.body, pr)}')`);
break;
default:
// prevent sending the embed.
return;
}
newsChannel.send(embed);
return;
}
if (m.name === "pull_request_review") {
if (m.payload.action === "submitted") {
const pr = m.payload.pull_request;
const review = m.payload.review;
const user = m.payload.review.user;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setURL(review.html_url);
let title = `New review for PR #${pr.number} – ${pr.title}`;
if (review.state.toLowerCase() === "approved") {
title = `PR #${pr.number} approved – ${pr.title}`;
} else if (review.state.toLowerCase() === "changes_requested") {
title = `Changes requested to PR #${pr.number} – ${pr.title}`;
}
embed.setTitle(title);
const comments = await octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments', {
owner: m.payload.repository.owner.login,
repo: m.payload.repository.name,
pull_number: pr.number,
review_id: review.id
});
let commentCount = comments.length;
let commentCountDescription = commentCount === 1 ? '1 comment' : `${commentCount} comments`;
let description = "No description provided";
if (review.body && commentCount) {
description = `${truncateString(review.body, pr)}\n\n${commentCountDescription}`;
} else if (review.body) {
description = truncateString(review.body, pr);
} else if (commentCount) {
if (commentCount === 1 && comments[0].body) {
description = truncateString(comments[0].body, pr);
} else {
description = commentCountDescription;
}
}
if (description) {
embed.setDescription(description);
}
newsChannel.send(embed);
}
return;
}
if (m.name === "member") {
if (m.payload.action === "added") {
const user = m.payload.member;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setTitle("New Contributor!");
embed.setDescription(`Congrats to ${user.login} for being a new contributor to the ${m.payload.repository.name} repository!\n:partying_face::love_you_gesture:`)
newsChannel.send(embed);
}
return;
}
if (m.name === "ping") {
newsChannel.send("Github sent me this weird thing:");
newsChannel.send(`"${m.payload.zen}"`);
newsChannel.send("What do you think it means?");
setTimeout(() => {
newsChannel.send("After confirmation with the folks at Github, it looks like we will be receiving news from a new repo: " + m.payload.repository.full_name + ". Wow. That's amazing.")
}, 10000)
return;
}
if (m.name === "star") {
const stars = m.payload.repository.stargazers_count;
if (!(stars % 1000)) {
newsChannel.send(`We reached ${stars} stars in the ${m.payload.repository.name} repo!`)
}
return;
}
if (m.name === "fork") {
const forks = m.payload.repository.forks_count;
if (!(forks % 1000)) {
newsChannel.send(`We reached ${forks} forks in the ${m.payload.repository.name} repo!`)
}
return;
}
if (m.name === "meta") {
newsChannel.send("My github hook was deleted. :sad: I will not be able to receive any more news from my friends out there.")
return;
}
if (m.name === "issues") {
// embed.setThumbnail(http://cdn.onlinewebfonts.com/svg/img_2382.png);
if (m.payload.action === "opened") {
const user = m.payload.sender;
const issue = m.payload.issue;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setURL(issue.html_url);
embed.setTitle(`New Issue: ${issue.title}`);
embed.setDescription(truncateString(issue.body, issue));
newsChannel.send(embed);
}
return;
}
if (m.name === "issue_comment") {
if (m.payload.action === "created") {
const user = m.payload.sender;
const issue = m.payload.issue;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setURL(issue.html_url);
embed.setTitle(`New comment on "${issue.title}"`)
embed.setDescription(truncateString(m.payload.comment.body, issue))
newsChannel.send(embed);
}
return;
}
if (m.name === "discussion") {
if (m.payload.action === "created") {
const user = m.payload.sender;
const discussion = m.payload.discussion;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setURL(discussion.html_url);
embed.setTitle(`New Discussion: ${discussion.title}`);
embed.setDescription(truncateString(discussion.body, discussion));
newsChannel.send(embed);
}
return;
}
if (m.name === "discussion_comment") {
if (m.payload.action === "created") {
const user = m.payload.sender;
const discussion = m.payload.discussion;
const embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setAuthor(user.login, user.avatar_url, user.html_url);
embed.setURL(discussion.html_url);
embed.setTitle(`New comment on "${discussion.title}"`);
embed.setDescription(truncateString(m.payload.comment.body, discussion));
newsChannel.send(embed);
}
return;
}
if (m.name === "milestone") {
if (isOneIn(m.payload.action, ["opened"])) {
newsChannel.send(`${m.payload.sender.login} created a milestone: ${m.payload.milestone.title}\n${m.payload.issue.html_url}`)
}
return;
}
if (m.name === "release") {
if (isOneIn(m.payload.action, ["published"])) {
newsChannel.send(`${m.payload.sender.login} published a release!\n${m.payload.issue.html_url}`)
}
return;
}
if (m.name === "secret_scanning_alert") {
// Notify Igor Korsukov. Anyone else to notify?
client.fetchUser('820950138125156353', false).then((user) => {
if (m.payload.action === "created") {
user.send('A secret was uncovered: ' + m.payload.alert.secret_type);
}
else if (m.payload.action === "resolved") {
user.send('The leaked secret (' + m.payload.alert.secret_type + ") alert has been resolved.");
}
else if (m.payload.action === "reopened") {
user.send('A secret leaked again: ' + m.payload.alert.secret_type);
}
});
}
if (isOneIn(m.name, ["check_run", "check_suite"])) {
return; // these events are not useful to us.
}
console.log("Received unknown event from github: " + m.name);
// newsChannel.send("Received unknown event from github: " + m.name);
}
else {
fetchChannel();
}
}
catch (e) {
console.error(e);
}
});
require("http").createServer((req, res) => {
if (req.url === "/github") {
webhooks.middleware(req, res);
return;
}
else if (req.url === "/discord") {
// Comes from the discord developer portal
const PUBLIC_KEY = '02da8fc1549bb4f83c88488bc9c7df5a7ae863a9b903b3e6673af88d324a6df5';
const signature = req.headers['x-signature-ed25519'];
const timestamp = req.headers['x-signature-timestamp'];
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
});
req.on("end", () => {
body = Buffer.concat(body).toString();
console.log(body);
const isVerified = nacl.sign.detached.verify(
Buffer.from(timestamp + body),
Buffer.from(signature, 'hex'),
Buffer.from(PUBLIC_KEY, 'hex')
);
body = JSON.parse(body);
if (!isVerified) {
console.log("invalid signature");
res.statusCode = 401;
res.end('invalid request signature');
return;
}
res.setHeader('Content-Type', 'application/json');
// respond to ping request.
if (body.type === 1) {
res.end(
JSON.stringify({
type: 1,
}),
);
initSlashCommands();
return;
}
if (body.data && body.data.name && body.data.name === "wakeup") {
res.statusCode = 200;
const responseBody = {
type: 4,
data: {
content: getOneOf(
[
"Wow, I was sleeping well.",
"What was that for! I was making a wonderful dream in a world free of " + getOneOf(["humans.", body.member.user.username + "."]),
"Oh did I sleep too much?",
"Sorry sir. Someone told me sleeping was essential... Please accept my sincere excuses. I will not do it again.",
"Oh lord and when is it that I get to sleep?"
]),
flags: 64,
},
}
res.end(JSON.stringify(responseBody));
return;
}
else {
console.log("Unknown or invalid command.");
}
res.statusCode = 404;
res.end();
// Note: the 2 lines above could be replaced with this next one:
// response.end(JSON.stringify(responseBody))
});
}
}).listen(3000);
// can now receive webhook events at port 3000
let params = {
muted_bool: false,
minpr_number: 0,
minmsissue_number: 100,
minghissue_number: 0,
timebeforedelete_number: 5000,
}
client.on('message', (msg) => {
try {
if (isOneIn(msg.content, ['/h', '/help', '/man'])) {
msg.channel.send(`
This bot finds issues and pull requests in your comments and adds a link to them.
To reference issues, use ms#issue_number, and for PRs use pr#pr_number. For github issues, use gh#issue_number.
Additionnal commands include:
- \`/mute\`: Prevent the bot from sending additionnal messages. It will still be listening (and answering) to commands.
- \`/unmute\`: unmute the bot.
- \`/restart\`: Recreate the discord bot client.
- \`/delete n\`: Delete the last n messages. Use without n to delete only the last one.
- \`/set target value\`: Set a parameter (\`target\`) to \`value\`. Available parameters are:
* \`minmsissue_number\` (default value: \`100\`): The minimum issue number required in #number before linking to an issue on musescore.org.
* \`minghissue_number\` (default value: \`100\`): The minimum issue number required in #number before linking to an issue on github.
* \`minpr_number\` (default value: \`0\`): The minimum number required in pr#number before linking it.
* \`timebeforedelete_number\` (default value: \`10000\`): some of this bot's messages autodelete after some time. Use this value (in ms) to configure it.
* \`muted_bool\` (default value: \`false\`): Whether the bot is muted. See also \`/mute\` and \`/unmute\`.
Note that you can always wake me up by visiting https://musebot-discord.glitch.me.
If you encounter any issue/typo visit https://github.com/Marr11317/muscord-bot.
`)
}
if (msg.content === '/mute') {
if (params.muted_bool) {
reply(msg, ["Already Muted", "Sorry Sir, but I cannot talk."]);
return;
}
params.muted_bool = true;
reply(msg, ['Muted']);
return;
}
if (msg.content === '/unmute') {
if (params.muted_bool) {
params.muted_bool = false;
reply(msg, ["Unmuted", "Ooof. Feels good to speaak."]);
return;
}
reply(msg, ["And why would you think I am muted?", "I am already free to speak."]);
return;
}
if (isOneIn(msg.content, ['/integrate', '/restart'])) {
client = new Discord.Client();
client.login(process.env.BOT_TOKEN);
client.on('ready', () => {
reply(msg, ["Channel integrated", " - Ooouiiiin...\n - Look! It's a bot!"]);
});
return;
}
if (msg.content.startsWith('/set')) {
const args = msg.content.trim().split(/ +/);
let target = args[1];
if (!target) {
reply(msg, [`Invalid usage: no value specified.\nExample of correct usage: \`/set minpr_number 250\``]);
return;
}
target = target.toLowerCase();
if (isOneIn(target, ["h", "help", "man"])) {
let str = "Valid options are:\n";
for (const key in params) {
if (Object.hasOwnProperty.call(params, key)) {
const value = params[key];
str += ` - ${key} (current value: ${value});\n`;
}
}
msg.reply(str + "Hope that helps!");
return;
}
let value = args[2];
if (!value) {
reply(msg, [`Invalid usage: no value specified.\nExample of correct usage: \`/set minpr_number 250\``]);
return;
}
value = value.toLowerCase();
if (target.endsWith('_number')) {
const n = parseInt(args[2]);
if (!Number.isFinite(n)) {
msg.reply(`Invalid usage: target value should be a number.\nExample of correct usage: \`/set ${target} 250\``);
return;
}
else {
if (params.hasOwnProperty(target)) {
params[target] = n;
}
}
}
else if (target.endsWith('_bool')) {
if (params.hasOwnProperty(target)) {
if (isOneIn(value, ["false", "f", "0", "No"])) {
params[target] = false;
msg.reply(`${target} set to false`);
return;
}
else {
params[target] = true;
msg.reply(`${target} set to true`);
return;
}
}
}
else {
if (!params.hasOwnProperty(target)) {
msg.reply(`I do not have such a configuration variable: \`${args[1]}\`\nThese are my options: ${JSON.stringify(params)}`);
return;
}
params[target] = value;
}
msg.reply(`${target} set to ${value}`);
return;
}
if (msg.content.startsWith('/delete')) {
let n = parseInt(msg.content.trim().split(/ +/)[1]);
if (!Number.isFinite(n)) {
n = 1;
}
const n_copy = n;
msg.channel.messages.fetch({
limit: 100
}).then(messages => {
const msgs = messages.filter(m => {
if (!m) {
return false;
}
return m.author.id === client.user.id;
});
for (const m of msgs) {
if (!m) {
break;
}
m[1].delete();
n--;
if (n < 1) {
break;
}
}
let bot_msg_promise = null;
const willDisappear = `\nThis message will disappear in ${(params.timebeforedelete_number * 0.001).toFixed(2)} seconds.`;
if (n_copy > 1) {
bot_msg_promise = send(msg.channel,
[`I just $%#$@@$#@*&^ my last ${n_copy} messages.`,
"Your orders have been executed, Sir.",
"Done.", "Thank you my dear, they were annoying me too.",
"Ohhh... Look! They disappeared!",
`A wild ${n_copy}-message has disappeared!`].map((m) => m + willDisappear ));
}
else {
bot_msg_promise = send(msg.channel, ["Deleted last message.", "Message deleted."].map((m) => m + willDisappear ));
}
// msg.delete();
if (bot_msg_promise && params.timebeforedelete_number) {
bot_msg_promise.then((bot_msg) => {
setTimeout(() => {
bot_msg.delete();
}, params.timebeforedelete_number);
})
}
});
return;
}
if (params.muted_bool) {
return;
}
if (msg.author.id !== client.user.id) {
let content = msg.content.replace(/ +/g, '');;
const prs = content.match(/pr#(\d+)/gi);
if (prs) {
for (const pr of prs) {
if (!pr) {
continue;
}
const strNumber = pr.substr(3);
const n = parseInt(strNumber, 10);
if (n > params.minpr_number) {
msg.channel.send("https://github.com/musescore/MuseScore/pull/" + strNumber);
}
}
}
const ghIssues = content.match(/gh#(\d+)/gi);
if (ghIssues) {
for (const issue of ghIssues) {
if (!issue) {
continue;
}
const strNumber = issue.substr(3);
const n = parseInt(strNumber, 10);
if (n > params.minghissue_number) {
msg.channel.send("https://github.com/musescore/MuseScore/issues/" + strNumber);
}
}
}
const issues = content.match(/ms#(\d+)/gi);
// const issues = content.match(/(?<!pr)(?<!gh)(?<!ms)#(\d+)/gi);
if (issues) {
for (const issue of issues) {
if (!issue) {
continue;
}
const strNumber = issue.substring(3);
const n = parseInt(strNumber, 10);
if (n > params.minmsissue_number) {
msg.channel.send("https://musescore.org/node/" + strNumber);
}
}
}
}
}
catch(e) {
console.error(e);
client = new Discord.Client();
client.login(process.env.BOT_TOKEN);
client.on('ready', () => {
send(msg.channel, ["I crashed but restarted. Casually.", "Wowowowow I just keep crashin'", "Good thing the ground is there, cause I keep crashin'"]);
});
return;
}
});
function reply(msg, choices) {
return msg.reply(getOneOf(choices));
}
function send(channel, choices) {
return channel.send(getOneOf(choices));
}
function getOneOf(choices) {
return choices[Math.floor(Math.random() * choices.length)];
}
function isOneIn(str, array) {
for (const t of array) {
if (str === t) {
return true;
}
}
return false;
}
function fetchChannel() {
// testing
// client.channels.fetch('821194544825237518')
// actual Musescore channel
client.channels.fetch('818848130027880479')
.then((channel) => {
newsChannel = channel;
console.log("Pushing news to: " + channel.name);
})
.catch(console.error);
}
async function initSlashCommands() {
// disable slash commands
// return;
const interaction = new DiscordInteractions({
applicationId: "821194769941790740",
authToken: process.env.BOT_TOKEN,
publicKey: "02da8fc1549bb4f83c88488bc9c7df5a7ae863a9b903b3e6673af88d324a6df5",
});
const wakeup = {
"name": "wakeup",
"description": "Wake up a sleeping musebot"
}
const commands = await interaction.getApplicationCommands();
if (!commands[0].name === "wakeup") {
await interaction.createApplicationCommand(wakeup, "821531129382305814").catch(console.error);
}
}
function truncateString(s, pr = null, maxLength = 1750) {
if (!s) return "";
if (s.length > maxLength)
return s.substring(0, maxLength) + "\nMessage truncated at " + maxLength + " characters" + pr ? `, [\`#${pr.number}\`](${pr.html_url} 'view on github')` : "."
return s;
}