/[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 51 by rakin, Mon Jul 29 17:28:23 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';
28  import { unmute } from './UnmuteCommand';  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          if (dateTime) {          const { default: Punishment } = await import('../../models/Punishment');
34              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) => {          
35                  if (err)          const { getTimeouts, clearTimeoutv2, setTimeoutv2 } = await import('../../utils/setTimeout');
36                      console.log(err);  
37                            const timeouts = getTimeouts();
38                      console.log('A timeout has been set.');          
39            for (const timeout of timeouts.values()) {
40                      setTimeout(async () => {              if (timeout.row.params) {
41                          await client.db.get("SELECT * FROM unmutes WHERE time = ?", [new Date(dateTime!).toISOString()], async (err: any, data: any) => {                  try {
42                              if (err)                      const json = JSON.parse(timeout.row.params);
43                                  console.log(err);  
44                                                    if (json) {
45                              if (data) {                          if (json[1] === user.id && timeout.row.filePath.endsWith('unmute-job')) {
46                                  await client.db.get('DELETE FROM unmutes WHERE id = ?', [data.id], async (err: any) => {                              await clearTimeoutv2(timeout);
47                                      let guild = await client.guilds.cache.find(g => g.id === data.guild_id);                          }
48                                      let member = await guild?.members.cache.find(m => m.id === data.user_id);                      }
49                            }
50                                      if (member) {                  catch (e) {
51                                          await unmute(client, member, msg, client.user!);                      console.log(e);                    
52                                          await History.create(member.id, msg.guild!, 'unmute', client.user!.id, null);                  }
53                                      }              }
54                    }
55                                      console.log(data);  
56                                  });          if (dateTime && timeInterval) {
57                              }              await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);
58                          });          }
59                      }, timeInterval);          
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          await History.create(user.id, msg.guild!, 'mute', msg.member!.user.id, typeof reason === 'undefined' ? null : reason);  
76          await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User);          await Punishment.create({
77          await user.send({              type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
78              embeds: [              user_id: user.id,
79                  new MessageEmbed()              guild_id: msg.guild!.id,
80                  .setAuthor({              mod_id: msg.member!.user.id,
81                      iconURL: <string> msg.guild!.iconURL(),              mod_tag: (msg.member!.user as User).tag,
82                      name: `\tYou have been muted in ${msg.guild!.name}`              reason,
83                  })              meta: {
84                  .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)                  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            try {
92                await user.send({
93                    embeds: [
94                        new MessageEmbed()
95                        .setAuthor({
96                            iconURL: <string> msg.guild!.iconURL(),
97                            name: `\tYou have been muted in ${msg.guild!.name}`
98                        })
99                        .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)
100                    ]
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 74  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 92  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 105  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 126  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 146  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 156  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 168  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 187  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 201  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 218  export default class MuteCommand extends Line 303  export default class MuteCommand extends
303              ]              ]
304          });          });
305      }      }
 }  
306    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26