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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26