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

Diff of /trunk/src/commands/moderation/HistoryCommand.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, EmojiIdentifierResolvable, GuildMember, Interaction, Message, TextChannel, User } from 'discord.js';  import { CommandInteraction, ContextMenuInteraction, Interaction, InteractionCollector, Message, MessageActionRow, MessageButton, User } 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';
8  import getMember from '../../utils/getMember';  import Punishment from '../../models/Punishment';
9  import History from '../../automod/History';  import PunishmentType from '../../types/PunishmentType';
 import { fetchEmoji } from '../../utils/Emoji';  
10    
11  export default class HistoryCommand extends BaseCommand {  export default class HistoryCommand extends BaseCommand {
12      supportsInteractions: boolean = true;      supportsInteractions: boolean = true;
13        supportsContextMenu = true;
14    
15      constructor() {      constructor() {
16          super('history', 'moderation', []);          super('history', 'moderation', ['Moderation History']);
17        }
18    
19        async genEmbed(client: DiscordClient, msg: Message | Interaction, user: User, page: number = 1) {
20            const limit = 3;
21            const offset = ((page < 1 ? 1 : page) - 1) * limit;
22    
23            const logs = await Punishment.find({
24                guild_id: msg.guild!.id,
25                user_id: user.id,
26            }).skip(offset).limit(limit).sort({ createdAt: -1 });
27    
28            let str = '';
29            
30            const maxPage = Math.ceil((await Punishment.count({
31                guild_id: msg.guild!.id,
32                user_id: user.id,
33            })) / limit);
34    
35            const convert = (type: PunishmentType) => {            
36                switch (type) {
37                    case PunishmentType.BAN:
38                        return 'Ban';
39                    case PunishmentType.SOFTBAN:
40                        return 'Soft Ban';
41                    case PunishmentType.TEMPBAN:
42                        return 'Temporary Ban';
43                    case PunishmentType.SHOT:
44                        return 'Shot';
45                    case PunishmentType.MUTE:
46                        return 'Mute';
47                    case PunishmentType.HARDMUTE:
48                        return 'Hardmute';
49                    case PunishmentType.KICK:
50                        return 'Kick';
51                    case PunishmentType.WARNING:
52                        return 'Warning';
53                    case PunishmentType.UNBAN:
54                        return 'Unban';
55                    case PunishmentType.UNMUTE:
56                        return 'Unmute';
57                    default:
58                        return "Unknown";
59                }
60            };
61    
62            for await (const log of logs) {
63                str += `**Case ID**: ${log.id}\n`;
64                str += `Type: ${convert(log.type as PunishmentType)}\n`;
65                str += `Reason: ${log.reason ? (log.reason.trim() === '' ? '*No reason provided*' : log.reason) : '*No reason provided*'}\n`;
66    
67                // let mod_tag;
68    
69                // try {
70                //     const mod = await client.users.fetch(log.get().mod_id);
71    
72                //     if (!mod)
73                //         throw new Error();
74    
75                //     mod_tag = mod.tag;
76                // }
77                // catch (e) {
78                //     mod_tag = log.get().mod_id;
79                // }
80    
81                str += `Action Executor: ${log.mod_tag}\n`;
82                str += `Date: ${log.createdAt.toLocaleString('en-US')}\n`;
83    
84                // if (log.get().type === PunishmentType.MUTE) {
85                //     str += `Duration: ${(log.get().meta ? JSON.parse(log.get().meta) : {})?.time ?? '*No duration set*'}\n`;              
86                // }
87    
88                if (log.meta) {
89                    const json = typeof log.meta === 'string' ? JSON.parse(log.meta) : log.meta;
90    
91                    if (Object.keys(json).length > 0) {
92                        str += "Additional Attributes:\n```\n";
93    
94                        for (const key in json) {
95                            str += `${key}: ${json[key]}\n`;
96                        }
97    
98                        str += '\n```\n';
99                    }
100                }
101    
102                str += '\n';
103            }
104    
105            return {
106                embeds: [
107                    new MessageEmbed({
108                        author: {
109                            name: user.tag,
110                            iconURL: user.displayAvatarURL()
111                        },
112                        title: 'Moderation History',
113                        description: str === '' ? 'No history.' : str,
114                        timestamp: new Date(),
115                    })
116                ],
117                components: [
118                    this.createActionRow(page, maxPage)
119                ]
120            };
121        }
122    
123        createActionRow(page: number, max: number) {
124            console.log(max);
125            
126            const back = new MessageButton({
127                customId: 'history-back-',
128                label: '<<',
129                style: 'PRIMARY'
130            });
131    
132            const next = new MessageButton({
133                customId: 'history-next-',
134                label: '>>',
135                style: 'PRIMARY'
136            });
137    
138            let nextPage = page + 1;
139            console.log(nextPage);
140    
141            if (nextPage > max) {
142                nextPage = max;
143                next.setDisabled(true);
144            }
145            else {
146                next.setDisabled(false);
147            }
148    
149            let prevPage = page - 1;
150            console.log(prevPage);
151    
152            if (prevPage <= 0) {
153                prevPage = 1;
154                back.setDisabled(true);
155            }
156            else {
157                back.setDisabled(false);
158            }
159    
160            next.setCustomId('history-next-' + nextPage);
161            back.setCustomId('history-back-' + prevPage);
162    
163            return new MessageActionRow()
164                .addComponents(
165                    back,
166                    next
167                );
168        }
169    
170        async update(client: DiscordClient, interaction: Interaction, message: Message) {
171            console.log('here');
172            
173            if (interaction.isButton() && interaction.customId.startsWith('history-')) {
174                const splitted = interaction.customId.split('-');
175    
176                if (splitted[2] === undefined || parseInt(splitted[2]) === NaN)
177                    return;
178    
179                if (splitted[1] === 'next' || splitted[1] === 'back') {
180                    const options = await this.genEmbed(client, interaction, (global as any).user, parseInt(splitted[2]));
181                    try {
182                        await interaction.update(options);
183                    }
184                    catch (e) {
185                        console.log(e);                    
186                    }
187                }
188            }
189      }      }
190    
191      async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {      async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {
# Line 56  export default class HistoryCommand exte Line 228  export default class HistoryCommand exte
228              }              }
229          }          }
230    
231          History.get(user.id, msg.guild!, async (data) => {          (global as any).user = user;
             let str = '';  
232    
233              for await (const row of data) {          let message = <Message> await msg.reply(await this.genEmbed(client, msg, user));
                 let mod: User | string | undefined;  
234    
235                  try {          if (msg instanceof CommandInteraction)
236                      mod = await client.users.fetch(row.mod_id);              message = <Message> await msg.fetchReply();
237    
238                      if (!mod) {          const collector = new InteractionCollector(client, {
239                          throw new Error();              guild: msg.guild!,
240                      }              channel: msg.channel!,
241                  }              max: 20,
242                  catch (e) {              componentType: 'BUTTON',
243                      console.log(e);              interactionType: 'MESSAGE_COMPONENT',
244                                    message,
245                      user = row.user_id;              time: 30000,
246                      mod = row.mod_id;              filter(i) {
247                  }                  return i.isButton() && i.member?.user.id === msg.member!.user.id;
248                }
249                  str += `\`[${new Date(row.date).toLocaleString()}]\` \`[${typeof mod === 'string' ? mod : mod?.tag}]\` `;          });
250    
251                  let type: string;          collector.on('collect', async i => {
252                await this.update(client, i, message);
253            });
254    
255                  if (row.type === 'ban') {          collector.on('end', async () => {
256                      type = 'Banned';              try {
257                  }                  if (msg instanceof ContextMenuInteraction) {
258                  else if (row.type === 'unban') {                      await msg.editReply({
259                      type = 'Unbanned';                          components: []
260                  }                      });
                 else if (row.type === 'kick') {  
                     type = 'Kicked';  
                 }  
                 else if (row.type === 'mute') {  
                     type = 'Muted';  
                 }  
                 else if (row.type === 'unmute') {  
                     type = 'Unmuted';  
                 }  
                 else if (row.type === 'bean') {  
                     type = 'Beaned';  
                 }  
                 else if (row.type === 'warn') {  
                     type = 'Warned';  
261                  }                  }
262                  else {                  else {
263                      type = 'Deleted warning for';                      await message.edit({
264                            components: []
265                        });
266                  }                  }
   
                 str += `\`${type}\` \`${typeof user === 'string' ? user : user?.tag}\` \`[Reason: ${row.reason ? row.reason : "No reason provided"}]\`\n`;  
267              }              }
268                catch (e) {
269              await msg.reply({                  console.log(e);                
270                  embeds: [              }
                     new MessageEmbed()  
                     .setAuthor({  
                         name: user!.tag,  
                         iconURL: user?.displayAvatarURL()!  
                     })  
                     .setTitle('Moderation history')  
                     .setDescription(str == '' ? 'No history' : str)  
                 ]  
             });  
271          });          });
272      }      }
 }  
273    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26