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

Annotation of /trunk/src/commands/moderation/HistoryCommand.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 105 - (hide annotations)
Mon Jul 29 17:28:37 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 8400 byte(s)
Fix history command
1 rakin 86 import { BanOptions, CommandInteraction, EmojiIdentifierResolvable, GuildMember, Interaction, InteractionCollector, Message, MessageActionRow, MessageButton, MessageOptions, ReplyOptions, TextChannel, User } from 'discord.js';
2 rakin 51 import BaseCommand from '../../utils/structures/BaseCommand';
3     import DiscordClient from '../../client/Client';
4     import CommandOptions from '../../types/CommandOptions';
5     import InteractionOptions from '../../types/InteractionOptions';
6     import MessageEmbed from '../../client/MessageEmbed';
7     import getUser from '../../utils/getUser';
8     import getMember from '../../utils/getMember';
9     import History from '../../automod/History';
10     import { fetchEmoji } from '../../utils/Emoji';
11 rakin 86 import Punishment from '../../models/Punishment';
12     import PunishmentType from '../../types/PunishmentType';
13 rakin 51
14     export default class HistoryCommand extends BaseCommand {
15     supportsInteractions: boolean = true;
16    
17     constructor() {
18     super('history', 'moderation', []);
19     }
20    
21 rakin 86 async genEmbed(client: DiscordClient, msg: Message | Interaction, user: User, page: number = 1) {
22     const limit = 3;
23     const offset = ((page < 1 ? 1 : page) - 1) * limit;
24    
25     const logs = await Punishment.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(logs.count / limit);
39    
40     const convert = (type: PunishmentType) => {
41     switch (type) {
42     case PunishmentType.BAN:
43     return 'Ban';
44     case PunishmentType.BEAN:
45     return 'Bean';
46     case PunishmentType.MUTE:
47     return 'Mute';
48     case PunishmentType.KICK:
49     return 'Kick';
50     case PunishmentType.WARNING:
51     return 'Warning';
52     case PunishmentType.UNBAN:
53     return 'Unban';
54     case PunishmentType.UNMUTE:
55     return 'Unmute';
56     default:
57     return "Unknown";
58     }
59     };
60    
61     for await (const log of logs.rows) {
62     str += `**Case ID**: ${log.get().id}\n`;
63     str += `Type: ${convert(log.get().type)}\n`;
64     str += `Reason: ${log.get().reason ? (log.get().reason.trim() === '' ? '*No reason provided*' : log.get().reason) : '*No reason provided*'}\n`;
65    
66     // let mod_tag;
67    
68     // try {
69     // const mod = await client.users.fetch(log.get().mod_id);
70    
71     // if (!mod)
72     // throw new Error();
73    
74     // mod_tag = mod.tag;
75     // }
76     // catch (e) {
77     // mod_tag = log.get().mod_id;
78     // }
79    
80     str += `Action Executor: ${log.get().mod_tag}\n`;
81     str += `Date: ${log.get().createdAt.toLocaleString('en-US')}\n`;
82    
83     // if (log.get().type === PunishmentType.MUTE) {
84     // str += `Duration: ${(log.get().meta ? JSON.parse(log.get().meta) : {})?.time ?? '*No duration set*'}\n`;
85     // }
86    
87     if (log.get().meta) {
88 rakin 105 const json = typeof log.get().meta === 'string' ? JSON.parse(log.get().meta) : log.get().meta;
89 rakin 86
90     if (Object.keys(json).length > 0) {
91     str += "Additional Attributes:\n```\n";
92    
93     for (const key in json) {
94     str += `${key}: ${json[key]}\n`;
95     }
96    
97     str += '\n```\n';
98     }
99     }
100    
101     str += '\n';
102     }
103    
104     return {
105     embeds: [
106     new MessageEmbed({
107     author: {
108     name: user.tag,
109     iconURL: user.displayAvatarURL()
110     },
111     title: 'Moderation History',
112     description: str === '' ? 'No history.' : str,
113     timestamp: new Date(),
114     })
115     ],
116     components: [
117     this.createActionRow(page, maxPage)
118     ]
119     };
120     }
121    
122     createActionRow(page: number, max: number) {
123     console.log(max);
124    
125     const back = new MessageButton({
126     customId: 'history-back-',
127     label: '<<',
128     style: 'PRIMARY'
129     });
130    
131     const next = new MessageButton({
132     customId: 'history-next-',
133     label: '>>',
134     style: 'PRIMARY'
135     });
136    
137     let nextPage = page + 1;
138     console.log(nextPage);
139    
140     if (nextPage > max) {
141     nextPage = max;
142     next.setDisabled(true);
143     }
144     else {
145     next.setDisabled(false);
146     }
147    
148     let prevPage = page - 1;
149     console.log(prevPage);
150    
151     if (prevPage <= 0) {
152     prevPage = 1;
153     back.setDisabled(true);
154     }
155     else {
156     back.setDisabled(false);
157     }
158    
159     next.setCustomId('history-next-' + nextPage);
160     back.setCustomId('history-back-' + prevPage);
161    
162     return new MessageActionRow()
163     .addComponents(
164     back,
165     next
166     );
167     }
168    
169     async update(client: DiscordClient, interaction: Interaction, message: Message) {
170     console.log('here');
171    
172     if (interaction.isButton() && interaction.customId.startsWith('history-')) {
173     const splitted = interaction.customId.split('-');
174    
175     if (splitted[2] === undefined || parseInt(splitted[2]) === NaN)
176     return;
177    
178     if (splitted[1] === 'next' || splitted[1] === 'back') {
179     const options = await this.genEmbed(client, interaction, (global as any).user, parseInt(splitted[2]));
180     try {
181     await interaction.update(options);
182     }
183     catch (e) {
184     console.log(e);
185     }
186     }
187     }
188     }
189    
190 rakin 51 async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {
191     if (!options.isInteraction && typeof options.args[0] === 'undefined') {
192     await msg.reply({
193     embeds: [
194     new MessageEmbed()
195     .setColor('#f14a60')
196     .setDescription(`This command requires at least one argument.`)
197     ]
198     });
199    
200     return;
201     }
202    
203     let user: User | null | undefined;
204    
205     if (options.isInteraction) {
206     user = await <User> options.options.getUser('user');
207     }
208     else {
209     try {
210     user = await getUser(client, msg as Message, options);
211    
212     if (!user)
213     throw new Error();
214     }
215     catch (e) {
216     console.log(e);
217    
218     await msg.reply({
219     embeds: [
220     new MessageEmbed()
221     .setColor('#f14a60')
222     .setDescription(`Invalid user given.`)
223     ]
224     });
225    
226     return;
227     }
228     }
229    
230 rakin 86 (global as any).user = user;
231 rakin 51
232 rakin 86 let message = <Message> await msg.reply(await this.genEmbed(client, msg, user));
233 rakin 51
234 rakin 86 if (msg instanceof CommandInteraction)
235     message = <Message> await msg.fetchReply();
236 rakin 51
237 rakin 86 const collector = new InteractionCollector(client, {
238     guild: msg.guild!,
239     channel: msg.channel!,
240     max: 20,
241     componentType: 'BUTTON',
242     interactionType: 'MESSAGE_COMPONENT',
243     message,
244     time: 30000,
245     filter(i) {
246     return i.isButton() && i.member?.user.id === msg.member!.user.id;
247     }
248     });
249 rakin 51
250 rakin 86 collector.on('collect', async i => {
251     await this.update(client, i, message);
252     });
253 rakin 51
254 rakin 86 collector.on('end', async () => {
255     try {
256     await message.edit({
257     components: []
258     });
259 rakin 51 }
260 rakin 86 catch (e) {
261     console.log(e);
262     }
263 rakin 51 });
264     }
265     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26