DiscordTickets/src/autocomplete/ticket.js

83 lines
2.2 KiB
JavaScript
Raw Normal View History

/* eslint-disable no-underscore-dangle */
2022-08-02 23:13:32 +03:00
const { Autocompleter } = require('@eartharoid/dbf');
2022-08-17 22:41:51 +03:00
const emoji = require('node-emoji');
const Cryptr = require('cryptr');
2022-10-24 19:44:07 +03:00
const { decrypt } = new Cryptr(process.env.ENCRYPTION_KEY);
const Keyv = require('keyv');
const ms = require('ms');
2022-08-02 23:13:32 +03:00
module.exports = class TicketCompleter extends Autocompleter {
constructor(client, options) {
super(client, {
...options,
id: 'ticket',
});
this.cache = new Keyv();
2022-08-02 23:13:32 +03:00
}
async getOptions(value, {
guildId,
open,
userId,
}) {
/** @type {import("client")} */
const client = this.client;
const cacheKey = [guildId, userId, open].join('/');
let tickets = await this.cache.get(cacheKey);
if (!tickets) {
2022-10-26 02:46:07 +03:00
const { locale } = await client.prisma.guild.findUnique({
select: { locale: true },
where: { id: guildId },
});
tickets = await client.prisma.ticket.findMany({
include: {
category: {
select: {
emoji: true,
name: true,
},
},
},
where: {
createdById: userId,
guildId,
open,
},
});
tickets = tickets.map(ticket => {
2022-10-26 02:46:07 +03:00
const date = new Date(ticket.createdAt).toLocaleString([locale, 'en-GB'], { dateStyle: 'short' });
2023-01-03 18:59:26 +02:00
const topic = ticket.topic ? '- ' + decrypt(ticket.topic).replace(/\n/g, ' ').substring(0, 50) : '';
const category = emoji.hasEmoji(ticket.category.emoji) ? emoji.get(ticket.category.emoji) + ' ' + ticket.category.name : ticket.category.name;
ticket._name = `${category} #${ticket.number} (${date}) ${topic}`;
return ticket;
});
this.cache.set(cacheKey, tickets, ms('1m'));
}
const options = value ? tickets.filter(t => t._name.match(new RegExp(value, 'i'))) : tickets;
return options
.slice(0, 25)
.map(t => ({
name: t._name,
value: t.id,
}));
2022-10-24 22:17:40 +03:00
}
2022-08-14 01:58:41 +03:00
/**
* @param {string} value
2022-09-04 23:00:18 +03:00
* @param {*} command
2022-08-14 01:58:41 +03:00
* @param {import("discord.js").AutocompleteInteraction} interaction
*/
2022-09-04 23:00:18 +03:00
async run(value, command, interaction) {
2022-08-14 01:58:41 +03:00
await interaction.respond(
await this.getOptions(value, {
guildId: interaction.guild.id,
open: ['add', 'close', 'force-close', 'remove'].includes(command.name), // false for `new`, `transcript` etc
userId: interaction.user.id,
}),
2022-08-14 01:58:41 +03:00
);
}
2022-08-02 23:13:32 +03:00
};