This repository has been archived by the owner on Apr 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfaq.ts
153 lines (149 loc) · 7.47 KB
/
faq.ts
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
import { Constants, Formatters, MessageSelectMenu, MessageButton, MessageActionRow, Message, type MessageContextMenuInteraction } from 'discord.js';
import { Discord as Utils } from '../../utils';
import DiscordClientError from '../error';
import { emojis } from '../../../config.json';
import type { ContextMenu } from '@discord/types';
import type { Discord } from '@typings/database';
import type { Filter } from 'mongodb';
const { isCachedMessageContextMenuInteraction } = Utils;
const command: ContextMenu<MessageContextMenuInteraction> = {
get name() {
return this.data.name;
},
set name(value) {
this.data.name = value;
},
cooldown: 15,
isAdministrator: false,
isGlobal: true,
data: {
name: "Search FAQ",
type: Constants.ApplicationCommandTypes.MESSAGE,
defaultPermission: true
},
async execute(interaction, { database }) {
await interaction.deferReply({ ephemeral: interaction.inCachedGuild() });
try {
const faqCollection = database.discord.collection<Discord.FAQ>("FAQ");
if (!interaction.targetMessage.content) throw new DiscordClientError(`${interaction.targetMessage instanceof Message ? Formatters.hyperlink("This message", interaction.targetMessage.url) : "This message"} has no content to search for...`);
const content = interaction.targetMessage.content.match(/[0-9a-zA-Z'-? ]/g).join("");
const filter: Filter<Discord.FAQ> = {
$text: { $search: content },
$or: [
{ public: true },
{ author: { $exists: false } }
]
};
if (interaction.inGuild()) filter.$or.push({ server: interaction.guildId });
const cursor = faqCollection.find(filter, {
sort: { score: { $meta: "textScore" } },
limit: 25
});
if (isCachedMessageContextMenuInteraction(interaction)) {
const documents = await cursor.toArray();
if (!documents.length) throw new DiscordClientError(`No FAQ results could be found with ${Formatters.hyperlink("this", interaction.targetMessage.url)} message...`);
const selectRow = new MessageActionRow({
components: [
new MessageSelectMenu({
customId: "faqSelect",
placeholder: "Select the FAQ to send...",
options: documents.map((doc, index) => ({
label: doc.question,
value: doc._id.toHexString(),
description: doc.answer.slice(0, 97) + (doc.answer.length > 97 ? "..." : ""),
emoji: emojis.help,
default: !index
}))
})
]
});
const buttonRow = new MessageActionRow({
components: [
new MessageButton({
style: "SUCCESS",
customId: "confirm",
label: "Confirm and send"
}),
new MessageButton({
style: "SUCCESS",
customId: "cancel",
label: "Cancel"
})
]
});
let currentDocument = documents[0];
const reply = await interaction.editReply({
content: `${Formatters.bold(currentDocument.question)}\n${currentDocument.answer}`,
components: [
selectRow,
buttonRow
]
});
const collector = reply.createMessageComponentCollector({
idle: 3 * 60 * 1000,
max: 9 * 60 * 1000
});
collector.on("collect", async componentInteraction => {
if (componentInteraction.isSelectMenu() && componentInteraction.customId === "faqSelect") {
const component = componentInteraction.component;
const [value] = componentInteraction.values;
component.options.forEach(option => {
option.default = option.value === value;
});
selectRow.setComponents(component);
currentDocument = documents.find(doc => doc._id.equals(value));
await componentInteraction.update({
content: `${Formatters.bold(currentDocument.question)}\n${currentDocument.answer}`,
components: [
selectRow,
buttonRow
]
});
} else if (componentInteraction.isButton()) {
await componentInteraction.deferUpdate();
collector.stop("selectedValue");
if (componentInteraction.customId === "confirm") {
await interaction.followUp({
content: `${Formatters.italic(`FAQ suggestion for ${Formatters.memberNicknameMention(interaction.targetMessage.author.id)}:`)}\n${Formatters.formatEmoji(emojis.help)} ${Formatters.bold(currentDocument.question + ":")}\n${Formatters.blockQuote(currentDocument.answer)}`,
allowedMentions: {
users: [interaction.targetMessage.author.id]
}
});
}
}
});
collector.once("end", async (collected) => {
selectRow.components.forEach(component => component.setDisabled(true));
buttonRow.components.forEach(component => component.setDisabled(true));
const reply = collected.last() ?? interaction;
await reply.editReply({
components: [
selectRow,
buttonRow
]
});
});
} else {
const doc = await cursor.tryNext();
if (!doc) throw new DiscordClientError("No FAQ results could be found with this message...");
await interaction.editReply({
content: `${Formatters.italic(`FAQ suggestion for ${Formatters.memberNicknameMention(interaction.targetMessage.author.id)}:`)}\n${Formatters.formatEmoji(emojis.help)} ${Formatters.bold(doc.question + ":")}\n${Formatters.blockQuote(doc.answer)}`,
allowedMentions: {
users: [interaction.targetMessage.author.id]
}
});
const hasNext = await cursor.hasNext();
if (hasNext) cursor.close();
}
}
catch(error) {
if (error instanceof DiscordClientError) {
await error.send(interaction);
} else {
console.error(`Error while executing ${interaction.commandName}`, error);
await DiscordClientError.sendUnknownError(interaction);
}
}
}
}
export = command;