-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
479 lines (396 loc) · 13.1 KB
/
Copy pathapp.js
File metadata and controls
479 lines (396 loc) · 13.1 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
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
import 'dotenv/config';
import {
ActionRowBuilder,
ChannelSelectMenuBuilder,
ChannelType,
Client,
Events,
GatewayIntentBits,
PermissionFlagsBits,
MessageFlags,
Message
} from 'discord.js';
import {
maybePostMonthlyTranslatorLeaderboard,
postTranslatorLeaderboard,
} from './translator-leaderboard.js';
const MOVE_WEBHOOK_NAME = 'Whoop Move Relay';
const MOVE_TARGET_CHANNEL_TYPES = [
ChannelType.GuildText,
ChannelType.GuildAnnouncement,
ChannelType.GuildForum,
ChannelType.PublicThread,
ChannelType.PrivateThread,
ChannelType.AnnouncementThread,
];
const MONTHLY_LEADERBOARD_CHECK_INTERVAL_MS = 60 * 60 * 1000;
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
],
});
client.once(Events.ClientReady, (c) => {
console.log(`Logged in as ${c.user.tag}`);
const weblateKey = process.env.WEBLATE_KEY;
if (!weblateKey) {
console.warn('WEBLATE_KEY is not configured; translator leaderboard is disabled.');
return;
}
maybePostMonthlyTranslatorLeaderboard(c, weblateKey).catch((error) => {
console.error('Failed to run monthly translator leaderboard:', error);
});
setInterval(() => {
maybePostMonthlyTranslatorLeaderboard(c, weblateKey).catch((error) => {
console.error('Failed to run monthly translator leaderboard:', error);
});
}, MONTHLY_LEADERBOARD_CHECK_INTERVAL_MS).unref();
});
function hasMoveAccess(member) {
return (
member.permissions.has(PermissionFlagsBits.Administrator) ||
member.roles.cache.some((role) => role.name.toLowerCase() === 'moderator')
);
}
function createMoveCustomId(userId, sourceChannelId, messageId) {
return `move:${userId}:${sourceChannelId}:${messageId}`;
}
function parseMoveCustomId(customId) {
const [action, userId, sourceChannelId, messageId] = customId.split(':');
if (action !== 'move' || !userId || !sourceChannelId || !messageId) {
return null;
}
return { userId, sourceChannelId, messageId };
}
function isGuildTextMessageChannel(channel) {
return channel?.isTextBased() && 'messages' in channel && channel.guild;
}
function isSupportedMoveTarget(channel) {
return channel?.guild && MOVE_TARGET_CHANNEL_TYPES.includes(channel.type);
}
function hasWebhookMethods(channel) {
return (
channel &&
typeof channel.fetchWebhooks === 'function' &&
typeof channel.createWebhook === 'function'
);
}
function createForumThreadName(message) {
const baseName = message.content
.replace(/\s+/g, ' ')
.trim()
.slice(0, 90);
if (baseName.length > 0) {
return baseName;
}
return `Moved message from ${message.author.username}`;
}
function getWebhookTarget(channel) {
if (channel.type === ChannelType.GuildForum) {
if (!hasWebhookMethods(channel)) {
throw new Error('Target forum channel does not support webhooks.');
}
return {
webhookChannel: channel,
threadId: undefined,
threadName: undefined,
};
}
if (channel.isThread()) {
if (!channel.parent || !hasWebhookMethods(channel.parent)) {
throw new Error('Target thread does not have a webhook-capable parent channel.');
}
return {
webhookChannel: channel.parent,
threadId: channel.id,
threadName: undefined,
};
}
if (!hasWebhookMethods(channel)) {
throw new Error('Target channel does not support webhooks.');
}
return {
webhookChannel: channel,
threadId: undefined,
threadName: undefined,
};
}
async function getOrCreateMoveWebhook(clientUserId, channel) {
const webhooks = await channel.fetchWebhooks();
const existingWebhook = webhooks.find(
(webhook) => webhook.owner?.id === clientUserId && webhook.name === MOVE_WEBHOOK_NAME,
);
if (existingWebhook) {
return existingWebhook;
}
return channel.createWebhook({
name: MOVE_WEBHOOK_NAME,
reason: 'Relay messages for the Move context command',
});
}
async function replayMessageWithWebhook(message, targetChannel) {
const { webhookChannel, threadId } = getWebhookTarget(targetChannel);
const webhook = await getOrCreateMoveWebhook(message.client.user.id, webhookChannel);
const files = [...message.attachments.values()].map((attachment) => ({
attachment: attachment.url,
name: attachment.name ?? `attachment-${attachment.id}`,
}));
const embeds = message.embeds.map((embed) => embed.toJSON());
const content = message.content.trim();
if (!content && embeds.length === 0 && files.length === 0) {
throw new Error('This message has no content, embeds, or attachments that can be moved.');
}
return webhook.send({
content: content || undefined,
username: message.member?.displayName ?? message.author.globalName ?? message.author.username,
avatarURL: message.author.displayAvatarURL(),
embeds,
files,
allowedMentions: { parse: [] },
threadId,
threadName: targetChannel.type === ChannelType.GuildForum ? createForumThreadName(message) : undefined,
});
}
function canManageSourceMessage(channel, botMember) {
const permissions = channel.permissionsFor(botMember);
return permissions?.has([
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.ManageMessages,
]);
}
function canUseTargetWebhook(channel, botMember) {
const { webhookChannel } = getWebhookTarget(channel);
const permissions = webhookChannel.permissionsFor(botMember);
return permissions?.has([
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ManageWebhooks,
]);
}
async function handleMoveCommand(interaction) {
if (!interaction.inGuild()) {
await interaction.reply({
content: 'The Move command can only be used inside a server.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!hasMoveAccess(member)) {
await interaction.reply({
content: 'Only moderators or administrators can move messages.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
if (!isGuildTextMessageChannel(interaction.targetMessage.channel)) {
await interaction.reply({
content: 'That message is not in a supported source channel.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
const selector = new ChannelSelectMenuBuilder()
.setCustomId(
createMoveCustomId(
interaction.user.id,
interaction.targetMessage.channelId,
interaction.targetMessage.id,
),
)
.setPlaceholder('Choose a destination channel or thread')
.setMinValues(1)
.setMaxValues(1)
.addChannelTypes(...MOVE_TARGET_CHANNEL_TYPES);
const row = new ActionRowBuilder().addComponents(selector);
await interaction.reply({
content: ``,
components: [row],
messageFlags: MessageFlags.Ephemeral
});
}
async function handleMoveSelection(interaction) {
const moveContext = parseMoveCustomId(interaction.customId);
if (!moveContext) {
await interaction.reply({
content: 'That move request is invalid.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
if (moveContext.userId !== interaction.user.id) {
await interaction.reply({
content: 'Only the moderator who opened this move menu can use it.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
await interaction.deferUpdate();
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!hasMoveAccess(member)) {
await interaction.editReply({
content: 'You no longer have permission to move messages.',
components: [],
});
return;
}
const sourceChannel = await interaction.client.channels.fetch(moveContext.sourceChannelId);
if (!isGuildTextMessageChannel(sourceChannel)) {
await interaction.editReply({
content: 'The original channel is no longer available.',
components: [],
});
return;
}
const targetChannel = await interaction.client.channels.fetch(interaction.values[0]);
if (!isSupportedMoveTarget(targetChannel)) {
await interaction.editReply({
content: 'Please choose a text channel, thread, or forum channel in this server.',
components: [],
});
return;
}
if (targetChannel.guildId !== interaction.guildId) {
await interaction.editReply({
content: 'The destination must be in the same server.',
components: [],
});
return;
}
if (sourceChannel.id === targetChannel.id) {
await interaction.editReply({
content: 'The destination must be different from the source channel.',
components: [],
});
return;
}
const botMember = interaction.guild.members.me;
if (!botMember) {
await interaction.editReply({
content: 'The bot member could not be resolved in this server.',
components: [],
});
return;
}
if (!canManageSourceMessage(sourceChannel, botMember)) {
await interaction.editReply({
content: 'The bot needs View Channel, Read Message History, and Manage Messages in the source channel.',
components: [],
});
return;
}
if (!canUseTargetWebhook(targetChannel, botMember)) {
await interaction.editReply({
content: 'The bot needs View Channel and Manage Webhooks in the destination channel or its parent channel.',
components: [],
});
return;
}
let sourceMessage;
try {
sourceMessage = await sourceChannel.messages.fetch(moveContext.messageId);
} catch {
await interaction.editReply({
content: 'The original message could not be found. It may already be deleted.',
components: [],
});
return;
}
try {
await replayMessageWithWebhook(sourceMessage, targetChannel);
await sourceMessage.delete();
await interaction.deleteReply();
} catch (error) {
console.error('Failed to move message:', error);
await interaction.editReply({
content: `Move failed: ${error.message}`,
components: [],
});
}
}
async function handleTranslatorLeaderboardCommand(interaction) {
if (!interaction.inGuild()) {
await interaction.reply({
content: 'The testleaderboard command can only be used inside a server.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!member.permissions.has(PermissionFlagsBits.Administrator)) {
await interaction.reply({
content: 'Only administrators can use this command.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
const weblateKey = process.env.WEBLATE_KEY;
if (!weblateKey) {
await interaction.reply({
content: 'WEBLATE_KEY is not configured for the bot.',
messageFlags: MessageFlags.Ephemeral
});
return;
}
await interaction.deferReply({ messageFlags: MessageFlags.Ephemeral });
try {
const period = await postTranslatorLeaderboard(interaction.guild, weblateKey);
await interaction.editReply(`Posted the translator leaderboard for ${period.label} in #hangar.`);
} catch (error) {
console.error('Failed to post translator leaderboard:', error);
await interaction.editReply(`Could not post translator leaderboard: ${error.message}`);
}
}
// Greet new members via DM
client.on(Events.GuildMemberAdd, async (member) => {
// Find channels by name
const introductions = member.guild.channels.cache.find(
(ch) => ch.name.indexOf('introductions') !== -1,
);
const help = member.guild.channels.cache.find(
(ch) => ch.name.indexOf('help') !== -1,
);
const introLink = introductions ? `<#${introductions.id}>` : 'introductions';
const helpLink = help ? `<#${help.id}>` : '#help';
const message =
`Hey ${member.user.username} :wave: welcome to the WebODM Community! If you want to connect with others check ${introLink} ` +
`Feel free to look around! If you need help, open a topic in ${helpLink}. Be polite, respect others. Have fun! `;
try {
await member.send(message);
console.log(`Greeted ${member.user.tag}`);
} catch (err) {
console.error(`Could not DM ${member.user.tag}:`, err.message);
}
});
// Handle /ping slash command
client.on(Events.InteractionCreate, async (interaction) => {
try {
if (interaction.isChatInputCommand() && interaction.commandName === 'ping') {
await interaction.reply('pong!');
return;
}
if (interaction.isChatInputCommand() && interaction.commandName === 'testleaderboard') {
await handleTranslatorLeaderboardCommand(interaction);
return;
}
if (interaction.isMessageContextMenuCommand() && interaction.commandName === 'Move') {
await handleMoveCommand(interaction);
return;
}
if (interaction.isChannelSelectMenu() && interaction.customId.startsWith('move:')) {
await handleMoveSelection(interaction);
}
} catch (error) {
console.error('Interaction handling failed:', error);
const replyPayload = {
content: 'Something went wrong while handling that interaction.',
messageFlags: MessageFlags.Ephemeral
};
if (interaction.deferred || interaction.replied) {
await interaction.followUp(replyPayload).catch(() => null);
return;
}
await interaction.reply(replyPayload).catch(() => null);
}
});
client.login(process.env.DISCORD_TOKEN);