/[sudobot]/branches/2.x/src/commands/moderation/HistoryCommand.ts
ViewVC logotype

Annotation of /branches/2.x/src/commands/moderation/HistoryCommand.ts

Parent Directory Parent Directory | Revision Log Revision Log


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26