Something went wrong. Try again.
A Discord bot designed to entertain your server esmbot.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346import { type AnyTextableChannel, type Attachment, AttachmentFlags, CommandInteraction, Constants, type JSONAttachment, type Message, type RawAttachment, type User,} from "oceanic.js";import messages from "#config/messages.json" with { type: "json" };import { pendingCommands, runningCommands, selectedImages } from "#utils/collections.js";import { convFlagType } from "#utils/handler.js";import { getAllLocalizations } from "#utils/i18n.js";import logger from "#utils/logger.js";import { runMediaJob } from "#utils/media.js";import mediaDetect from "#utils/mediadetect.js";import { maxFileSize, random } from "#utils/misc.js";import { getEnv } from "#utils/runtime.js";import { clean, isEmpty } from "#utils/sanitize.js";import { upload } from "#utils/tempimages.js";import type { CommandFlag, MediaParams, MediaMeta, MediaTypes } from "#utils/types.js";import Command from "./command.ts";
class MediaCommand extends Command { params?: object;
paramsFunc(): object { return {}; }
async criteria(_text?: string | number | boolean | User | Attachment) { return true; }
async run() { this.success = false;
if (!this.permissions.has("ATTACH_FILES")) return this.getString("permissions.noAttachFiles");
const timestamp = this.type === "application" && this.interaction ? CommandInteraction.getCreatedAt(this.interaction.id) : (this.message?.createdAt ?? new Date()); // check if this command has already been run in this channel with the same arguments, and we are awaiting its result // if so, don't re-run it const running = runningCommands.get(this.author?.id); if (running && running.getTime() - timestamp.getTime() < 5000) { return this.getString("image.slowDown"); }
await this.acknowledge();
// before awaiting the command result, add this command to the set of running commands runningCommands.set(this.author.id, timestamp); pendingCommands.delete(this.author.id);
const staticProps = this.constructor as typeof MediaCommand;
const ephemeral = this.getOptionBoolean("ephemeral"); const spoiler = this.getOptionBoolean("spoiler"); const sizeLimit = this.interaction?.attachmentSizeLimit ?? maxFileSize(this.guild); const canUseSelection = !this.getOptionAttachment("image") && !this.getOptionString("link"); let mediaParams: MediaParams;
if (staticProps.requiresMedia) { try { let selection: MediaMeta | undefined; if (canUseSelection) { selection = selectedImages.get(this.author.id); } const media = selection && !selection.result ? [selection] : await mediaDetect(this.client, this.permissions, this.message, this.interaction).catch((e) => { if (e.name === "AbortError") { runningCommands.delete(this.author.id); return this.getString("image.timeout"); } if (selection) return []; throw e; }); if (typeof media === "string") return media; if (selection && selection.result) { media.push(selection); } if (media.length === 0) { runningCommands.delete(this.author.id); if (canUseSelection) { pendingCommands.set(this.author.id, new staticProps(this.client, this.database, this.origOptions)); } return `${this.getString(`commands.noImage.${this.cmdName}`, { returnNull: true }) || this.getString("image.noImage", { returnNull: true }) || staticProps.noImage} ${this.getString("image.tip", { params: { name: this.client.user.globalName ?? this.client.user.username } })}`; } selectedImages.delete(this.author.id); mediaParams = { cmd: staticProps.command, params: {}, id: (this.interaction ?? this.message)?.id ?? Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(), inputs: media, spoiler, token: this.interaction?.token, filesize: sizeLimit, }; } catch (e) { runningCommands.delete(this.author.id); throw e; } } else { mediaParams = { cmd: staticProps.command, params: {}, inputs: [], id: (this.interaction ?? this.message)?.id ?? Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(), spoiler, token: this.interaction?.token, filesize: sizeLimit, }; }
if (staticProps.requiresParam) { const text = this.getOption( staticProps.requiredParam, convFlagType(staticProps.requiredParamType), staticProps.requiredParamType !== Constants.ApplicationCommandOptionTypes.STRING && staticProps.requiredParamType !== "string", ) ?? this.args.join(" ").trim(); if (!text || (typeof text === "string" && isEmpty(text)) || !(await this.criteria(text))) { runningCommands.delete(this.author?.id); return ( this.getString(`commands.noParam.${this.cmdName}`, { returnNull: true }) || this.getString("image.noParam", { returnNull: true }) || staticProps.noParam ); } }
mediaParams.params = { togif: !!this.getOptionBoolean("togif"), ...(this.params ?? this.paramsFunc()), };
let status: Message | undefined; if (this.message) { status = await this.processMessage( this.message.channel ?? (await this.client.rest.channels.get(this.message.channelID)), ); }
try { const result = await runMediaJob(mediaParams); const buffer = result.buffer; const type = result.type; if (type === "sent") { if (buffer.length > 2 && this.interaction && this.interaction.authorizingIntegrationOwners[0] === undefined) { const attachment = JSON.parse(buffer.toString()) as RawAttachment & JSONAttachment; const path = new URL(attachment.proxy_url ?? attachment.proxyURL); path.searchParams.set("animated", "true"); selectedImages.set(this.interaction.user.id, { path: path.toString(), spoiler: !!(attachment.flags & AttachmentFlags.IS_SPOILER), result: true, }); } return; } if (type === "large") return this.getString("image.large"); if (type === "frames") return this.getString("image.frames"); if (type === "small") return this.getString("image.small"); if (type === "avis") return this.getString("image.animatedAVIF"); if (type === "unknown") return this.getString("image.unknown"); if (type === "noresult") return this.getString("image.noResult"); if (type === "ratelimit") return this.getString("image.ratelimit"); if (type === "nocmd") return this.getString("image.nocmd"); if (type === "noanim") return this.getString("image.noanim"); if (type === "nomedia") { if (canUseSelection) { pendingCommands.set(this.author.id, new staticProps(this.client, this.database, this.origOptions)); } return `${this.getString(`commands.noImage.${this.cmdName}`, { returnNull: true }) || this.getString("image.noImage", { returnNull: true }) || staticProps.noImage} ${this.getString("image.tip", { params: { name: this.client.user.globalName ?? this.client.user.username } })}`; } if (type === "empty") return staticProps.empty;
this.success = true; const flags = ephemeral ? 64 : undefined;
if (type === "text") { return { content: `\`\`\`\n${clean(buffer.toString("utf8"), [], true)}\n\`\`\``, flags, }; }
const file = { contents: buffer, name: `${spoiler || result.spoiler ? "SPOILER_" : ""}${staticProps.command}.${type}`, }; if (buffer.length > sizeLimit) { const tempdir = getEnv("TEMPDIR"); if (tempdir && this.permissions.has("EMBED_LINKS")) { if (this.interaction) { await upload(this.client, { ...file, flags }, this.interaction, tempdir); } else if (this.message) { await upload(this.client, { ...file, flags }, this.message, tempdir); } } else { return { content: this.getString("image.noTempServer"), flags: 64, }; } } else { return { files: [file], flags, }; } } catch (e) { const err = e as Error; const errString = err.toString(); if (errString.includes("media_not_working")) return this.getString("image.notWorking"); if (errString.includes("Request ended prematurely due to a closed connection")) return this.getString("image.tryAgain"); if (errString.includes("image_pixel_limit")) return this.getString("image.pixelLimit"); if (errString.includes("media_job_killed") || errString.includes("Timeout")) return this.getString("image.tooLong"); if (errString.includes("No available servers")) return this.getString("image.noServers"); throw err; } finally { if (status) await status.delete().catch((e) => logger.warn(`Failed to delete status message: ${e}`)); runningCommands.delete(this.author?.id); } }
async finalize(res?: Message) { if (!this.interaction || !res) return; const attachment = res.attachments.first(); if (attachment) { const path = new URL(attachment.proxyURL); path.searchParams.set("animated", "true"); selectedImages.set(this.interaction.user.id, { path: path.toString(), spoiler: !!(attachment.flags & AttachmentFlags.IS_SPOILER), result: true, }); } }
processMessage(channel: AnyTextableChannel): Promise<Message> { return channel.createMessage({ content: `${random(messages.emotes) || "⚙️"} ${this.getString("image.processing")}`, }); }
static addTextParam(maxLen?: number) { this.flags.unshift({ name: "text", nameLocalizations: getAllLocalizations("image.flagNames.text"), type: Constants.ApplicationCommandOptionTypes.STRING, description: "The text to put on the image", descriptionLocalizations: getAllLocalizations("image.flags.text"), maxLength: maxLen ?? 4096, required: !this.textOptional, classic: true, }); }
static init() { this.flags = []; if (this.requiresMedia) { this.flags.push( { name: "image", nameLocalizations: getAllLocalizations("image.flagNames.image"), type: Constants.ApplicationCommandOptionTypes.ATTACHMENT, fileTypes: this.supportedTypes, description: "An image/GIF attachment", descriptionLocalizations: getAllLocalizations("image.flags.image"), }, { name: "link", nameLocalizations: getAllLocalizations("image.flagNames.link"), type: Constants.ApplicationCommandOptionTypes.STRING, description: "An image/GIF URL", descriptionLocalizations: getAllLocalizations("image.flags.link"), }, ); } if (!this.alwaysGIF) { this.flags.push({ name: "togif", nameLocalizations: getAllLocalizations("image.flagNames.togif"), type: Constants.ApplicationCommandOptionTypes.BOOLEAN, description: "Force GIF output", descriptionLocalizations: getAllLocalizations("image.flags.togif"), }); }
this.flags.push( { name: "spoiler", nameLocalizations: getAllLocalizations("image.flagNames.spoiler"), type: Constants.ApplicationCommandOptionTypes.BOOLEAN, description: "Attempt to send output as a spoiler", descriptionLocalizations: getAllLocalizations("image.flags.spoiler"), }, { name: "ephemeral", nameLocalizations: getAllLocalizations("image.flagNames.ephemeral"), type: Constants.ApplicationCommandOptionTypes.BOOLEAN, description: "Attempt to send output as an ephemeral/temporary response", descriptionLocalizations: getAllLocalizations("image.flags.ephemeral"), }, ); return this; }
static allowedFonts = [ "futura", "impact", "helvetica", "arial", "roboto", "noto", "times", "comic sans ms", "ubuntu", ];
static supportedTypes: MediaTypes[] = ["image"];
static requiresMedia = true; static requiresParam = false; static requiredParam = "text"; static requiredParamType: CommandFlag["type"] = "string"; static textOptional = false; static alwaysGIF = false; static noImage = "You need to provide an image/GIF!"; static noParam = "You need to provide some text!"; static empty = "The resulting output was empty!"; static command = "";}
export default MediaCommand;