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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 333 - (hide 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 rakin 203 import { BanOptions, CommandInteraction, GuildMember, Interaction, Message, Permissions, User } from 'discord.js';
2 rakin 51 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 rakin 86 import PunishmentType from '../../types/PunishmentType';
13 rakin 194 import { hasPermission, shouldNotModerate } from '../../utils/util';
14 rakin 51
15 rakin 124 export async function mute(client: DiscordClient, dateTime: number | undefined, user: GuildMember, msg: Message | CommandInteraction, timeInterval: number | undefined, reason: string | undefined, hard: boolean = false) {
16 rakin 51 try {
17 rakin 86 const { default: Punishment } = await import('../../models/Punishment');
18    
19 rakin 102 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 rakin 106 if (json[1] === user.id && timeout.row.filePath.endsWith('unmute-job')) {
30 rakin 102 await clearTimeoutv2(timeout);
31     }
32     }
33     }
34     catch (e) {
35     console.log(e);
36     }
37     }
38     }
39    
40     if (dateTime && timeInterval) {
41 rakin 51 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 rakin 102 await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);
48 rakin 51 });
49     }
50 rakin 102
51 rakin 124 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 rakin 333 createdAt: new Date()
61 rakin 124 });
62     }
63    
64 rakin 51 const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));
65 rakin 124 await user.roles.add(role!, reason);
66 rakin 86
67     await Punishment.create({
68 rakin 124 type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
69 rakin 86 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 rakin 124
79     await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User, hard);
80 rakin 159
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 rakin 51 }
97     catch (e) {
98     console.log(e);
99    
100 rakin 124 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 rakin 51
117     return;
118     }
119     }
120    
121     export default class MuteCommand extends BaseCommand {
122     supportsInteractions: boolean = true;
123 rakin 203 permissions = [Permissions.FLAGS.MODERATE_MEMBERS];
124 rakin 51
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 rakin 124 if (msg instanceof CommandInteraction)
143     await msg.deferReply();
144    
145 rakin 51 let user: GuildMember;
146     let reason: string | undefined;
147     let time: string | undefined;
148     let timeInterval: number | undefined;
149     let dateTime: number | undefined;
150 rakin 124 let hard: boolean = false;
151 rakin 51
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 rakin 124 if (options.options.getBoolean('hardmute')) {
160     hard = await <boolean> options.options.getBoolean('hardmute');
161     }
162    
163 rakin 51 if (options.options.getString('time')) {
164     time = await options.options.getString('time') as string;
165     timeInterval = await ms(time);
166    
167     if (!timeInterval) {
168 rakin 124 await this.deferReply(msg, {
169 rakin 51 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 rakin 124 await this.deferReply(msg, {
185 rakin 51 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 rakin 124 args.splice(index - 1, 2);
205 rakin 51 }
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 rakin 124 await this.deferReply(msg, {
215 rakin 51 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 rakin 124 await this.deferReply(msg, {
227 rakin 51 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 rakin 194 if (!(await hasPermission(client, user, msg, null, "You don't have permission to mute this user."))) {
246     return;
247     }
248    
249 rakin 153 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 rakin 124 await mute(client, dateTime, user, msg, timeInterval, reason, hard);
262 rakin 51
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 rakin 124 },
276     {
277     name: "Role Takeout",
278     value: hard ? 'Yes' : 'No'
279 rakin 51 }
280     ];
281    
282     console.log(fields);
283    
284 rakin 124 await this.deferReply(msg, {
285 rakin 51 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 rakin 153 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26