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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 102 by rakin, Mon Jul 29 17:28:36 2024 UTC revision 393 by rakin, Mon Jul 29 17:29:59 2024 UTC
# Line 1  Line 1 
1  import { BanOptions, CommandInteraction, GuildMember, Interaction, Message, User } from 'discord.js';  /**
2    * This file is part of SudoBot.
3    *
4    * Copyright (C) 2021-2022 OSN Inc.
5    *
6    * SudoBot is free software; you can redistribute it and/or modify it
7    * under the terms of the GNU Affero General Public License as published by
8    * the Free Software Foundation, either version 3 of the License, or
9    * (at your option) any later version.
10    *
11    * SudoBot is distributed in the hope that it will be useful, but
12    * WITHOUT ANY WARRANTY; without even the implied warranty of
13    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14    * GNU Affero General Public License for more details.
15    *
16    * You should have received a copy of the GNU Affero General Public License
17    * along with SudoBot. If not, see <https://www.gnu.org/licenses/>.
18    */
19    
20    import { CommandInteraction, GuildMember, Message, Permissions, User } from 'discord.js';
21  import BaseCommand from '../../utils/structures/BaseCommand';  import BaseCommand from '../../utils/structures/BaseCommand';
22  import DiscordClient from '../../client/Client';  import DiscordClient from '../../client/Client';
23  import CommandOptions from '../../types/CommandOptions';  import CommandOptions from '../../types/CommandOptions';
24  import InteractionOptions from '../../types/InteractionOptions';  import InteractionOptions from '../../types/InteractionOptions';
25  import MessageEmbed from '../../client/MessageEmbed';  import MessageEmbed from '../../client/MessageEmbed';
 import getUser from '../../utils/getUser';  
 import History from '../../automod/History';  
26  import getMember from '../../utils/getMember';  import getMember from '../../utils/getMember';
27  import ms from 'ms';  import ms from 'ms';
 import { unmute } from './UnmuteCommand';  
28  import PunishmentType from '../../types/PunishmentType';  import PunishmentType from '../../types/PunishmentType';
29    import { hasPermission, shouldNotModerate } from '../../utils/util';
30    
31  export async function mute(client: DiscordClient, dateTime: number | undefined, user: GuildMember, msg: Message | CommandInteraction, timeInterval: number | undefined, reason: string | undefined) {  export async function mute(client: DiscordClient, dateTime: number | undefined, user: GuildMember, msg: Message | CommandInteraction, timeInterval: number | undefined, reason: string | undefined, hard: boolean = false) {
32      try {      try {
33          const { default: Punishment } = await import('../../models/Punishment');          const { default: Punishment } = await import('../../models/Punishment');
34                    
# Line 25  export async function mute(client: Disco Line 42  export async function mute(client: Disco
42                      const json = JSON.parse(timeout.row.params);                      const json = JSON.parse(timeout.row.params);
43    
44                      if (json) {                      if (json) {
45                          if (json[1] === user.id) {                          if (json[1] === user.id && timeout.row.filePath.endsWith('unmute-job')) {
46                              await clearTimeoutv2(timeout);                              await clearTimeoutv2(timeout);
47                          }                          }
48                      }                      }
# Line 37  export async function mute(client: Disco Line 54  export async function mute(client: Disco
54          }          }
55    
56          if (dateTime && timeInterval) {          if (dateTime && timeInterval) {
57              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) => {              await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);
                 if (err)  
                     console.log(err);  
                   
                     console.log('A timeout has been set.');  
   
                     await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);  
             });  
58          }          }
59                    
60            if (hard) {
61                const { default: Hardmute } = await import("../../models/Hardmute");
62                const roles = await user.roles.cache.filter(r => r.id !== msg.guild!.id);
63                await user.roles.remove(roles, reason);
64    
65                await Hardmute.create({
66                    user_id: user.id,
67                    roles: roles.map(role => role.id),
68                    guild_id: msg.guild!.id,
69                    createdAt: new Date()
70                });
71            }
72    
73          const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));          const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));
74          await user.roles.add(role!);          await user.roles.add(role!, reason);
75    
76          await Punishment.create({          await Punishment.create({
77              type: PunishmentType.MUTE,              type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
78              user_id: user.id,              user_id: user.id,
79              guild_id: msg.guild!.id,              guild_id: msg.guild!.id,
80              mod_id: msg.member!.user.id,              mod_id: msg.member!.user.id,
# Line 59  export async function mute(client: Disco Line 82  export async function mute(client: Disco
82              reason,              reason,
83              meta: {              meta: {
84                  time: timeInterval ? ms(timeInterval) : undefined                  time: timeInterval ? ms(timeInterval) : undefined
85              }              },
86                createdAt: new Date()
87          });          });
88            
89            await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User, hard);
90    
91          await History.create(user.id, msg.guild!, 'mute', msg.member!.user.id, typeof reason === 'undefined' ? null : reason);          try {
92          await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User);              await user.send({
93          await user.send({                  embeds: [
94              embeds: [                      new MessageEmbed()
95                  new MessageEmbed()                      .setAuthor({
96                  .setAuthor({                          iconURL: <string> msg.guild!.iconURL(),
97                      iconURL: <string> msg.guild!.iconURL(),                          name: `\tYou have been muted in ${msg.guild!.name}`
98                      name: `\tYou have been muted in ${msg.guild!.name}`                      })
99                  })                      .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)
100                  .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)                  ]
101              ]              });
102          });          }
103            catch (e) {
104                console.log(e);
105            }
106      }      }
107      catch (e) {      catch (e) {
108          console.log(e);          console.log(e);
109                    
110          await msg.reply({          if (msg instanceof Message)
111              embeds: [              await msg.reply({
112                  new MessageEmbed()                  embeds: [
113                  .setColor('#f14a60')                      new MessageEmbed()
114                  .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")                      .setColor('#f14a60')
115              ]                      .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
116          });                  ]
117                });
118            else
119                await msg.editReply({
120                    embeds: [
121                        new MessageEmbed()
122                        .setColor('#f14a60')
123                        .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
124                    ]
125                });
126    
127          return;          return;
128      }      }
# Line 92  export async function mute(client: Disco Line 130  export async function mute(client: Disco
130    
131  export default class MuteCommand extends BaseCommand {  export default class MuteCommand extends BaseCommand {
132      supportsInteractions: boolean = true;      supportsInteractions: boolean = true;
133        permissions = [Permissions.FLAGS.MODERATE_MEMBERS];
134    
135      constructor() {      constructor() {
136          super('mute', 'moderation', []);          super('mute', 'moderation', []);
# Line 110  export default class MuteCommand extends Line 149  export default class MuteCommand extends
149              return;              return;
150          }          }
151    
152            if (msg instanceof CommandInteraction)
153                await msg.deferReply();
154    
155          let user: GuildMember;          let user: GuildMember;
156          let reason: string | undefined;          let reason: string | undefined;
157          let time: string | undefined;          let time: string | undefined;
158          let timeInterval: number | undefined;          let timeInterval: number | undefined;
159          let dateTime: number | undefined;          let dateTime: number | undefined;
160            let hard: boolean = false;
161    
162          if (options.isInteraction) {          if (options.isInteraction) {
163              user = await <GuildMember> options.options.getMember('member');              user = await <GuildMember> options.options.getMember('member');
# Line 123  export default class MuteCommand extends Line 166  export default class MuteCommand extends
166                  reason = await <string> options.options.getString('reason');                  reason = await <string> options.options.getString('reason');
167              }              }
168    
169                if (options.options.getBoolean('hardmute')) {
170                    hard = await <boolean> options.options.getBoolean('hardmute');
171                }
172    
173              if (options.options.getString('time')) {              if (options.options.getString('time')) {
174                  time = await options.options.getString('time') as string;                  time = await options.options.getString('time') as string;
175                  timeInterval = await ms(time);                  timeInterval = await ms(time);
176    
177                  if (!timeInterval) {                  if (!timeInterval) {
178                      await msg.reply({                      await this.deferReply(msg, {
179                          embeds: [                          embeds: [
180                              new MessageEmbed()                              new MessageEmbed()
181                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 144  export default class MuteCommand extends Line 191  export default class MuteCommand extends
191              const user2 = await getMember((msg as Message), options);              const user2 = await getMember((msg as Message), options);
192    
193              if (!user2) {              if (!user2) {
194                  await msg.reply({                  await this.deferReply(msg, {
195                      embeds: [                      embeds: [
196                          new MessageEmbed()                          new MessageEmbed()
197                          .setColor('#f14a60')                          .setColor('#f14a60')
# Line 164  export default class MuteCommand extends Line 211  export default class MuteCommand extends
211                  args.shift();                  args.shift();
212    
213                  if (index !== -1) {                  if (index !== -1) {
214                      args.splice(index - 1, 2)                      args.splice(index - 1, 2);
215                  }                  }
216    
217                  reason = await args.join(' ');                  reason = await args.join(' ');
# Line 174  export default class MuteCommand extends Line 221  export default class MuteCommand extends
221                  time = await options.args[index + 1];                  time = await options.args[index + 1];
222    
223                  if (time === undefined) {                  if (time === undefined) {
224                      await msg.reply({                      await this.deferReply(msg, {
225                          embeds: [                          embeds: [
226                              new MessageEmbed()                              new MessageEmbed()
227                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 186  export default class MuteCommand extends Line 233  export default class MuteCommand extends
233                  }                  }
234    
235                  if (!ms(time)) {                  if (!ms(time)) {
236                      await msg.reply({                      await this.deferReply(msg, {
237                          embeds: [                          embeds: [
238                              new MessageEmbed()                              new MessageEmbed()
239                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 205  export default class MuteCommand extends Line 252  export default class MuteCommand extends
252              dateTime = Date.now() + timeInterval;              dateTime = Date.now() + timeInterval;
253          }          }
254    
255          await mute(client, dateTime, user, msg, timeInterval, reason);          if (!(await hasPermission(client, user, msg, null, "You don't have permission to mute this user."))) {
256                return;
257            }
258            
259            if (shouldNotModerate(client, user)) {
260                await msg.reply({
261                    embeds: [
262                        {
263                            description: "This user cannot be muted."
264                        }
265                    ]
266                });
267    
268                return;
269            }
270            
271            await mute(client, dateTime, user, msg, timeInterval, reason, hard);
272    
273          const fields = [          const fields = [
274              {              {
# Line 219  export default class MuteCommand extends Line 282  export default class MuteCommand extends
282              {              {
283                  name: "Duration",                  name: "Duration",
284                  value: time === undefined ? "*No duration set*" : (time + '')                  value: time === undefined ? "*No duration set*" : (time + '')
285                },
286                {
287                    name: "Role Takeout",
288                    value: hard ? 'Yes' : 'No'
289              }              }
290          ];          ];
291    
292          console.log(fields);                  console.log(fields);        
293    
294          await msg.reply({          await this.deferReply(msg, {
295              embeds: [              embeds: [
296                  new MessageEmbed()                  new MessageEmbed()
297                  .setAuthor({                  .setAuthor({
# Line 236  export default class MuteCommand extends Line 303  export default class MuteCommand extends
303              ]              ]
304          });          });
305      }      }
 }  
306    }

Legend:
Removed from v.102  
changed lines
  Added in v.393

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26