-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathindex.ts
More file actions
416 lines (360 loc) · 11.2 KB
/
index.ts
File metadata and controls
416 lines (360 loc) · 11.2 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
import type {
Message,
CollectorFilter,
TextChannel,
DMChannel,
NewsChannel,
Guild,
Client,
ThreadChannel,
CommandInteraction,
} from 'discord.js';
import { MessageButton } from 'discord.js';
import {
MessageActionRow,
} from 'discord.js';
import { filter } from 'domyno';
import type { CommandDataWithHandler } from '../../../types';
import { SERVER_ID } from '../../env.js';
import { cache } from '../../spam_filter/index.js';
import { MultistepForm } from '../../utils/MultistepForm.js';
import { asyncCatch } from '../../utils/asyncCatch.js';
import { createEmbed, createMarkdownCodeBlock } from '../../utils/discordTools.js';
import { lock, unlock } from '../../utils/dmLock';
import { map } from '../../utils/map.js';
import { pipe } from '../../utils/pipe.js';
import { capitalize } from '../../utils/string.js';
import {
AWAIT_MESSAGE_TIMEOUT,
JOB_POSTINGS_CHANNEL,
POST_LIMITER,
POST_LIMITER_IN_HOURS,
} from './env.js';
import { questions } from './questions.v2.js';
const dateFormatter = new Intl.DateTimeFormat('en-US', {
month: 'long',
weekday: 'long',
day: '2-digit',
year: 'numeric',
});
export type OutputField = {
name: string;
value: string;
inline: boolean;
};
type Metadata = {
username: string;
discriminator: string;
msgID?: string;
userID?: string;
};
type Channel = TextChannel | NewsChannel | DMChannel;
type Answers = Map<string, string>;
type CacheEntry = {
key: string;
value: Date;
};
const getCurrentDate = () => {
return dateFormatter.format(Date.now());
};
/*
The `capitalize` function does **not** capitalize only one word in a string.
It capitalizes all words present in the string itself, separated with a space.
*/
const getTargetChannel = (
guild: Guild,
name: string
): TextChannel | ThreadChannel =>
guild.channels.cache.get(name) as
| TextChannel
| ThreadChannel;
const generateURL = (guildID: string, channelID: string, msgID: string) =>
`https://discordapp.com/channels/${guildID}/${channelID}/${msgID}`;
const getReply = async (
channel: DMChannel,
filter: CollectorFilter<[Message]>,
timeMultiplier = 1
) => {
try {
const res = await channel.awaitMessages({
filter,
max: 1,
time: AWAIT_MESSAGE_TIMEOUT * timeMultiplier,
});
const content = res.first().content.trim();
return content.toLowerCase() === 'cancel' ? false : content; // Return false if the user explicitly cancels the form
} catch {
channel.send('You have timed out. Please try again.');
}
};
const sendAlert = (
guild: Guild,
userInput: string,
{ username, discriminator }: Metadata
): void => {
const targetChannel = getTargetChannel(guild, JOB_POSTINGS_CHANNEL);
if (!targetChannel) {
// eslint-disable-next-line no-console
console.warn(
'env.MOD_CHANNEL does not exist on this server - via post.sendAlert'
);
return;
}
const userTag = createUserTag(username, discriminator);
try {
targetChannel.send({
embeds: [
createEmbed({
description:
'A user attempted creating a job post whilst providing invalid compensation.',
fields: [
{
inline: true,
name: 'User',
value: userTag,
},
{
inline: false,
name: 'Input',
value: createMarkdownCodeBlock(userInput),
},
{
inline: false,
name: 'Command',
value: createMarkdownCodeBlock(
`?ban ${userTag} Invalid compensation.`
),
},
{
inline: false,
name: 'Message Link',
value: 'DM Channel - Not Applicable.',
},
],
footerText: 'Job Posting Module',
provider: 'spam',
title: 'Alert!',
url: 'https://discord.gg/',
}).embed,
],
});
} catch (error) {
// eslint-disable-next-line no-console
console.error('post.sendAlert', error);
}
};
const generateFields = pipe<Answers, Iterable<OutputField>>([
filter(
([key, val]: [string, string]) =>
!['guidelines'].includes(key) && !(key === 'remote' && val.toLowerCase() === 'onsite')
),
map(([key, val]: [string, string]): OutputField => {
let value = val;
switch (key) {
case 'compensation':
value = val
break;
case 'compensation_type':
value = capitalize(val)
break;
case 'remote':
value = val === 'remote' ? "Yes" : "No";
break;
}
return {
inline: false,
name: capitalize(key.replace('_', ' ')),
value: createMarkdownCodeBlock(value.replace(/```/g,'')),
};
}),
]);
const createUserTag = (username: string, discriminator: string) =>
`${username}#${discriminator}`;
const createJobPost = async (
answers: Answers,
guild: Guild,
{ username, discriminator, userID }: Metadata
) => {
const targetChannel = getTargetChannel(guild, JOB_POSTINGS_CHANNEL);
if (!targetChannel) {
// eslint-disable-next-line no-console
console.warn(
'env.JOB_POSTINGS_CHANNEL does not exist on this server - via post.createJobPost'
);
return;
}
const user = createUserTag(username, discriminator);
// const url = generateURL(guild.id, channelID, msgID);
try {
const msg = await targetChannel.send({
content: `Job Poster: <@${userID}>`,
embeds: [
createEmbed({
author: {
name: user,
},
description: `A user has created a new job post!`,
// Using the spam provider because we only need the color/icon, which it provides anyway
fields: [
{
inline: true,
name: 'Created On',
value: getCurrentDate(),
},
...generateFields(answers),
],
footerText: 'Job Posting Module',
provider: 'spam',
title: 'New Job Post',
// url, doesn't seem to serve a purpose due to !post messages no longer existing and also never really used anyway
}).embed,
],
components: [
new MessageActionRow().addComponents(
new MessageButton()
.setCustomId(`job🤔${userID}🤔response`)
.setStyle('PRIMARY')
.setLabel('DM me the posting')
.setEmoji('✉️'),
new MessageButton()
.setCustomId(`job🤔${userID}🤔delete`)
.setStyle('SECONDARY')
.setLabel('Delete my post (poster only)')
.setEmoji('🗑')
),
],
});
return generateURL(guild.id, msg.channel.id, msg.id);
} catch (error) {
// eslint-disable-next-line no-console
console.error('post.createJobPost', error);
}
};
const generateCacheEntry = (key: string): CacheEntry => ({
key: `jp-${key}`, // JP stands for Job Posting, for the sake of key differentiation
value: new Date(),
});
const calcNextPostingThreshold = (diff: number) => {
if (diff === 0) {
return 'in a bit';
}
return diff === 1 ? 'in an hour' : `in ${diff} hours`;
};
const handleJobPostingRequest = async (
client: Client,
interaction: CommandInteraction
): Promise<void> => {
const { guild, member } = interaction;
const { user: author } = interaction;
const { username, discriminator, id: userID } = author;
const filter: CollectorFilter<[Message]> = m => m.author.id === userID;
const send = (str: string) => author.send(str);
// Generate cache entry
const entry = generateCacheEntry(userID);
try {
// Check if the user has been cached
const isCached = cache.get(entry.key);
if (isCached) {
const diff =
Number.parseInt(POST_LIMITER_IN_HOURS) -
Math.abs(Date.now() - entry.value.getTime()) / 3_600_000;
interaction.reply({
content: `You cannot create a job posting right now.\nPlease try again ${calcNextPostingThreshold(
diff
)}.`,
ephemeral: true,
});
return;
}
cache.set(entry.key, entry.value, POST_LIMITER);
await interaction.reply({
content: `I've DMed you to start the process.`,
ephemeral: true,
});
// Notify the user regarding the rules, and get the channel
const channel = await author.createDM();
const form = new MultistepForm(questions, channel, author);
lock(guild.id, userID, 'JOB_POST_FORM')
const answers = (await form.getResult('guidelines')) as unknown as Answers;
unlock(guild.id, userID, 'JOB_POST_FORM')
console.log(answers)
// Just return if the iteration breaks due to invalid input
if (!answers) {
cache.del(entry.key)
return;
}
const url = await createJobPost(answers, guild, {
discriminator,
userID,
username,
});
// Notify the user that the form is now complete
await send(`Your job posting has been created!\n${url}`);
// Store the job post in the cache
cache.set(entry.key, entry.value, POST_LIMITER);
} catch (error) {
cache.del(entry.key)
interaction.reply(
'Please temporarily enable direct messages as the bot cares about your privacy.'
);
// eslint-disable-next-line no-console
console.error('post.handleJobPostingRequest', error);
}
};
export const jobPostCommand: CommandDataWithHandler = {
name: 'post',
description: 'Start the process of creating a new job post',
handler: handleJobPostingRequest,
guildValidate: (guild) => guild.id === SERVER_ID,
onAttach: client => {
client.on('interactionCreate', asyncCatch(async interaction => {
if (!interaction.isButton()) {
return;
}
const [category, userId, type] = interaction.customId.split('🤔');
if (category !== 'job') {
return;
}
const message = await interaction.channel.messages.fetch(interaction.message.id)
if (type === 'delete') {
if (interaction.user.id !== userId) {
interaction.reply({
content: "You don't have permission to delete this post",
ephemeral: true,
});
return;
}
await message.delete();
interaction.reply({
content: 'Your job post was deleted',
ephemeral: true,
});
}
if (type === 'response') {
await interaction.deferReply({ ephemeral: true });
const dmChannel = await interaction.user.createDM();
try {
dmChannel.send({
content: `The user you want to DM is <@!${userId}>. The job posting can be found here: ${message.url}.\nA copy of the job posting is below for reference as well`,
embeds: message.embeds
});
interaction.editReply({
content: 'Please check your dms',
components: [
new MessageActionRow().addComponents(
new MessageButton()
.setStyle('LINK')
.setURL(`https://discord.com/channels/@me/${dmChannel.id}`)
.setLabel('Go to DMs')
),
],
});
} catch {
interaction.editReply(
`I tried to send you a DM but your DMs appear to be off. Heres the user you wish to DM <@${userId}>. If that doesn't work, please enable your DMs and try again.`
);
}
}
}));
},
};