/[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 427 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                    
# Line 25  export async function mute(client: Disco Line 43  export async function mute(client: Disco
43                      const json = JSON.parse(timeout.row.params);                      const json = JSON.parse(timeout.row.params);
44    
45                      if (json) {                      if (json) {
46                          if (json[1] === user.id) {                          if (json[1] === user.id && timeout.row.filePath.endsWith('unmute-job')) {
47                              await clearTimeoutv2(timeout);                              await clearTimeoutv2(timeout);
48                          }                          }
49                      }                      }
# Line 37  export async function mute(client: Disco Line 55  export async function mute(client: Disco
55          }          }
56    
57          if (dateTime && timeInterval) {          if (dateTime && timeInterval) {
58              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);
59                  if (err)              await client.queueManager.addQueue(UnmuteQueue, {
60                      console.log(err);                  data: {
61                                        guildID: msg.guild!.id,
62                      console.log('A timeout has been set.');                      memberID: user.id
63                    },
64                      await setTimeoutv2('unmute-job', timeInterval, msg.guild!.id, `unmute ${user.id}`, msg.guild!.id, user.id);                  runAt: new Date(Date.now() + timeInterval)
65              });              });
66          }          }
67                    
68          const role = await msg.guild!.roles.fetch(client.config.get('mute_role'));          if (hard) {
69          await user.roles.add(role!);              const { default: Hardmute } = await import("../../models/Hardmute");
70                const roles = await user.roles.cache.filter(r => r.id !== msg.guild!.id);
71                await user.roles.remove(roles, reason);
72    
73                await Hardmute.create({
74                    user_id: user.id,
75                    roles: roles.map(role => role.id),
76                    guild_id: msg.guild!.id,
77                    createdAt: new Date()
78                });
79            }
80    
81            const role = await msg.guild!.roles.fetch(client.config.props[msg.guild!.id].mute_role);
82            await user.roles.add(role!, reason);
83    
84          await Punishment.create({          await Punishment.create({
85              type: PunishmentType.MUTE,              type: hard ? PunishmentType.HARDMUTE : PunishmentType.MUTE,
86              user_id: user.id,              user_id: user.id,
87              guild_id: msg.guild!.id,              guild_id: msg.guild!.id,
88              mod_id: msg.member!.user.id,              mod_id: msg.member!.user.id,
# Line 59  export async function mute(client: Disco Line 90  export async function mute(client: Disco
90              reason,              reason,
91              meta: {              meta: {
92                  time: timeInterval ? ms(timeInterval) : undefined                  time: timeInterval ? ms(timeInterval) : undefined
93              }              },
94                createdAt: new Date()
95          });          });
96            
97            await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User, hard);
98    
99          await History.create(user.id, msg.guild!, 'mute', msg.member!.user.id, typeof reason === 'undefined' ? null : reason);          try {
100          await client.logger.logMute(user, reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason, timeInterval, msg.member!.user as User);              await user.send({
101          await user.send({                  embeds: [
102              embeds: [                      new MessageEmbed()
103                  new MessageEmbed()                      .setAuthor({
104                  .setAuthor({                          iconURL: <string> msg.guild!.iconURL(),
105                      iconURL: <string> msg.guild!.iconURL(),                          name: `\tYou have been muted in ${msg.guild!.name}`
106                      name: `\tYou have been muted in ${msg.guild!.name}`                      })
107                  })                      .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)
108                  .addField("Reason", reason === undefined || reason.trim() === '' ? "*No reason provided*" : reason)                  ]
109              ]              });
110          });          }
111            catch (e) {
112                console.log(e);
113            }
114      }      }
115      catch (e) {      catch (e) {
116          console.log(e);          console.log(e);
117                    
118          await msg.reply({          if (msg instanceof Message)
119              embeds: [              await msg.reply({
120                  new MessageEmbed()                  embeds: [
121                  .setColor('#f14a60')                      new MessageEmbed()
122                  .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')
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            else if (msg.editReply)
127                await msg.editReply({
128                    embeds: [
129                        new MessageEmbed()
130                        .setColor('#f14a60')
131                        .setDescription("Failed to assign the muted role to this user. Maybe missing permisions/roles or I'm not allowed to assign roles this user?")
132                    ]
133                });
134    
135          return;          return;
136      }      }
# Line 92  export async function mute(client: Disco Line 138  export async function mute(client: Disco
138    
139  export default class MuteCommand extends BaseCommand {  export default class MuteCommand extends BaseCommand {
140      supportsInteractions: boolean = true;      supportsInteractions: boolean = true;
141        permissions = [Permissions.FLAGS.MODERATE_MEMBERS];
142    
143      constructor() {      constructor() {
144          super('mute', 'moderation', []);          super('mute', 'moderation', []);
# Line 110  export default class MuteCommand extends Line 157  export default class MuteCommand extends
157              return;              return;
158          }          }
159    
160            if (msg instanceof CommandInteraction)
161                await msg.deferReply();
162    
163          let user: GuildMember;          let user: GuildMember;
164          let reason: string | undefined;          let reason: string | undefined;
165          let time: string | undefined;          let time: string | undefined;
166          let timeInterval: number | undefined;          let timeInterval: number | undefined;
167          let dateTime: number | undefined;          let dateTime: number | undefined;
168            let hard: boolean = false;
169    
170          if (options.isInteraction) {          if (options.isInteraction) {
171              user = await <GuildMember> options.options.getMember('member');              user = await <GuildMember> options.options.getMember('member');
# Line 123  export default class MuteCommand extends Line 174  export default class MuteCommand extends
174                  reason = await <string> options.options.getString('reason');                  reason = await <string> options.options.getString('reason');
175              }              }
176    
177                if (options.options.getBoolean('hardmute')) {
178                    hard = await <boolean> options.options.getBoolean('hardmute');
179                }
180    
181              if (options.options.getString('time')) {              if (options.options.getString('time')) {
182                  time = await options.options.getString('time') as string;                  time = await options.options.getString('time') as string;
183                  timeInterval = await ms(time);                  timeInterval = await ms(time);
184    
185                  if (!timeInterval) {                  if (!timeInterval) {
186                      await msg.reply({                      await this.deferReply(msg, {
187                          embeds: [                          embeds: [
188                              new MessageEmbed()                              new MessageEmbed()
189                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 144  export default class MuteCommand extends Line 199  export default class MuteCommand extends
199              const user2 = await getMember((msg as Message), options);              const user2 = await getMember((msg as Message), options);
200    
201              if (!user2) {              if (!user2) {
202                  await msg.reply({                  await this.deferReply(msg, {
203                      embeds: [                      embeds: [
204                          new MessageEmbed()                          new MessageEmbed()
205                          .setColor('#f14a60')                          .setColor('#f14a60')
# Line 164  export default class MuteCommand extends Line 219  export default class MuteCommand extends
219                  args.shift();                  args.shift();
220    
221                  if (index !== -1) {                  if (index !== -1) {
222                      args.splice(index - 1, 2)                      args.splice(index - 1, 2);
223                  }                  }
224    
225                  reason = await args.join(' ');                  reason = await args.join(' ');
# Line 174  export default class MuteCommand extends Line 229  export default class MuteCommand extends
229                  time = await options.args[index + 1];                  time = await options.args[index + 1];
230    
231                  if (time === undefined) {                  if (time === undefined) {
232                      await msg.reply({                      await this.deferReply(msg, {
233                          embeds: [                          embeds: [
234                              new MessageEmbed()                              new MessageEmbed()
235                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 186  export default class MuteCommand extends Line 241  export default class MuteCommand extends
241                  }                  }
242    
243                  if (!ms(time)) {                  if (!ms(time)) {
244                      await msg.reply({                      await this.deferReply(msg, {
245                          embeds: [                          embeds: [
246                              new MessageEmbed()                              new MessageEmbed()
247                              .setColor('#f14a60')                              .setColor('#f14a60')
# Line 205  export default class MuteCommand extends Line 260  export default class MuteCommand extends
260              dateTime = Date.now() + timeInterval;              dateTime = Date.now() + timeInterval;
261          }          }
262    
263          await mute(client, dateTime, user, msg, timeInterval, reason);          if (!(await hasPermission(client, user, msg, null, "You don't have permission to mute this user."))) {
264                return;
265            }
266            
267            if (shouldNotModerate(client, user)) {
268                await msg.reply({
269                    embeds: [
270                        {
271                            description: "This user cannot be muted."
272                        }
273                    ]
274                });
275    
276                return;
277            }
278            
279            await mute(client, dateTime, user, msg, timeInterval, reason, hard);
280    
281          const fields = [          const fields = [
282              {              {
# Line 219  export default class MuteCommand extends Line 290  export default class MuteCommand extends
290              {              {
291                  name: "Duration",                  name: "Duration",
292                  value: time === undefined ? "*No duration set*" : (time + '')                  value: time === undefined ? "*No duration set*" : (time + '')
293                },
294                {
295                    name: "Role Takeout",
296                    value: hard ? 'Yes' : 'No'
297              }              }
298          ];          ];
299    
300          console.log(fields);                  console.log(fields);        
301    
302          await msg.reply({          await this.deferReply(msg, {
303              embeds: [              embeds: [
304                  new MessageEmbed()                  new MessageEmbed()
305                  .setAuthor({                  .setAuthor({
# Line 236  export default class MuteCommand extends Line 311  export default class MuteCommand extends
311              ]              ]
312          });          });
313      }      }
 }  
314    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26