/[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 194 - (show annotations)
Mon Jul 29 17:28:58 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 9968 byte(s)
feat: add proper permission checking and error messages
1 import { BanOptions, CommandInteraction, GuildMember, Interaction, Message, 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 });
61 }
62
63 const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));
64 await user.roles.add(role!, reason);
65
66 await Punishment.create({
67 type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
68 user_id: user.id,
69 guild_id: msg.guild!.id,
70 mod_id: msg.member!.user.id,
71 mod_tag: (msg.member!.user as User).tag,
72 reason,
73 meta: {
74 time: timeInterval ? ms(timeInterval) : undefined
75 }
76 });
77
78 await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User, hard);
79
80 try {
81 await user.send({
82 embeds: [
83 new MessageEmbed()
84 .setAuthor({
85 iconURL: <string> msg.guild!.iconURL(),
86 name: `\tYou have been muted in ${msg.guild!.name}`
87 })
88 .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)
89 ]
90 });
91 }
92 catch (e) {
93 console.log(e);
94 }
95 }
96 catch (e) {
97 console.log(e);
98
99 if (msg instanceof Message)
100 await msg.reply({
101 embeds: [
102 new MessageEmbed()
103 .setColor('#f14a60')
104 .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
105 ]
106 });
107 else
108 await msg.editReply({
109 embeds: [
110 new MessageEmbed()
111 .setColor('#f14a60')
112 .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
113 ]
114 });
115
116 return;
117 }
118 }
119
120 export default class MuteCommand extends BaseCommand {
121 supportsInteractions: boolean = true;
122
123 constructor() {
124 super('mute', 'moderation', []);
125 }
126
127 async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {
128 if (!options.isInteraction && typeof options.args[0] === 'undefined') {
129 await msg.reply({
130 embeds: [
131 new MessageEmbed()
132 .setColor('#f14a60')
133 .setDescription(`This command requires at least one argument.`)
134 ]
135 });
136
137 return;
138 }
139
140 if (msg instanceof CommandInteraction)
141 await msg.deferReply();
142
143 let user: GuildMember;
144 let reason: string | undefined;
145 let time: string | undefined;
146 let timeInterval: number | undefined;
147 let dateTime: number | undefined;
148 let hard: boolean = false;
149
150 if (options.isInteraction) {
151 user = await <GuildMember> options.options.getMember('member');
152
153 if (options.options.getString('reason')) {
154 reason = await <string> options.options.getString('reason');
155 }
156
157 if (options.options.getBoolean('hardmute')) {
158 hard = await <boolean> options.options.getBoolean('hardmute');
159 }
160
161 if (options.options.getString('time')) {
162 time = await options.options.getString('time') as string;
163 timeInterval = await ms(time);
164
165 if (!timeInterval) {
166 await this.deferReply(msg, {
167 embeds: [
168 new MessageEmbed()
169 .setColor('#f14a60')
170 .setDescription(`Option \`-t\` (time) requires an argument which must be a valid time interval.`)
171 ]
172 });
173
174 return;
175 }
176 }
177 }
178 else {
179 const user2 = await getMember((msg as Message), options);
180
181 if (!user2) {
182 await this.deferReply(msg, {
183 embeds: [
184 new MessageEmbed()
185 .setColor('#f14a60')
186 .setDescription(`Invalid user given.`)
187 ]
188 });
189
190 return;
191 }
192
193 user = user2;
194
195 const index = await options.args.indexOf('-t');
196
197 if (options.args[1]) {
198 const args = [...options.args];
199 args.shift();
200
201 if (index !== -1) {
202 args.splice(index - 1, 2);
203 }
204
205 reason = await args.join(' ');
206 }
207
208 if (index !== -1) {
209 time = await options.args[index + 1];
210
211 if (time === undefined) {
212 await this.deferReply(msg, {
213 embeds: [
214 new MessageEmbed()
215 .setColor('#f14a60')
216 .setDescription(`Option \`-t\` (time) requires an argument.`)
217 ]
218 });
219
220 return;
221 }
222
223 if (!ms(time)) {
224 await this.deferReply(msg, {
225 embeds: [
226 new MessageEmbed()
227 .setColor('#f14a60')
228 .setDescription(`Option \`-t\` (time) requires an argument which must be a valid time interval.`)
229 ]
230 });
231
232 return;
233 }
234
235 timeInterval = await ms(time);
236 }
237 }
238
239 if (timeInterval) {
240 dateTime = Date.now() + timeInterval;
241 }
242
243 if (!(await hasPermission(client, user, msg, null, "You don't have permission to mute this user."))) {
244 return;
245 }
246
247 if (shouldNotModerate(client, user)) {
248 await msg.reply({
249 embeds: [
250 {
251 description: "This user cannot be muted."
252 }
253 ]
254 });
255
256 return;
257 }
258
259 await mute(client, dateTime, user, msg, timeInterval, reason, hard);
260
261 const fields = [
262 {
263 name: "Muted by",
264 value: (msg.member!.user as User).tag
265 },
266 {
267 name: "Reason",
268 value: reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason
269 },
270 {
271 name: "Duration",
272 value: time === undefined ? "*No duration set*" : (time + '')
273 },
274 {
275 name: "Role Takeout",
276 value: hard ? 'Yes' : 'No'
277 }
278 ];
279
280 console.log(fields);
281
282 await this.deferReply(msg, {
283 embeds: [
284 new MessageEmbed()
285 .setAuthor({
286 name: user.user.tag,
287 iconURL: user.displayAvatarURL(),
288 })
289 .setDescription(user.user.tag + " has been muted.")
290 .addFields(fields)
291 ]
292 });
293 }
294 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26