-
-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathmessageCreate.ts
318 lines (255 loc) Β· 12.4 KB
/
messageCreate.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
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
/*!
* @author TRACTION (iamtraction)
* @copyright 2022
*/
import { ChannelType, Message, Snowflake, Team, ThreadAutoArchiveDuration } from "discord.js";
import { Client, Listener, Logger } from "@bastion/tesseract";
import GuildModel, { Guild as GuildDocument } from "../models/Guild";
import MemberModel from "../models/Member";
import RoleModel from "../models/Role";
import TriggerModel from "../models/Trigger";
import { COLORS } from "../utils/constants";
import { generate as generateEmbed } from "../utils/embeds";
import * as gamification from "../utils/gamification";
import * as members from "../utils/members";
import * as numbers from "../utils/numbers";
import * as regex from "../utils/regex";
import * as variables from "../utils/variables";
import * as yaml from "../utils/yaml";
import { bastion } from "../types";
class MessageCreateListener extends Listener<"messageCreate"> {
public activeUsers: Map<Snowflake, Snowflake[]>;
constructor() {
super("messageCreate");
this.activeUsers = new Map<Snowflake, Snowflake[]>();
}
handleLevelRoles = async (message: Message, level: number): Promise<void> => {
const roles = await RoleModel.find({
guild: message.guild.id,
level: { $exists: true, $ne: null },
});
// check whether there are any level up roles
if (!roles?.length) return;
// get the nearest level for which roles are available
const nearestLevel = numbers.smallestNeighbor(level, roles.map(r => r.level));
// identify valid roles
const levelRoles = roles.filter(r => r.level === nearestLevel && message.guild.roles.cache.has(r._id));
const extraRoles = roles.filter(r => r.level !== nearestLevel && message.guild.roles.cache.has(r._id));
// update member roles
if (levelRoles.length) {
const memberRoles = message.member.roles.cache
.filter(r => extraRoles.some(doc => doc.id === r.id)) // remove roles from any other level
.map(r => r.id)
.concat(levelRoles.map(doc => doc.id)); // add roles in the current level
// update member roles
message.member.roles.set(memberRoles).catch(Logger.error);
}
};
handleGamification = async (message: Message<true>, guildDocument: GuildDocument): Promise<void> => {
// get recent users
const activeUsers = this.activeUsers.get(message.guild.id) || [];
// check whether the member had recently gained XP
if (activeUsers.includes(message.author.id)) return;
// find member document or create a new one
const memberDocument = await MemberModel.findOneAndUpdate({ user: message.author.id, guild: message.guildId }, {}, { new: true, upsert: true });
// check whether gamification is enabled
if (!guildDocument.gamification) return;
// check whether member has exceeded max level or experience
if (memberDocument.level >= gamification.MAX_LEVEL || memberDocument.experience >= gamification.MAX_EXPERIENCE(guildDocument.gamificationMultiplier)) return;
// increment experience
memberDocument.experience = message.member.premiumSinceTimestamp ? memberDocument.experience + 2 : memberDocument.experience + 1;
// compute current level from new experience
const computedLevel: number = gamification.computeLevel(memberDocument.experience, guildDocument.gamificationMultiplier);
// level up
if (computedLevel > memberDocument.level) {
// credit reward amount into member's account
await members.updateBalance(memberDocument, computedLevel * gamification.DEFAUL_CURRENCY_REWARD_MULTIPLIER);
// achievement message
if (guildDocument.gamificationMessages) {
message.reply((message.client as Client).locales.getText(message.guild.preferredLocale, "leveledUp", { level: `Level ${ computedLevel }` }))
.catch(Logger.ignore);
}
// reward level roles, if available
this.handleLevelRoles(message, computedLevel)
.catch(Logger.error);
}
// update level
memberDocument.level = computedLevel;
// save document
await memberDocument.save();
// add to recent users
activeUsers.push(message.author.id);
this.activeUsers.set(message.guildId, activeUsers);
// remove the user after cooldown period
setTimeout(() => {
const activeUsers = this.activeUsers.get(message.guildId);
activeUsers.splice(activeUsers.indexOf(message.author.id), 1);
this.activeUsers.set(message.guildId, activeUsers);
}, 13e3).unref();
};
handleTriggers = async (message: Message<true>): Promise<unknown> => {
const triggers = await TriggerModel.find({ guild: message.guild.id });
// responses
const responseMessages: string[] = [];
const responseReactions: string[] = [];
for (const trigger of triggers) {
const patternRegExp = new RegExp(trigger.pattern.replace(/\?/g, ".").replace(/\*+/g, ".*"), "ig");
if (!patternRegExp.test(message.content)) continue;
if (trigger.message) {
responseMessages.push(trigger.message);
}
if (trigger.reactions) {
responseReactions.push(trigger.reactions);
}
}
// response message
if (responseMessages.length) {
const responseMessage = generateEmbed(variables.replace(responseMessages[Math.floor(Math.random() * responseMessages.length)], message));
if (typeof responseMessage === "string") {
return message.reply(responseMessage)
.catch(Logger.error);
}
return message.reply({
embeds: [ responseMessage ],
})
.catch(Logger.error);
}
// response reaction
if (responseReactions.length) {
message.react(responseReactions[Math.floor(Math.random() * responseReactions.length)])
.catch(Logger.error);
}
};
handleVotingChannel = async (message: Message<true>, guildDocument: GuildDocument): Promise<void> => {
// check whether channel has slow mode
if (!message.channel.rateLimitPerUser) return;
// check whether it's a voting channel
if (!guildDocument.votingChannels?.includes(message.channelId)) return;
// set the message up for voting
message.react("π").catch(Logger.ignore);
message.react("π").catch(Logger.ignore);
};
handleKarma = async (message: Message<true>, guildDocument: GuildDocument): Promise<void> => {
if (!message.content) return;
// check whether gamification is enabled
if (!guildDocument.gamification) return;
const mentiondUsers = message.mentions.users?.filter(u => u.id !== message.author.id);
if (mentiondUsers?.size && [ "thank you", "thankyou", "thanks" ].some(w => message.content.toLowerCase().includes(w))) {
const users = Array.from(mentiondUsers.keys());
await MemberModel.updateMany({
user: {
$in: users,
},
guild: message.guild.id,
}, {
$inc: {
karma: 1,
},
});
}
};
handleAutoThreads = async (message: Message<true>, guildDocument: GuildDocument): Promise<void> => {
if (!message.content) return;
// check whether the channel is valid
if (message.channel.type !== ChannelType.GuildText) return;
// check whether channel has slow mode
if (!message.channel.rateLimitPerUser) return;
// check whether auto threads is enabled in the channel
if (!guildDocument.autoThreadChannels?.includes(message.channelId)) return;
// create a new thread
const thread = await message.channel.threads.create({
type: ChannelType.PrivateThread,
name: message.member.displayName + " β " + new Date().toDateString(),
autoArchiveDuration: ThreadAutoArchiveDuration.OneDay,
reason: `Auto Thread for ${ message.author.tag }`,
invitable: true,
startMessage: message,
});
thread.send({
content: `Hello ${ message.author }!
\nThis thread has been automatically created from your message in the ${ message.channel } channel.
\n**Useful Commands**
β’ \`/thread name\` β Change the name of the thread.
β’ \`/thread close\` β Close and lock the thread once you're done.
\n*This thread will be automatically archived after 24 hours of inactivity.*`,
}).catch(Logger.ignore);
};
handleInstantResponses = async (message: Message): Promise<void> => {
if (!message.content) return;
const responses = yaml.parse("data", "responses.yaml");
for (const response of responses) {
if (response.messages.includes(message.content.toLowerCase())) {
const replies: string | string[] = response.responses[Math.floor(Math.random() * response.responses.length)];
message.reply(replies instanceof Array ? replies.join("\n") : replies)
.catch(Logger.ignore);
}
}
};
handleDirectMessageRelay = async (message: Message, relayDirectMessages: boolean | string): Promise<unknown> => {
if (!message.content) return;
// generate the message payload
const payload = {
embeds: [
{
color: COLORS.SECONDARY,
author: {
name: message.author.tag,
icon_url: message.author.displayAvatarURL(),
},
description: message.content,
footer: {
text: message.author.id,
},
},
],
};
// check whether the message should be relayed via webhook
if (typeof relayDirectMessages === "string") {
// match the string for a valid webhook url
const match = relayDirectMessages.match(regex.WEBHOOK_URL);
// check whether the match was a success
if (!(match instanceof Array)) return;
// get the webhook id & token from the matched array
const [ , webhookId, webhookToken ] = match;
// fetch the webhook
const webhook = await message.client.fetchWebhook(webhookId, webhookToken);
// relay the message via the webhook
return await webhook?.send(payload);
}
// get the application owner
const app = await message.client.application.fetch();
const owner = app.owner instanceof Team ? app.owner.owner.user : app.owner;
// check if the message author is same as the owner
if (message.author.id === owner.id) return;
const channel = await owner.createDM();
// relay the message to the application owner
await channel.send(payload);
};
public async exec(message: Message<boolean>): Promise<void> {
// check whether message author is a bot
if (message.author.bot) return;
if (message.inGuild()) {
const guildDocument = await GuildModel.findById(message.guildId);
// gamification
this.handleGamification(message, guildDocument).catch(Logger.error);
// message triggers
this.handleTriggers(message).catch(Logger.error);
// voting channel
this.handleVotingChannel(message, guildDocument).catch(Logger.error);
// karma
this.handleKarma(message, guildDocument).catch(Logger.error);
// auto threads
this.handleAutoThreads(message, guildDocument).catch(Logger.error);
} else {
const relayDirectMessages = process.env.BASTION_RELAY_DMS || ((message.client as Client).settings as bastion.Settings)?.relayDirectMessages;
if (relayDirectMessages) {
// relay direct messages
this.handleDirectMessageRelay(message, relayDirectMessages).catch(Logger.error);
} else {
// instant responses
this.handleInstantResponses(message).catch(Logger.error);
}
}
}
}
export = MessageCreateListener;