-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
415 lines (361 loc) Β· 13.8 KB
/
Copy pathindex.js
File metadata and controls
415 lines (361 loc) Β· 13.8 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
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
require('dotenv').config();
const fs = require('node:fs');
const path = require('node:path');
const mongoose = require('mongoose');
const express = require('express');
const crypto = require('crypto');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { DISCORD_TOKEN, MONGODB_URI, WEBHOOK_SECRET, ENABLE_ISSUE_MESSAGES = 'true' } = process.env;
console.log('WEBHOOK_SECRET loaded:', !!WEBHOOK_SECRET, WEBHOOK_SECRET ? 'Present' : 'Missing');
console.log('ENABLE_ISSUE_MESSAGES:', ENABLE_ISSUE_MESSAGES);
const RepoLink = require('./models/repoLink');
const { getIssueMessages, getBountyMessages } = require('./utils/issueMessages');
// Connect to MongoDB
mongoose.connect(MONGODB_URI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
// Create Express app for webhooks
const app = express();
// Capture the raw request body for GitHub signature verification.
// GitHub computes the signature over the exact raw bytes, not JSON.stringify(req.body).
app.use(express.json({
verify: (req, _res, buf) => {
req.rawBody = buf;
},
}));
function verifyGithubSignature(req) {
const signature = req.headers['x-hub-signature-256'];
if (!signature) {
return { ok: false, status: 401, msg: 'Unauthorized' };
}
if (!WEBHOOK_SECRET) {
return { ok: false, status: 500, msg: 'Server misconfigured' };
}
const computedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(req.rawBody || Buffer.from(''))
.digest('hex');
const expected = Buffer.from(`sha256=${computedSignature}`, 'ascii');
const actual = Buffer.from(String(signature), 'ascii');
if (expected.length !== actual.length) {
return { ok: false, status: 401, msg: 'Unauthorized' };
}
if (!crypto.timingSafeEqual(expected, actual)) {
return { ok: false, status: 401, msg: 'Unauthorized' };
}
return { ok: true };
}
async function webhookHandler(req, res) {
console.log('π Webhook received!');
const payload = req.body || {};
const event = req.headers['x-github-event'];
console.log(`Event: ${event}, Action: ${payload.action}, Repo: ${payload.repository?.full_name}`);
const signatureResult = verifyGithubSignature(req);
if (!signatureResult.ok) {
if (signatureResult.status === 401) {
console.log('β Invalid or missing webhook signature');
} else {
console.log('β Webhook server misconfigured (missing WEBHOOK_SECRET)');
}
return res.status(signatureResult.status).send(signatureResult.msg);
}
// Use the router function logic adapted for Discord bot
switch (event) {
case 'issues':
switch (payload.action) {
case 'opened':
await handleIssueOpened(payload, res);
break;
case 'labeled':
await handleIssueLabeled(payload, res);
break;
case 'closed':
console.log(`Issue #${payload.issue.number} closed in ${payload.repository.full_name}`);
break;
case 'reopened':
console.log(`Issue #${payload.issue.number} reopened in ${payload.repository.full_name}`);
break;
// Add more cases as needed
default:
return res.status(200).json();
}
break;
default:
return res.status(200).json();
}
res.status(200).send('OK');
}
// Webhook endpoints (support both direct and /back-prefixed routing)
app.post('/api/v1/discord-bot', webhookHandler);
app.post('/back/api/v1/discord-bot', webhookHandler);
async function handleIssueOpened(payload) {
const repoName = payload.repository.full_name;
const repoKey = String(repoName).toLowerCase();
const item = payload.issue;
// Prefer canonical match, fallback to legacy repoName match (case-insensitive) for existing DB entries.
let links = await RepoLink.find({ repoKey });
if (!links.length) {
links = await RepoLink.find({ repoName: new RegExp(`^${repoName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, 'i') });
}
if (!links.length) {
console.log(`β No link found for repo ${repoName} (key: ${repoKey})`);
return;
}
// Extract labels
const labels = item.labels.map(l => l.name);
const labelsText = labels.length > 0 ? labels.join(', ') : 'None';
// Extract points from labels (e.g., "points: 10")
let points = 'Not specified';
let pointsValue = 0;
for (const label of labels) {
const match = label.match(/points:\s*(\d+)/i);
if (match) {
points = match[1];
pointsValue = parseInt(match[1], 10);
break;
}
}
// Determine type based on labels
let type = 'FCFS (First come first serve)';
if (labels.some(l => l.toLowerCase().includes('ofa') || l.toLowerCase().includes('open-for-all'))) {
type = 'Open for all';
} else if (labels.some(l => l.toLowerCase().includes('compe') || l.toLowerCase().includes('competitive'))) {
type = 'Competitive';
}
// Determine embed color based on points (higher points = more important color)
// Default green
let color = 0x00ff00;
// Red for very high points
if (pointsValue >= 31) {
color = 0xff0000;
// Orange for high points
} else if (pointsValue >= 21) {
color = 0xffa500;
// Yellow for medium points
} else if (pointsValue >= 11) {
color = 0xffff00;
}
// Truncate description to max 5 lines
let description = item.body || 'No description provided.';
const lines = description.split('\n');
if (lines.length > 5) {
description = lines.slice(0, 5).join('\n') + '\n...';
}
const embed = {
author: {
name: item.user.login,
icon_url: item.user.avatar_url,
url: item.user.html_url,
},
title: `Issue #${item.number}`,
url: item.html_url,
description: `**${item.title}**\n\n${description}`,
color: color,
fields: [
{ name: 'Repository', value: `[${payload.repository.full_name}](${payload.repository.html_url})`, inline: true },
{ name: 'Labels', value: labelsText || 'None', inline: true },
{ name: 'Points', value: points, inline: true },
{ name: 'Type', value: type, inline: true },
{ name: 'State', value: item.state, inline: true },
],
image: {
url: `https://opengraph.githubassets.com/1/${payload.repository.full_name}/issues/${item.number}`,
},
footer: {
text: 'Created',
},
timestamp: item.created_at,
};
for (const link of links) {
console.log(`β
Found link for repo ${repoName}, posting to channel ${link.channelId} (guild ${link.guildId})`);
const guild = client.guilds.cache.get(link.guildId);
if (!guild) {
console.log('β Guild not found');
continue;
}
const channel = guild.channels.cache.get(link.channelId);
if (!channel) {
console.log('β Channel not found');
continue;
}
// Pick a random announcement message based on issue characteristics
const availableMessages = getIssueMessages(labels, pointsValue);
const randomMsg = availableMessages[Math.floor(Math.random() * availableMessages.length)];
// Create role mentions
let roleMentions = '';
if (link.mentionRoles && link.mentionRoles.length > 0) {
roleMentions = link.mentionRoles
.filter(roleId => {
const role = guild.roles.cache.get(roleId);
return role && !['Mentor', 'Contributor'].includes(role.name);
})
.map(roleId => `<@&${roleId}>`)
.join(' ') + ' ';
}
// Send greeting and announcement (only if ENABLE_ISSUE_MESSAGES is true)
if (ENABLE_ISSUE_MESSAGES === 'true') {
await channel.send(`π Hello Contributors! ${roleMentions}\n\n${randomMsg}`);
// Send the embed
await channel.send({ embeds: [embed] });
console.log(`π€ Posted issue ${item.number} in ${channel.name}`);
}
}
}
async function handleIssueLabeled(payload) {
const label = payload.label?.name ? String(payload.label.name).toLowerCase() : '';
if (label !== 'bounty') {
return;
}
const repoName = payload.repository.full_name;
const repoKey = String(repoName).toLowerCase();
const item = payload.issue;
// Prefer canonical match, fallback to legacy repoName match (case-insensitive) for existing DB entries.
let links = await RepoLink.find({ repoKey });
if (!links.length) {
links = await RepoLink.find({ repoName: new RegExp(`^${repoName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, 'i') });
}
if (!links.length) {
console.log(`β No link found for repo ${repoName} (key: ${repoKey})`);
return;
}
// Extract labels
const labels = item.labels.map(l => l.name);
const labelsText = labels.length > 0 ? labels.join(', ') : 'None';
// Extract points from labels (e.g., "points: 10")
let points = 'Not specified';
let pointsValue = 0;
for (const label of labels) {
const match = label.match(/points:\s*(\d+)/i);
if (match) {
points = match[1];
pointsValue = parseInt(match[1], 10);
break;
}
}
// Determine type based on labels
let type = 'FCFS (First come first serve)';
if (labels.some(l => l.toLowerCase().includes('ofa') || l.toLowerCase().includes('open-for-all'))) {
type = 'Open for all';
} else if (labels.some(l => l.toLowerCase().includes('compe') || l.toLowerCase().includes('competitive'))) {
type = 'Competitive';
}
// Determine embed color based on points (higher points = more important color)
// Default green
let color = 0x00ff00;
// Red for very high points
if (pointsValue >= 31) {
color = 0xff0000;
// Orange for high points
} else if (pointsValue >= 21) {
color = 0xffa500;
// Yellow for medium points
} else if (pointsValue >= 11) {
color = 0xffff00;
}
// Truncate description to max 5 lines
let description = item.body || 'No description provided.';
const lines = description.split('\n');
if (lines.length > 5) {
description = lines.slice(0, 5).join('\n') + '\n...';
}
const embed = {
author: {
name: item.user.login,
icon_url: item.user.avatar_url,
url: item.user.html_url,
},
title: `Bounty Issue #${item.number}`,
url: item.html_url,
description: `**${item.title}**\n\n${description}`,
color: color,
fields: [
{ name: 'Repository', value: `[${payload.repository.full_name}](${payload.repository.html_url})`, inline: true },
{ name: 'Labels', value: labelsText || 'None', inline: true },
{ name: 'Points', value: points, inline: true },
{ name: 'Type', value: type, inline: true },
{ name: 'State', value: item.state, inline: true },
],
image: {
url: `https://opengraph.githubassets.com/1/${payload.repository.full_name}/issues/${item.number}`,
},
footer: {
text: 'Bounty Added',
},
timestamp: new Date().toISOString(),
};
for (const link of links) {
console.log(`β
Found link for repo ${repoName}, posting bounty to channel ${link.channelId} (guild ${link.guildId})`);
const guild = client.guilds.cache.get(link.guildId);
if (!guild) {
console.log('β Guild not found');
continue;
}
const channel = guild.channels.cache.get(link.channelId);
if (!channel) {
console.log('β Channel not found');
continue;
}
// Pick a random bounty announcement message
const availableMessages = getBountyMessages(labels, pointsValue);
const randomMsg = availableMessages[Math.floor(Math.random() * availableMessages.length)];
// Create role mentions
let roleMentions = '';
if (link.mentionRoles && link.mentionRoles.length > 0) {
roleMentions = link.mentionRoles
.filter(roleId => {
const role = guild.roles.cache.get(roleId);
return role && !['Mentor', 'Contributor'].includes(role.name);
})
.map(roleId => `<@&${roleId}>`)
.join(' ') + ' ';
}
// Send greeting and announcement (only if ENABLE_ISSUE_MESSAGES is true)
if (ENABLE_ISSUE_MESSAGES === 'true') {
await channel.send(`π° Bounty Alert! ${roleMentions}\n\n${randomMsg}`);
// Send the embed
await channel.send({ embeds: [embed] });
console.log(`π€ Posted bounty for issue ${item.number} in ${channel.name}`);
}
}
}
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
// creating a cooldown collection
client.cooldowns = new Collection();
// reading all of the slash commands from the commands/ directory
// then activating them
client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
// reading all of the events from the event/ directory
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter((file) => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// Log in to Discord with your client's DISCORD_TOKEN
client.login(DISCORD_TOKEN);
// Start the Express server for webhooks
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Webhook server listening on port ${PORT}`);
});