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

Diff of /trunk/src/commands/moderation/ClearCommand.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 344 by rakin, Mon Jul 29 17:29:40 2024 UTC
# Line 1  Line 1 
1  import { BanOptions, CommandInteraction, Emoji, GuildMember, Interaction, Message, TextChannel, User } from 'discord.js';  import { CommandInteraction, Emoji, GuildChannel, Message, TextChannel, User, Permissions } from 'discord.js';
2  import BaseCommand from '../../utils/structures/BaseCommand';  import BaseCommand from '../../utils/structures/BaseCommand';
3  import DiscordClient from '../../client/Client';  import DiscordClient from '../../client/Client';
4  import CommandOptions from '../../types/CommandOptions';  import CommandOptions from '../../types/CommandOptions';
5  import InteractionOptions from '../../types/InteractionOptions';  import InteractionOptions from '../../types/InteractionOptions';
6  import MessageEmbed from '../../client/MessageEmbed';  import MessageEmbed from '../../client/MessageEmbed';
7  import getUser from '../../utils/getUser';  import getUser from '../../utils/getUser';
 import getMember from '../../utils/getMember';  
 import History from '../../automod/History';  
8  import { fetchEmoji } from '../../utils/Emoji';  import { fetchEmoji } from '../../utils/Emoji';
9    import { hasPermission, shouldNotModerate } from '../../utils/util';
10    
11  export default class ClearCommand extends BaseCommand {  export default class ClearCommand extends BaseCommand {
12      supportsInteractions: boolean = true;      supportsInteractions: boolean = true;
13        permissions = [Permissions.FLAGS.MANAGE_MESSAGES];
14    
15      constructor() {      constructor() {
16          super('clear', 'moderation', []);          super('clear', 'moderation', []);
# Line 29  export default class ClearCommand extend Line 29  export default class ClearCommand extend
29              return;              return;
30          }          }
31    
32          let member: GuildMember | undefined | null;          let user: User | undefined | null;
33            let msgCount = 0, channel: GuildChannel = msg.channel! as GuildChannel;
34    
35          if (options.isInteraction) {          if (options.isInteraction) {
36              member = <GuildMember> await options.options.getMember('member');              if (options.options.getUser('user'))
37                    user = <User> options.options.getUser('user');
38    
39                console.log(user?.tag);            
40    
41                if (options.options.getChannel('channel')) {
42                    channel = <GuildChannel> options.options.getChannel('channel');
43    
44                    if (channel.type !== 'GUILD_TEXT' && channel.type !== 'GUILD_NEWS' && channel.type !== 'GUILD_PUBLIC_THREAD' && channel.type !== 'GUILD_PRIVATE_THREAD') {
45                        await msg.reply({
46                            content: 'Invalid channel given.'
47                        });
48                        
49                        return;
50                    }
51                }
52    
53                if (options.options.getInteger('count')) {
54                    msgCount = <number> options.options.getInteger('count');
55                }
56          }          }
57          else {          else {
58              try {              try {
59                  member = await getMember(msg as Message, options);                  user = await getUser(client, msg as Message, options);
60    
61                  if (!member) {                  if (!user) {
62                      throw new Error();                      throw new Error();
63                  }                  }
64              }              }
# Line 56  export default class ClearCommand extend Line 76  export default class ClearCommand extend
76                  return;                  return;
77              }              }
78          }          }
79            
80            if (msgCount === 0 && !user) {
81                await msg.reply({
82                    embeds: [
83                        new MessageEmbed()
84                        .setColor('#f14a60')
85                        .setDescription('You have to specify either the message count or the user.')
86                    ]
87                });
88    
89                return;
90            }
91    
92            if (user) {
93                try {
94                    const member = await msg.guild?.members.fetch(user.id);
95    
96                    if (member && !(await hasPermission(client, member, msg, null, "You don't have permission to clear messages from this user.")))
97                        return;
98    
99                    if (member && shouldNotModerate(client, member)) {
100                        await msg.reply({
101                            embeds: [
102                                { description: "Cannot clear messages from this user: Operation not permitted" }
103                            ]
104                        });
105                        
106                        return;
107                    }
108                }
109                catch (e) {
110                    console.log(e);
111                }
112            }
113    
         let fetched;  
114          let count = 0;          let count = 0;
115            (global as any).deletingMessages = true;
116    
117          const message = await msg.reply({          let message = await msg.reply({
118              embeds: [              embeds: [
119                  new MessageEmbed()                  new MessageEmbed()
120                  .setColor('GOLD')                  .setColor('GOLD')
121                  .setDescription('Deleting messages...')                  .setDescription((await fetchEmoji('loading'))?.toString() + ' Deleting messages...')
122              ]              ]
123          });          });
124    
125          do {          if (msg instanceof CommandInteraction)
126              fetched = await msg.channel!.messages.fetch({ limit: 100 });              message = <Message> await msg.fetchReply();
127              fetched = await fetched.filter(m => m.author.id === member!.id);  
128              await (msg.channel as TextChannel).bulkDelete(fetched);          if (msgCount === 0 && user) {
129              count += await fetched.size;              console.log(user?.tag);
130                
131                let fetched;
132    
133                do {
134                    fetched = await (channel as TextChannel).messages.fetch({ limit: 100 });
135                    fetched = await fetched.filter(m => m.author.id === user!.id && m.id !== message!.id && (Date.now() - m.createdTimestamp) <= (2 * 7 * 24 * 60 * 60 * 1000));
136                    await (channel as TextChannel).bulkDelete(fetched);
137                    count += fetched.size;
138    
139                    /*for await (const [id, m] of fetched.entries()) {
140                        try {
141                            await m.delete();
142                            count++;
143                        }
144                        catch (e) {
145                            console.log('Error deleting message', e);
146                        }
147                    }
148                    */
149                    
150                    await new Promise(r => setTimeout(r, 900));
151                }
152                while (fetched.size >= 2);
153            }
154            else {
155                let fetched = 0;
156                let safeLimit = 0, safeLimit2 = 0;
157    
158                do {
159                    if (count >= msgCount || safeLimit >= 50) {
160                        break;
161                    }
162    
163                    try {
164                        const data = await (channel as TextChannel).messages.fetch({ limit: 100 });
165    
166                        fetched = 0;
167    
168                        for await (const [id, m] of data.entries()) {
169                            try {
170                                if (count >= msgCount || safeLimit2 > 200) {
171                                    break;
172                                }
173    
174                                if (user && m.author?.id !== user?.id) {
175                                    continue;
176                                }
177    
178                                if (message!.id === m.id || (Date.now() - m.createdTimestamp) > (2 * 7 * 24 * 60 * 60 * 1000))
179                                    continue;
180    
181                                if (m.deletable) {
182                                    console.log('here', user?.tag);
183                                    
184                                    await m.delete();
185    
186                                    fetched++;
187                                    count++;
188                                    safeLimit2++;
189                                }
190    
191                                if (count % 10 === 0) {
192                                    await new Promise(r => setTimeout(r, 1100));
193                                }
194                            }
195                            catch(e) {
196                                console.log(e);
197                                safeLimit2 += 100;
198                            }
199                        }
200                    }
201                    catch(e) {
202                        console.log(e);
203                        
204                        break;
205                    }
206    
207                    safeLimit++;
208                }
209                while (fetched >= 2);
210          }          }
         while (fetched.size >= 2);  
211    
212          const messageOptions = {          const messageOptions = {
213              embeds: [              embeds: [
214                  new MessageEmbed()                  new MessageEmbed()
215                  .setColor('GREEN')                  .setColor('GREEN')
216                  .setDescription((await fetchEmoji('check') as Emoji).toString() + " Deleted " + count + " message(s) from user " + member.user.tag)                  .setDescription((await fetchEmoji('check') as Emoji).toString() + " Deleted " + count + " message(s)" + (user ? " from user " + user.tag : ''))
217              ]              ]
218          };          };
219    
# Line 90  export default class ClearCommand extend Line 223  export default class ClearCommand extend
223          else {          else {
224              await message!.edit(messageOptions);              await message!.edit(messageOptions);
225          }          }
226    
227            setTimeout(async () => {
228                try {
229                    if (msg instanceof Message)
230                        await msg.delete();
231                }
232                catch (e) {
233                    console.log(e);                
234                }
235                
236                try {
237                    await message!.delete();
238                }
239                catch (e) {
240                    console.log(e);                
241                }
242            }, 5500);
243    
244            (global as any).deletingMessages = false;
245      }      }
 }  
246    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26