-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy paththreadThanks.ts
More file actions
242 lines (217 loc) · 6.79 KB
/
threadThanks.ts
File metadata and controls
242 lines (217 loc) · 6.79 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
import type {
ButtonInteraction,
Client,
CommandInteraction,
Message,
SelectMenuInteraction,
ThreadMember,
} from 'discord.js';
import {
MessageActionRow,
MessageButton,
Collection,
MessageSelectMenu,
} from 'discord.js';
import { POINT_LIMITER_IN_MINUTES } from '../../env.js';
import { asyncCatch } from '../../utils/asyncCatch.js';
import { _ } from '../../utils/pluralize.js';
import { createResponse } from './createResponse.js';
import type { ThanksInteractionType } from './db_model.js';
import { ThanksInteraction } from './db_model.js';
const memoryCache = new Map<string, Message>();
export async function handleThreadThanks(msg: Message): Promise<void> {
const { channel, author, id: msgId } = msg;
if (!channel.isThread()) {
return;
}
const oldResponseId = [author.id, channel.id].join('|');
if (memoryCache.has(oldResponseId)) {
await memoryCache
.get(oldResponseId)
.delete()
.catch(error => {
console.error('message already deleted');
})
.finally(() => {
memoryCache.delete(oldResponseId);
});
}
// channel.members.fetch should return a collection
const [members, previousInteractions]: [
Collection<string, ThreadMember>,
ThanksInteractionType[]
] = await Promise.all([
channel.members.fetch(undefined, { cache: false }) as unknown as Promise<
Collection<string, ThreadMember>
>,
ThanksInteraction.find({
thanker: author.id,
createdAt: {
$gte: Date.now() - Number.parseInt(POINT_LIMITER_IN_MINUTES) * 60_000,
},
}),
]);
const previouslyThankedIds = new Set(
previousInteractions.flatMap(x => x.thankees)
);
const alreadyThanked = [];
const otherMembers = members.filter(x => {
const notSelf = x.user.id !== author.id;
const notBot = !x.user.bot;
const notTimeout = !previouslyThankedIds.has(x.user.id);
if (!notTimeout) {
alreadyThanked.push(x);
}
return notSelf && notBot && notTimeout;
});
if (otherMembers.size === 0) {
return;
}
const response = await msg.reply({
content: [
"Hey, it looks like you're trying to thank one or many users, but haven't specified who. Who would you like to thank?",
alreadyThanked.length > 0
? _`There ${_.mapper({ 1: 'is' }, 'are')} **${_.n} user${_.s
} that you can't thank as you've thanked them recently**, so they won't show up as an option.`(
alreadyThanked.length
)
: '',
]
.filter(Boolean)
.join('\n'),
components: [
new MessageActionRow().addComponents(
new MessageSelectMenu()
.addOptions(
otherMembers.map(item => ({
label: item.guildMember.displayName,
value: item.user.id,
description: `${item.user.username}#${item.user.discriminator}`,
}))
)
.setMinValues(1)
.setCustomId(`threadThanks🤔${msgId}🤔select🤔${author.id}`)
),
new MessageActionRow().addComponents(
new MessageButton()
.setLabel('Nevermind')
.setStyle('SECONDARY')
.setCustomId(`threadThanks🤔${msgId}🤔cancel🤔${author.id}`)
),
],
});
if (channel?.id) {
memoryCache.set([author.id, channel.id].join('|'), response);
}
}
export function attachThreadThanksHandler(client: Client): void {
client.on(
'interactionCreate',
asyncCatch(async interaction => {
if (!(interaction.isSelectMenu() || interaction.isButton())) {
return;
}
const { channel, customId, user, message, guild } = interaction;
const [category, msgId, type, userId] = customId.split('🤔');
if (category !== 'threadThanks') {
return;
}
if (user.id !== userId) {
interaction.reply({
content: "That's not for you! That prompt is for someone else.",
ephemeral: true,
});
return;
}
if (type === 'cancel') {
await Promise.all([
channel.messages.delete(message.id),
interaction.reply({
content: 'Sure thing, message removed!',
ephemeral: true,
}),
]);
return;
}
if (type === 'select') {
const { values } = interaction as SelectMenuInteraction;
channel.messages.delete(message.id);
const msgPromise = channel.messages.fetch(msgId);
const thankedMembers = await guild.members.fetch({
user: values,
});
const thankedUsers = new Collection(
thankedMembers.map(item => [item.user.id, item.user])
);
const responseData = createResponse(thankedUsers, user.id, client);
let response: Message;
const msg = await msgPromise;
if (msg) {
response = await msg.reply(responseData);
} else {
response = await msg.channel.send(responseData);
}
const name = [channel.id, user.id].join('|');
if (memoryCache.has(name)) {
const item = memoryCache.get(name);
memoryCache.delete(name);
await item.delete();
}
if (channel.isThread() && channel.ownerId === user.id) {
sendCloseThreadQuery(interaction);
}
await ThanksInteraction.create({
thanker: userId,
guild: guild.id,
channel: channel.id,
thankees: thankedUsers.map(u => u.id),
responseMsgId: response.id,
});
}
})
);
}
function sendCloseThreadQuery(
interaction: SelectMenuInteraction | ButtonInteraction | CommandInteraction
) {
interaction.reply({
content: 'Would you like to archive this thread and mark it as resolved?',
components: [
new MessageActionRow().addComponents(
new MessageButton()
.setStyle('PRIMARY')
.setLabel('Yes please!')
.setCustomId(`closeThread🤔${interaction.channel.id}🤔close`)
),
],
ephemeral: true,
});
}
export function attachThreadClose(client: Client): void {
client.on(
'interactionCreate',
asyncCatch(async interaction => {
if (!interaction.isButton()) {
return;
}
const id = interaction.customId;
const msgId = interaction.message.id;
const [type, channelId, thankeeId] = id.split('🤔');
if (type !== 'closeThread') {
return;
}
await interaction.deferReply({ ephemeral: true });
const activeThreads =
await interaction.guild.channels.fetchActiveThreads();
const channel = activeThreads.threads.get(channelId);
if (!channel || channel.archived) {
interaction.reply({ content: '' });
}
await interaction.editReply({
content: 'Closed!',
});
await channel.setName(`✅ ${channel.name}`);
await channel.setArchived(true, 'Resolved!');
})
);
}