/[sudobot]/trunk/src/commands/moderation/MuteCommand.ts
ViewVC logotype

Contents of /trunk/src/commands/moderation/MuteCommand.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 333 - (show annotations)
Mon Jul 29 17:29:35 2024 UTC (8 months, 2 weeks ago) by rakin
File MIME type: application/typescript
File size: 10075 byte(s)
refactor(hardmuting): use mongodb
1 import { BanOptions, CommandInteraction, GuildMember, Interaction, Message, Permissions, User } from 'discord.js';
2 import BaseCommand from '../../utils/structures/BaseCommand';
3 import DiscordClient from '../../client/Client';
4 import CommandOptions from '../../types/CommandOptions';
5 import InteractionOptions from '../../types/InteractionOptions';
6 import MessageEmbed from '../../client/MessageEmbed';
7 import getUser from '../../utils/getUser';
8 import History from '../../automod/History';
9 import getMember from '../../utils/getMember';
10 import ms from 'ms';
11 import { unmute } from './UnmuteCommand';
12 import PunishmentType from '../../types/PunishmentType';
13 import { hasPermission, shouldNotModerate } from '../../utils/util';
14
15 export async function mute(client: DiscordClient, dateTime: number | undefined, user: GuildMember, msg: Message | CommandInteraction, timeInterval: number | undefined, reason: string | undefined, hard: boolean = false) {
16 try {
17 const { default: Punishment } = await import('../../models/Punishment');
18
19 const { getTimeouts, clearTimeoutv2, setTimeoutv2 } = await import('../../utils/setTimeout');
20
21 const timeouts = getTimeouts();
22
23 for (const timeout of timeouts.values()) {
24 if (timeout.row.params) {
25 try {
26 const json = JSON.parse(timeout.row.params);
27
28 if (json) {
29 if (json[1] === user.id && timeout.row.filePath.endsWith('unmute-job')) {
30 await clearTimeoutv2(timeout);
31 }
32 }
33 }
34 catch (e) {
35 console.log(e);
36 }
37 }
38 }
39
40 if (dateTime && timeInterval) {
41 await client.db.get("INSERT INTO unmutes(user_id, guild_id, time) VALUES(?, ?, ?)", [user.id, msg.guild!.id, new Date(dateTime).toISOString()], async (err: any) => {
42 if (err)
43 console.log(err);
44
45 console.log('A timeout has been set.');
46
47 await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);
48 });
49 }
50
51 if (hard) {
52 const { default: Hardmute } = await import("../../models/Hardmute");
53 const roles = await user.roles.cache.filter(r => r.id !== msg.guild!.id);
54 await user.roles.remove(roles, reason);
55
56 await Hardmute.create({
57 user_id: user.id,
58 roles: roles.map(role => role.id),
59 guild_id: msg.guild!.id,
60 createdAt: new Date()
61 });
62 }
63
64 const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));
65 await user.roles.add(role!, reason);
66
67 await Punishment.create({
68 type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
69 user_id: user.id,
70 guild_id: msg.guild!.id,
71 mod_id: msg.member!.user.id,
72 mod_tag: (msg.member!.user as User).tag,
73 reason,
74 meta: {
75 time: timeInterval ? ms(timeInterval) : undefined
76 }
77 });
78
79 await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User, hard);
80
81 try {
82 await user.send({
83 embeds: [
84 new MessageEmbed()
85 .setAuthor({
86 iconURL: <string> msg.guild!.iconURL(),
87 name: `\tYou have been muted in ${msg.guild!.name}`
88 })
89 .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)
90 ]
91 });
92 }
93 catch (e) {
94 console.log(e);
95 }
96 }
97 catch (e) {
98 console.log(e);
99
100 if (msg instanceof Message)
101 await msg.reply({
102 embeds: [
103 new MessageEmbed()
104 .setColor('#f14a60')
105 .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
106 ]
107 });
108 else
109 await msg.editReply({
110 embeds: [
111 new MessageEmbed()
112 .setColor('#f14a60')
113 .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
114 ]
115 });
116
117 return;
118 }
119 }
120
121 export default class MuteCommand extends BaseCommand {
122 supportsInteractions: boolean = true;
123 permissions = [Permissions.FLAGS.MODERATE_MEMBERS];
124
125 constructor() {
126 super('mute', 'moderation', []);
127 }
128
129 async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {
130 if (!options.isInteraction && typeof options.args[0] === 'undefined') {
131 await msg.reply({
132 embeds: [
133 new MessageEmbed()
134 .setColor('#f14a60')
135 .setDescription(`This command requires at least one argument.`)
136 ]
137 });
138
139 return;
140 }
141
142 if (msg instanceof CommandInteraction)
143 await msg.deferReply();
144
145 let user: GuildMember;
146 let reason: string | undefined;
147 let time: string | undefined;
148 let timeInterval: number | undefined;
149 let dateTime: number | undefined;
150 let hard: boolean = false;
151
152 if (options.isInteraction) {
153 user = await <GuildMember> options.options.getMember('member');
154
155 if (options.options.getString('reason')) {
156 reason = await <string> options.options.getString('reason');
157 }
158
159 if (options.options.getBoolean('hardmute')) {
160 hard = await <boolean> options.options.getBoolean('hardmute');
161 }
162
163 if (options.options.getString('time')) {
164 time = await options.options.getString('time') as string;
165 timeInterval = await ms(time);
166
167 if (!timeInterval) {
168 await this.deferReply(msg, {
169 embeds: [
170 new MessageEmbed()
171 .setColor('#f14a60')
172 .setDescription(`Option \`-t\` (time) requires an argument which must be a valid time interval.`)
173 ]
174 });
175
176 return;
177 }
178 }
179 }
180 else {
181 const user2 = await getMember((msg as Message), options);
182
183 if (!user2) {
184 await this.deferReply(msg, {
185 embeds: [
186 new MessageEmbed()
187 .setColor('#f14a60')
188 .setDescription(`Invalid user given.`)
189 ]
190 });
191
192 return;
193 }
194
195 user = user2;
196
197 const index = await options.args.indexOf('-t');
198
199 if (options.args[1]) {
200 const args = [...options.args];
201 args.shift();
202
203 if (index !== -1) {
204 args.splice(index - 1, 2);
205 }
206
207 reason = await args.join(' ');
208 }
209
210 if (index !== -1) {
211 time = await options.args[index + 1];
212
213 if (time === undefined) {
214 await this.deferReply(msg, {
215 embeds: [
216 new MessageEmbed()
217 .setColor('#f14a60')
218 .setDescription(`Option \`-t\` (time) requires an argument.`)
219 ]
220 });
221
222 return;
223 }
224
225 if (!ms(time)) {
226 await this.deferReply(msg, {
227 embeds: [
228 new MessageEmbed()
229 .setColor('#f14a60')
230 .setDescription(`Option \`-t\` (time) requires an argument which must be a valid time interval.`)
231 ]
232 });
233
234 return;
235 }
236
237 timeInterval = await ms(time);
238 }
239 }
240
241 if (timeInterval) {
242 dateTime = Date.now() + timeInterval;
243 }
244
245 if (!(await hasPermission(client, user, msg, null, "You don't have permission to mute this user."))) {
246 return;
247 }
248
249 if (shouldNotModerate(client, user)) {
250 await msg.reply({
251 embeds: [
252 {
253 description: "This user cannot be muted."
254 }
255 ]
256 });
257
258 return;
259 }
260
261 await mute(client, dateTime, user, msg, timeInterval, reason, hard);
262
263 const fields = [
264 {
265 name: "Muted by",
266 value: (msg.member!.user as User).tag
267 },
268 {
269 name: "Reason",
270 value: reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason
271 },
272 {
273 name: "Duration",
274 value: time === undefined ? "*No duration set*" : (time + '')
275 },
276 {
277 name: "Role Takeout",
278 value: hard ? 'Yes' : 'No'
279 }
280 ];
281
282 console.log(fields);
283
284 await this.deferReply(msg, {
285 embeds: [
286 new MessageEmbed()
287 .setAuthor({
288 name: user.user.tag,
289 iconURL: user.displayAvatarURL(),
290 })
291 .setDescription(user.user.tag + " has been muted.")
292 .addFields(fields)
293 ]
294 });
295 }
296 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26