/[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 341 - (hide annotations)
Mon Jul 29 17:29:38 2024 UTC (8 months, 2 weeks ago) by rakin
File MIME type: application/typescript
File size: 8767 byte(s)
refactor: removing using the old history manager
1 rakin 125 import { BanOptions, CommandInteraction, ContextMenuInteraction, 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 rakin 86 import Punishment from '../../models/Punishment';
9     import PunishmentType from '../../types/PunishmentType';
10 rakin 51
11     export default class HistoryCommand extends BaseCommand {
12     supportsInteractions: boolean = true;
13 rakin 125 supportsContextMenu = true;
14 rakin 51
15     constructor() {
16 rakin 125 super('history', 'moderation', ['Moderation History']);
17 rakin 51 }
18    
19 rakin 86 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 rakin 336 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 rakin 86
28     let str = '';
29 rakin 336
30     const maxPage = Math.ceil((await Punishment.count({
31     guild_id: msg.guild!.id,
32     user_id: user.id,
33     })) / limit);
34 rakin 86
35     const convert = (type: PunishmentType) => {
36     switch (type) {
37     case PunishmentType.BAN:
38     return 'Ban';
39 rakin 106 case PunishmentType.SOFTBAN:
40     return 'Soft Ban';
41     case PunishmentType.TEMPBAN:
42     return 'Temporary Ban';
43 rakin 197 case PunishmentType.SHOT:
44     return 'Shot';
45 rakin 86 case PunishmentType.MUTE:
46     return 'Mute';
47 rakin 106 case PunishmentType.HARDMUTE:
48     return 'Hardmute';
49 rakin 86 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 rakin 336 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 rakin 86
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 rakin 336 str += `Action Executor: ${log.mod_tag}\n`;
82     str += `Date: ${log.createdAt.toLocaleString('en-US')}\n`;
83 rakin 86
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 rakin 336 if (log.meta) {
89     const json = typeof log.meta === 'string' ? JSON.parse(log.meta) : log.meta;
90 rakin 86
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 rakin 51 async run(client: DiscordClient, msg: Message | CommandInteraction, options: CommandOptions | InteractionOptions) {
192     if (!options.isInteraction && typeof options.args[0] === 'undefined') {
193     await msg.reply({
194     embeds: [
195     new MessageEmbed()
196     .setColor('#f14a60')
197     .setDescription(`This command requires at least one argument.`)
198     ]
199     });
200    
201     return;
202     }
203    
204     let user: User | null | undefined;
205    
206     if (options.isInteraction) {
207     user = await <User> options.options.getUser('user');
208     }
209     else {
210     try {
211     user = await getUser(client, msg as Message, options);
212    
213     if (!user)
214     throw new Error();
215     }
216     catch (e) {
217     console.log(e);
218    
219     await msg.reply({
220     embeds: [
221     new MessageEmbed()
222     .setColor('#f14a60')
223     .setDescription(`Invalid user given.`)
224     ]
225     });
226    
227     return;
228     }
229     }
230    
231 rakin 86 (global as any).user = user;
232 rakin 51
233 rakin 86 let message = <Message> await msg.reply(await this.genEmbed(client, msg, user));
234 rakin 51
235 rakin 86 if (msg instanceof CommandInteraction)
236     message = <Message> await msg.fetchReply();
237 rakin 51
238 rakin 86 const collector = new InteractionCollector(client, {
239     guild: msg.guild!,
240     channel: msg.channel!,
241     max: 20,
242     componentType: 'BUTTON',
243     interactionType: 'MESSAGE_COMPONENT',
244     message,
245     time: 30000,
246     filter(i) {
247     return i.isButton() && i.member?.user.id === msg.member!.user.id;
248     }
249     });
250 rakin 51
251 rakin 86 collector.on('collect', async i => {
252     await this.update(client, i, message);
253     });
254 rakin 51
255 rakin 86 collector.on('end', async () => {
256     try {
257 rakin 125 if (msg instanceof ContextMenuInteraction) {
258     await msg.editReply({
259     components: []
260     });
261     }
262     else {
263     await message.edit({
264     components: []
265     });
266     }
267 rakin 51 }
268 rakin 86 catch (e) {
269     console.log(e);
270     }
271 rakin 51 });
272     }
273 rakin 197 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26