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

Diff of /trunk/src/commands/moderation/NotesCommand.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 334 by rakin, Mon Jul 29 17:29:36 2024 UTC
# Line 1  Line 1 
1  import { BanOptions, CommandInteraction, GuildMember, Interaction, Message, User } from 'discord.js';  import { BanOptions, CommandInteraction, EmojiIdentifierResolvable, GuildMember, Interaction, InteractionCollector, Message, MessageActionRow, MessageButton, MessageOptions, ReplyOptions, TextChannel, 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 Note from '../../models/Note';
 import History from '../../automod/History';  
9    
10  export default class NotesCommand extends BaseCommand {  export default class NotesCommand extends BaseCommand {
11      supportsInteractions: boolean = true;      supportsInteractions: boolean = true;
# Line 15  export default class NotesCommand extend Line 14  export default class NotesCommand extend
14          super('notes', 'moderation', []);          super('notes', 'moderation', []);
15      }      }
16    
17        async genEmbed(client: DiscordClient, msg: Message | Interaction, user: User, page: number = 1) {
18            const limit = 5;
19            const offset = ((page < 1 ? 1 : page) - 1) * limit;
20    
21            const notes = await Note.find({
22                guild_id: msg.guild!.id,
23                user_id: user.id,
24            }).skip(offset).limit(limit).sort("createdAt");
25    
26            let str = '';
27            const maxPage = Math.ceil(notes.length / limit);
28    
29            for await (const note of notes) {
30                str += `**Note ID**: ${note.id}\n`;
31                str += `Note taken by: ${note.mod_tag}\n`;
32                str += `Date: ${note.createdAt.toLocaleString()}\n`;
33                str += `Content:\n\`\`\`\n${note.content}\n\`\`\`\n`;
34                str += '\n';
35            }
36    
37            return {
38                embeds: [
39                    new MessageEmbed({
40                        author: {
41                            name: user.tag,
42                            iconURL: user.displayAvatarURL()
43                        },
44                        title: 'Notes',
45                        description: str === '' ? 'No notes.' : str,
46                        timestamp: new Date(),
47                    })
48                ],
49                components: [
50                    this.createActionRow(page, maxPage)
51                ]
52            };
53        }
54    
55        createActionRow(page: number, max: number) {
56            console.log(max);
57            
58            const back = new MessageButton({
59                customId: 'notes-back-',
60                label: '<<',
61                style: 'PRIMARY'
62            });
63    
64            const next = new MessageButton({
65                customId: 'notes-next-',
66                label: '>>',
67                style: 'PRIMARY'
68            });
69    
70            let nextPage = page + 1;
71            console.log(nextPage);
72    
73            if (nextPage > max) {
74                nextPage = max;
75                next.setDisabled(true);
76            }
77            else {
78                next.setDisabled(false);
79            }
80    
81            let prevPage = page - 1;
82            console.log(prevPage);
83    
84            if (prevPage <= 0) {
85                prevPage = 1;
86                back.setDisabled(true);
87            }
88            else {
89                back.setDisabled(false);
90            }
91    
92            next.setCustomId('notes-next-' + nextPage);
93            back.setCustomId('notes-back-' + prevPage);
94    
95            return new MessageActionRow()
96                .addComponents(
97                    back,
98                    next
99                );
100        }
101    
102        async update(client: DiscordClient, interaction: Interaction, message: Message) {
103            console.log('here');
104            
105            if (interaction.isButton() && interaction.customId.startsWith('notes-')) {
106                const splitted = interaction.customId.split('-');
107    
108                if (splitted[2] === undefined || parseInt(splitted[2]) === NaN)
109                    return;
110    
111                if (splitted[1] === 'next' || splitted[1] === 'back') {
112                    const options = await this.genEmbed(client, interaction, (global as any).user, parseInt(splitted[2]));
113                    
114                    try {
115                        await interaction.update(options);
116                    }
117                    catch (e) {
118                        console.log(e);                    
119                    }
120                }
121            }
122        }
123    
124      async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {      async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {
125          if (!options.isInteraction && typeof options.args[0] === 'undefined') {          if (!options.isInteraction && typeof options.args[0] === 'undefined') {
126              await msg.reply({              await msg.reply({
# Line 28  export default class NotesCommand extend Line 134  export default class NotesCommand extend
134              return;              return;
135          }          }
136    
137          let user: GuildMember;          let user: User | null | undefined;
138    
139          if (options.isInteraction) {          if (options.isInteraction) {
140              user = await <GuildMember> options.options.getMember('member');              user = await <User> options.options.getUser('user');
   
             if (!user) {  
                 await msg.reply({  
                     embeds: [  
                         new MessageEmbed()  
                         .setColor('#f14a60')  
                         .setDescription("Invalid user given.")  
                     ]  
                 });  
       
                 return;  
             }  
141          }          }
142          else {          else {
143              try {              try {
144                  const user2 = await getMember((msg as Message), options);                  user = await getUser(client, msg as Message, options);
   
                 if (!user2) {  
                     throw new Error('Invalid user');  
                 }  
145    
146                  user = user2;                  if (!user)
147                        throw new Error();
148              }              }
149              catch (e) {              catch (e) {
150                    console.log(e);
151                    
152                  await msg.reply({                  await msg.reply({
153                      embeds: [                      embeds: [
154                          new MessageEmbed()                          new MessageEmbed()
# Line 63  export default class NotesCommand extend Line 156  export default class NotesCommand extend
156                          .setDescription(`Invalid user given.`)                          .setDescription(`Invalid user given.`)
157                      ]                      ]
158                  });                  });
159        
160                  return;                  return;
161              }              }
   
             console.log(user);  
162          }          }
163    
164          await client.db.all("SELECT * FROM notes WHERE user_id = ? AND guild_id = ?", [user.id, msg.guild!.id], async (err: any, data: any) => {          (global as any).user = user;
             if (err) {  
                 console.log(err);  
             }  
   
             if (data === undefined || data.length < 1) {  
                 await msg.reply({  
                     embeds: [  
                         new MessageEmbed()  
                         .setColor('#f14a60')  
                         .setDescription('No notes found for user ' + user.user.tag)  
                     ]  
                 });  
165    
166                  return;          let message = <Message> await msg.reply(await this.genEmbed(client, msg, user));
             }  
167    
168              let desc = '';          if (msg instanceof CommandInteraction)
169                message = <Message> await msg.fetchReply();
170    
171              for (let row of data) {          const collector = new InteractionCollector(client, {
172                  desc += `\n\n**Note #${row.id}**\n${row.content}\nDate: ${new Date(row.date).toUTCString()}`;              guild: msg.guild!,
173                channel: msg.channel!,
174                max: 20,
175                componentType: 'BUTTON',
176                interactionType: 'MESSAGE_COMPONENT',
177                message,
178                time: 30000,
179                filter(i) {
180                    return i.isButton() && i.member?.user.id === msg.member!.user.id;
181              }              }
182            });
183    
184              desc = desc.substring(1);          collector.on('collect', async i => {
185                await this.update(client, i, message);
186            });
187    
188              await msg.reply({          collector.on('end', async () => {
189                  embeds: [              try {
190                      new MessageEmbed()                  await message.edit({
191                      .setAuthor({                      components: []
192                          iconURL: user.displayAvatarURL(),                  });
193                          name: user.user.tag              }
194                      })              catch (e) {
195                      .setDescription(desc)                  console.log(e);                
196                  ]              }
             });  
197          });          });
198      }      }
199  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26