/[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 86 by rakin, Mon Jul 29 17:28:32 2024 UTC revision 428 by rakin, Mon Jul 29 17:30:11 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, Guild, 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    import UnmuteQueue from '../../queues/UnmuteQueue';
31    
32  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 | { guild: Guild, member: GuildMember, editReply?: undefined }, timeInterval: number | undefined, reason: string | undefined, hard: boolean = false) {
33      try {      try {
34          const { default: Punishment } = await import('../../models/Punishment');          const { default: Punishment } = await import('../../models/Punishment');
35                    
36          if (dateTime) {          const { getTimeouts, clearTimeoutv2, setTimeoutv2 } = await import('../../utils/setTimeout');
37              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) => {  
38                  if (err)          const timeouts = getTimeouts();
39                      console.log(err);          
40                            for (const timeout of timeouts.values()) {
41                      console.log('A timeout has been set.');              if (timeout.row.params) {
42                    try {
43                      setTimeout(async () => {                      const json = JSON.parse(timeout.row.params);
44                          await client.db.get("SELECT * FROM unmutes WHERE time = ?", [new Date(dateTime!).toISOString()], async (err: any, data: any) => {  
45                              if (err)                      if (json) {
46                                  console.log(err);                          if (json[1] === user.id && timeout.row.filePath.endsWith('unmute-job')) {
47                                                            await clearTimeoutv2(timeout);
48                              if (data) {                          }
49                                  await client.db.get('DELETE FROM unmutes WHERE id = ?', [data.id], async (err: any) => {                      }
50                                      let guild = await client.guilds.cache.find(g => g.id === data.guild_id);                  }
51                                      let member = await guild?.members.cache.find(m => m.id === data.user_id);                  catch (e) {
52                                console.log(e);                    
53                                      if (member) {                  }
54                                          await unmute(client, member, msg, client.user!);              }
55                                          await History.create(member.id, msg.guild!, 'unmute', client.user!.id, null);          }
56                                      }  
57                    if (dateTime && timeInterval) {
58                                      console.log(data);              // await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);
59                                  });              for await (const queue of client.queueManager.queues.values()) {
60                              }                  if (queue instanceof UnmuteQueue && queue.data!.memberID === user.id && queue.data!.guildID === msg.guild!.id) {
61                          });                      await queue.cancel();
62                      }, timeInterval);                  }
63                }
64    
65                await client.queueManager.addQueue(UnmuteQueue, {
66                    data: {
67                        guildID: msg.guild!.id,
68                        memberID: user.id
69                    },
70                    runAt: new Date(Date.now() + timeInterval)
71                });
72            }
73            
74            if (hard) {
75                const { default: Hardmute } = await import("../../models/Hardmute");
76                const roles = await user.roles.cache.filter(r => r.id !== msg.guild!.id);
77                await user.roles.remove(roles, reason);
78    
79                await Hardmute.create({
80                    user_id: user.id,
81                    roles: roles.map(role => role.id),
82                    guild_id: msg.guild!.id,
83                    createdAt: new Date()
84              });              });
85          }          }
86    
87          const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));          const role = await msg.guild!.roles.fetch(client.config.props[msg.guild!.id].mute_role);
88          await user.roles.add(role!);          await user.roles.add(role!, reason);
89    
90          await Punishment.create({          await Punishment.create({
91              type: PunishmentType.MUTE,              type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
92              user_id: user.id,              user_id: user.id,
93              guild_id: msg.guild!.id,              guild_id: msg.guild!.id,
94              mod_id: msg.member!.user.id,              mod_id: msg.member!.user.id,
# Line 57  export async function mute(client: Disco Line 96  export async function mute(client: Disco
96              reason,              reason,
97              meta: {              meta: {
98                  time: timeInterval ? ms(timeInterval) : undefined                  time: timeInterval ? ms(timeInterval) : undefined
99              }              },
100                createdAt: new Date()
101          });          });
102            
103            await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User, hard);
104    
105          await History.create(user.id, msg.guild!, 'mute', msg.member!.user.id, typeof reason === 'undefined' ? null : reason);          try {
106          await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User);              await user.send({
107          await user.send({                  embeds: [
108              embeds: [                      new MessageEmbed()
109                  new MessageEmbed()                      .setAuthor({
110                  .setAuthor({                          iconURL: <string> msg.guild!.iconURL(),
111                      iconURL: <string> msg.guild!.iconURL(),                          name: `\tYou have been muted in ${msg.guild!.name}`
112                      name: `\tYou have been muted in ${msg.guild!.name}`                      })
113                  })                      .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)
114                  .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)                  ]
115              ]              });
116          });          }
117            catch (e) {
118                console.log(e);
119            }
120      }      }
121      catch (e) {      catch (e) {
122          console.log(e);          console.log(e);
123                    
124          await msg.reply({          if (msg instanceof Message)
125              embeds: [              await msg.reply({
126                  new MessageEmbed()                  embeds: [
127                  .setColor('#f14a60')                      new MessageEmbed()
128                  .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')
129              ]                      .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
130          });                  ]
131                });
132            else if (msg.editReply)
133                await msg.editReply({
134                    embeds: [
135                        new MessageEmbed()
136                        .setColor('#f14a60')
137                        .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
138                    ]
139                });
140    
141          return;          return;
142      }      }
# Line 90  export async function mute(client: Disco Line 144  export async function mute(client: Disco
144    
145  export default class MuteCommand extends BaseCommand {  export default class MuteCommand extends BaseCommand {
146      supportsInteractions: boolean = true;      supportsInteractions: boolean = true;
147        permissions = [Permissions.FLAGS.MODERATE_MEMBERS];
148    
149      constructor() {      constructor() {
150          super('mute', 'moderation', []);          super('mute', 'moderation', []);
# Line 108  export default class MuteCommand extends Line 163  export default class MuteCommand extends
163              return;              return;
164          }          }
165    
166            if (msg instanceof CommandInteraction)
167                await msg.deferReply();
168    
169          let user: GuildMember;          let user: GuildMember;
170          let reason: string | undefined;          let reason: string | undefined;
171          let time: string | undefined;          let time: string | undefined;
172          let timeInterval: number | undefined;          let timeInterval: number | undefined;
173          let dateTime: number | undefined;          let dateTime: number | undefined;
174            let hard: boolean = false;
175    
176          if (options.isInteraction) {          if (options.isInteraction) {
177              user = await <GuildMember> options.options.getMember('member');              user = await <GuildMember> options.options.getMember('member');
# Line 121  export default class MuteCommand extends Line 180  export default class MuteCommand extends
180                  reason = await <string> options.options.getString('reason');                  reason = await <string> options.options.getString('reason');
181              }              }
182    
183                if (options.options.getBoolean('hardmute')) {
184                    hard = await <boolean> options.options.getBoolean('hardmute');
185                }
186    
187              if (options.options.getString('time')) {              if (options.options.getString('time')) {
188                  time = await options.options.getString('time') as string;                  time = await options.options.getString('time') as string;
189                  timeInterval = await ms(time);                  timeInterval = await ms(time);
190    
191                  if (!timeInterval) {                  if (!timeInterval) {
192                      await msg.reply({                      await this.deferReply(msg, {
193                          embeds: [                          embeds: [
194                              new MessageEmbed()                              new MessageEmbed()
195                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 142  export default class MuteCommand extends Line 205  export default class MuteCommand extends
205              const user2 = await getMember((msg as Message), options);              const user2 = await getMember((msg as Message), options);
206    
207              if (!user2) {              if (!user2) {
208                  await msg.reply({                  await this.deferReply(msg, {
209                      embeds: [                      embeds: [
210                          new MessageEmbed()                          new MessageEmbed()
211                          .setColor('#f14a60')                          .setColor('#f14a60')
# Line 162  export default class MuteCommand extends Line 225  export default class MuteCommand extends
225                  args.shift();                  args.shift();
226    
227                  if (index !== -1) {                  if (index !== -1) {
228                      args.splice(index - 1, 2)                      args.splice(index - 1, 2);
229                  }                  }
230    
231                  reason = await args.join(' ');                  reason = await args.join(' ');
# Line 172  export default class MuteCommand extends Line 235  export default class MuteCommand extends
235                  time = await options.args[index + 1];                  time = await options.args[index + 1];
236    
237                  if (time === undefined) {                  if (time === undefined) {
238                      await msg.reply({                      await this.deferReply(msg, {
239                          embeds: [                          embeds: [
240                              new MessageEmbed()                              new MessageEmbed()
241                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 184  export default class MuteCommand extends Line 247  export default class MuteCommand extends
247                  }                  }
248    
249                  if (!ms(time)) {                  if (!ms(time)) {
250                      await msg.reply({                      await this.deferReply(msg, {
251                          embeds: [                          embeds: [
252                              new MessageEmbed()                              new MessageEmbed()
253                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 203  export default class MuteCommand extends Line 266  export default class MuteCommand extends
266              dateTime = Date.now() + timeInterval;              dateTime = Date.now() + timeInterval;
267          }          }
268    
269          await mute(client, dateTime, user, msg, timeInterval, reason);          if (!(await hasPermission(client, user, msg, null, "You don't have permission to mute this user."))) {
270                return;
271            }
272            
273            if (shouldNotModerate(client, user)) {
274                await msg.reply({
275                    embeds: [
276                        {
277                            description: "This user cannot be muted."
278                        }
279                    ]
280                });
281    
282                return;
283            }
284            
285            await mute(client, dateTime, user, msg, timeInterval, reason, hard);
286    
287          const fields = [          const fields = [
288              {              {
# Line 217  export default class MuteCommand extends Line 296  export default class MuteCommand extends
296              {              {
297                  name: "Duration",                  name: "Duration",
298                  value: time === undefined ? "*No duration set*" : (time + '')                  value: time === undefined ? "*No duration set*" : (time + '')
299                },
300                {
301                    name: "Role Takeout",
302                    value: hard ? 'Yes' : 'No'
303              }              }
304          ];          ];
305    
306          console.log(fields);                  console.log(fields);        
307    
308          await msg.reply({          await this.deferReply(msg, {
309              embeds: [              embeds: [
310                  new MessageEmbed()                  new MessageEmbed()
311                  .setAuthor({                  .setAuthor({
# Line 234  export default class MuteCommand extends Line 317  export default class MuteCommand extends
317              ]              ]
318          });          });
319      }      }
 }  
320    }

Legend:
Removed from v.86  
changed lines
  Added in v.428

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26