From 9539ea32cdbbe6377508959eea746810af50e109 Mon Sep 17 00:00:00 2001 From: murm Date: Sun, 19 Mar 2023 06:42:07 -0400 Subject: [PATCH] remove paginator, it is extremely discord-specific --- app.js | 5 - commands/general/base64.js | 4 +- commands/general/count.js | 59 ++++------- commands/general/help.js | 2 - commands/general/image.js | 2 - commands/tags/tags.js | 2 - events/roommessage.js | 43 +------- utils/pagination/pagination.js | 187 --------------------------------- 8 files changed, 27 insertions(+), 277 deletions(-) delete mode 100644 utils/pagination/pagination.js diff --git a/app.js b/app.js index e5e4fc7..567ffde 100644 --- a/app.js +++ b/app.js @@ -20,12 +20,7 @@ config({ path: resolve(dirname(fileURLToPath(import.meta.url)), ".env") }); import { reloadImageConnections } from "./utils/image.js"; // main services -// import { Client } from "oceanic.js"; import * as sdk from "matrix-js-sdk"; -// const AutojoinRoomsMixin = sdk.AutojoinRoomsMixin; - - - import pm2 from "pm2"; // some utils diff --git a/commands/general/base64.js b/commands/general/base64.js index 9a4a9b7..46f3081 100644 --- a/commands/general/base64.js +++ b/commands/general/base64.js @@ -1,5 +1,5 @@ import Command from "../../classes/command.js"; -import { clean } from "../../utils/misc.js"; +import { clean, htmlescape } from "../../utils/misc.js"; class Base64Command extends Command { static category = "general" @@ -13,7 +13,7 @@ class Base64Command extends Command { this.success = true; if (command === "decode") { const b64Decoded = Buffer.from(string, "base64").toString("utf8"); - return { html: `
${await clean(b64Decoded)}
` }; + return { html: `
${htmlescape(await clean(b64Decoded))}
` }; } else if (command === "encode") { const b64Encoded = Buffer.from(string, "utf8").toString("base64"); return { html: `
${b64Encoded}
` }; diff --git a/commands/general/count.js b/commands/general/count.js index e4dbf54..d95ec13 100644 --- a/commands/general/count.js +++ b/commands/general/count.js @@ -1,52 +1,33 @@ -import paginator from "../../utils/pagination/pagination.js"; import database from "../../utils/database.js"; import Command from "../../classes/command.js"; +import * as collections from "../../utils/collections.js"; +import { htmlescape } from "../../utils/misc.js"; class CountCommand extends Command { static category = "general" async run() { - if (this.guild && !this.channel.permissionsOf(this.client.user.id.toString()).has("EMBED_LINKS")) { - this.success = false; - return "I don't have the `Embed Links` permission!"; - } const counts = await database.getCounts(); - const countArray = []; - for (const entry of Object.entries(counts)) { - countArray.push(entry); + if (this.args.length !== 0) { + if (collections.commands.has(this.args[0].toLowerCase())) { + let html; + const command = collections.aliases.get(this.args[0].toLowerCase()) ?? this.args[0].toLowerCase(); + // TODO: room-specific prefix + const prefix = htmlescape(process.env.PREFIX); + let amount = counts[command] + if (amount == 1) { + amount = `${amount} time!` + } else { + amount = `${amount} times!` + } + html = `The command ${prefix}${command} has been used ${amount}` + return { html: html } + } + return "You need to specify a valid command to see its usage amount!" } - const sortedValues = countArray.sort((a, b) => { - return b[1] - a[1]; - }); - const countArray2 = []; - for (const [key, value] of sortedValues) { - countArray2.push(`**${key}**: ${value}`); - } - const embeds = []; - const groups = countArray2.map((item, index) => { - return index % 15 === 0 ? countArray2.slice(index, index + 15) : null; - }).filter((item) => { - return item; - }); - for (const [i, value] of groups.entries()) { - embeds.push({ - embeds: [{ - title: "Command Usage Counts", - color: 16711680, - footer: { - text: `Page ${i + 1} of ${groups.length}` - }, - description: value.join("\n"), - author: { - name: this.author.username, - iconURL: this.author.avatarURL() - } - }] - }); - } - return paginator(this.client, { type: this.type, message: this.message, interaction: this.interaction, channel: this.channel, author: this.author }, embeds); + return "You need to specify a command to see its usage amount!" } - static description = "Gets how many times every command was used"; + static description = "Gets how many times a command was used"; static arguments = ["{mention/id}"]; static aliases = ["counts"]; static dbRequired = true; diff --git a/commands/general/help.js b/commands/general/help.js index f985a6b..9befa6c 100644 --- a/commands/general/help.js +++ b/commands/general/help.js @@ -1,8 +1,6 @@ -// import { Constants } from "oceanic.js"; // import database from "../../utils/database.js"; import * as collections from "../../utils/collections.js"; import { htmlescape } from "../../utils/misc.js"; -// import paginator from "../../utils/pagination/pagination.js"; import * as help from "../../utils/help.js"; import Command from "../../classes/command.js"; // const tips = ["You can change the bot's prefix using the prefix command.", "Image commands also work with images previously posted in that channel.", "You can use the tags commands to save things for later use.", "You can visit https://esmbot.net/help.html for a web version of this command list.", "You can view a command's aliases by putting the command name after the help command (e.g. help image).", "Parameters wrapped in [] are required, while parameters wrapped in {} are optional.", "esmBot is hosted and paid for completely out-of-pocket by the main developer. If you want to support development, please consider donating! https://patreon.com/TheEssem"]; diff --git a/commands/general/image.js b/commands/general/image.js index 32871f1..f891618 100644 --- a/commands/general/image.js +++ b/commands/general/image.js @@ -1,4 +1,3 @@ -import paginator from "../../utils/pagination/pagination.js"; import { readFileSync } from "fs"; const { searx } = JSON.parse(readFileSync(new URL("../../config/servers.json", import.meta.url))); import { random } from "../../utils/misc.js"; @@ -9,7 +8,6 @@ class ImageSearchCommand extends Command { static category = "general" async run() { this.success = false; - // if (this.channel && !this.channel.permissionsOf(this.client.user.id.toString()).has("EMBED_LINKS")) return "I don't have the `Embed Links` permission!"; const query = this.options.query ?? this.args.join(" "); if (!query || !query.trim()) return "You need to provide something to search for!"; // await this.acknowledge(); diff --git a/commands/tags/tags.js b/commands/tags/tags.js index 9030258..1748ec7 100644 --- a/commands/tags/tags.js +++ b/commands/tags/tags.js @@ -1,5 +1,4 @@ import database from "../../utils/database.js"; -import paginator from "../../utils/pagination/pagination.js"; import { random } from "../../utils/misc.js"; import Command from "../../classes/command.js"; const blacklist = ["create", "add", "edit", "remove", "delete", "list", "random", "own", "owner"]; @@ -84,7 +83,6 @@ class TagsCommand extends Command { if (embeds.length === 0) return "I couldn't find any tags!"; this.success = true; return output; - // return paginator(this.client, { type: this.type, message: this.message, interaction: this.interaction, channel: this.channel, author: this.author }, embeds); } else { let getResult; if (cmd === "random") { diff --git a/events/roommessage.js b/events/roommessage.js index 9bf40d1..76b1387 100644 --- a/events/roommessage.js +++ b/events/roommessage.js @@ -5,7 +5,6 @@ import parseCommand from "../utils/parseCommand.js"; import { clean } from "../utils/misc.js"; import sizeOf from "image-size"; // import { upload } from "../utils/tempimages.js"; -// import { ThreadChannel } from "oceanic.js"; let mentionRegex; @@ -52,9 +51,9 @@ export default async function (matrixClient, event, room, toStartOfTimeline) { try { // parse args const parsed = parseCommand(preArgs); - // if (database) { - // await database.addCount(aliases.get(command) ?? command); - // } + if (database) { + await database.addCount(aliases.get(command) ?? command); + } const startTime = new Date(); // eslint-disable-next-line no-unused-vars const commandClass = new cmd(matrixClient, { type: "classic", message: event.event, args: parsed._, content: text.replace(command, "").trim(), specialArgs: (({ _, ...o }) => o)(parsed) }); // we also provide the message content as a parameter for cases where we need more accuracy @@ -70,7 +69,6 @@ export default async function (matrixClient, event, room, toStartOfTimeline) { console.log(err); }); } else if (typeof result === "object") { - // console.log(result) if (result.html) { const content = { format: "org.matrix.custom.html", @@ -105,16 +103,13 @@ export default async function (matrixClient, event, room, toStartOfTimeline) { width: result.width, height: result.height } - // if (mime === "jpg") { - // mime = "jpeg"; - // } await matrixClient.sendImageMessage(event.event.room_id, mxcUri.content_uri, {h: imgsize.height, w: imgsize.width, mimetype: `image/${mime}`, size: result.contents.length, thumbnail_info: {h: imgsize.height, w: imgsize.width, mimetype: `image/${mime}`, size: result.contents.length}}, result.name) } } else { - // await client.rest.channels.createMessage(message.channelID, Object.assign(result, reference)); + // no-op } } else { - // console.log(typeof result) + // no-op } } catch (error) { logger.log("error", error.stack) @@ -129,34 +124,6 @@ export default async function (matrixClient, event, room, toStartOfTimeline) { } catch (e) { _error(`While attempting to send the previous error message, another error occurred: ${e.stack || e}`); } - // if (error.toString().includes("Request entity too large")) { - // await client.rest.channels.createMessage(event.event.room_id, Object.assign({ - // content: "The resulting file was too large to upload. Try again with a smaller image if possible." - // }, reference)); - // } else if (error.toString().includes("Job ended prematurely")) { - // await client.rest.channels.createMessage(event.event.room_id, Object.assign({ - // content: "Something happened to the image servers before I could receive the image. Try running your command again." - // }, reference)); - // } else if (error.toString().includes("Timed out")) { - // await client.rest.channels.createMessage(event.event.room_id, Object.assign({ - // content: "The request timed out before I could download that image. Try uploading your image somewhere else or reducing its size." - // }, reference)); - // } else { - // _error(`Error occurred with command message ${event.event.content.body}: ${error.stack || error}`); - // try { - // let err = error; - // if (error?.constructor?.name == "Promise") err = await error; - // await client.rest.channels.createMessage(event.event.room_id, Object.assign({ - // content: "Uh oh! I ran into an error while running this command. Please report the content of the attached file at the following link or on the esmBot Support server: ", - // files: [{ - // contents: `Message: ${clean(err)}\n\nStack Trace: ${clean(err.stack)}`, - // name: "error.txt" - // }] - // }, reference)); - // } catch (e) { - // _error(`While attempting to send the previous error message, another error occurred: ${e.stack || e}`); - // } - // } } return; } diff --git a/utils/pagination/pagination.js b/utils/pagination/pagination.js deleted file mode 100644 index 774ae2c..0000000 --- a/utils/pagination/pagination.js +++ /dev/null @@ -1,187 +0,0 @@ -import InteractionCollector from "./awaitinteractions.js"; -import { ComponentInteraction } from "oceanic.js"; - -export default async (client, info, pages, timeout = 120000) => { - const options = info.type === "classic" ? { - messageReference: { - channelID: info.message.channelID, - messageID: info.message.id, - guildID: info.message.guildID, - failIfNotExists: false - }, - allowedMentions: { - repliedUser: false - } - } : {}; - let page = 0; - const components = { - components: [{ - type: 1, - components: [ - { - type: 2, - label: "Back", - emoji: { - id: null, - name: "◀" - }, - style: 1, - customID: "back" - }, - { - type: 2, - label: "Forward", - emoji: { - id: null, - name: "▶" - }, - style: 1, - customID: "forward" - }, - { - type: 2, - label: "Jump", - emoji: { - id: null, - name: "🔢" - }, - style: 1, - customID: "jump" - }, - { - type: 2, - label: "Delete", - emoji: { - id: null, - name: "🗑" - }, - style: 4, - customID: "delete" - } - ] - }] - }; - let currentPage; - if (info.type === "classic") { - currentPage = await client.rest.channels.createMessage(info.message.channelID, Object.assign(pages[page], options, pages.length > 1 ? components : {})); - } else { - currentPage = await info.interaction[info.interaction.acknowledged ? "editOriginal" : "createMessage"](Object.assign(pages[page], pages.length > 1 ? components : {})); - if (!currentPage) currentPage = await info.interaction.getOriginal(); - } - - if (pages.length > 1) { - const interactionCollector = new InteractionCollector(client, currentPage, ComponentInteraction, timeout); - interactionCollector.on("interaction", async (interaction) => { - if ((interaction.member ?? interaction.user).id === info.author.id) { - switch (interaction.data.customID) { - case "back": - await interaction.deferUpdate(); - page = page > 0 ? --page : pages.length - 1; - currentPage = await currentPage.edit(Object.assign(pages[page], options)); - interactionCollector.extend(); - break; - case "forward": - await interaction.deferUpdate(); - page = page + 1 < pages.length ? ++page : 0; - currentPage = await currentPage.edit(Object.assign(pages[page], options)); - interactionCollector.extend(); - break; - case "jump": - await interaction.deferUpdate(); - var newComponents = JSON.parse(JSON.stringify(components)); - for (const index of newComponents.components[0].components.keys()) { - newComponents.components[0].components[index].disabled = true; - } - currentPage = await currentPage.edit(newComponents); - interactionCollector.extend(); - var jumpComponents = { - components: [{ - type: 1, - components: [{ - type: 3, - customID: "seekDropdown", - placeholder: "Page Number", - options: [] - }] - }] - }; - for (let i = 0; i < pages.length && i < 25; i++) { - const payload = { - label: i + 1, - value: i - }; - jumpComponents.components[0].components[0].options[i] = payload; - } - var promise; - if (info.type === "classic") { - promise = client.rest.channels.createMessage(info.message.channelID, Object.assign({ content: "What page do you want to jump to?" }, { - messageReference: { - channelID: currentPage.channelID, - messageID: currentPage.id, - guildID: currentPage.guildID, - failIfNotExists: false - }, - allowedMentions: { - repliedUser: false - } - }, jumpComponents)); - } else { - promise = info.interaction.createFollowup(Object.assign({ content: "What page do you want to jump to?" }, jumpComponents)); - } - promise.then(askMessage => { - const dropdownCollector = new InteractionCollector(client, askMessage, ComponentInteraction, timeout); - let ended = false; - dropdownCollector.on("interaction", async (response) => { - if (response.data.customID !== "seekDropdown") return; - try { - await askMessage.delete(); - } catch { - // no-op - } - page = Number(response.data.values.raw[0]); - currentPage = await currentPage.edit(Object.assign(pages[page], options, components)); - ended = true; - dropdownCollector.stop(); - }); - dropdownCollector.once("end", async () => { - if (ended) return; - try { - await askMessage.delete(); - } catch { - // no-op - } - currentPage = await currentPage.edit(Object.assign(pages[page], options, components)); - }); - }).catch(error => { - throw error; - }); - break; - case "delete": - await interaction.deferUpdate(); - interactionCollector.emit("end", true); - try { - await currentPage.delete(); - } catch { - // no-op - } - return; - default: - break; - } - } - }); - interactionCollector.once("end", async (deleted = false) => { - interactionCollector.removeAllListeners("interaction"); - if (!deleted) { - for (const index of components.components[0].components.keys()) { - components.components[0].components[index].disabled = true; - } - try { - await currentPage.edit(components); - } catch { - // no-op - } - } - }); - } -};