mrmBot-Matrix/utils/misc.js

44 lines
1.5 KiB
JavaScript

import util from "util";
import fs from "fs";
import { config } from "dotenv";
// random(array) to select a random entry in array
export function random(array) {
if (!array || array.length < 1) return null;
return array[Math.floor(Math.random() * array.length)];
}
const optionalReplace = (token) => {
return token === undefined || token === "" ? "" : (token === "true" || token === "false" ? token : "<redacted>");
};
// clean(text) to clean message of any private info or mentions
export function clean(text) {
if (typeof text !== "string")
text = util.inspect(text, { depth: 1 });
text = text
.replaceAll("`", `\`${String.fromCharCode(8203)}`)
.replaceAll("@", `@${String.fromCharCode(8203)}`);
const { parsed } = config();
const imageServers = JSON.parse(fs.readFileSync(new URL("../config/servers.json", import.meta.url), { encoding: "utf8" })).image;
if (imageServers?.length !== 0) {
for (const { server, auth } of imageServers) {
text = text.replaceAll(server, optionalReplace(server));
text = text.replaceAll(auth, optionalReplace(auth));
}
}
for (const env of Object.keys(parsed)) {
text = text.replaceAll(parsed[env], optionalReplace(parsed[env]));
}
return text;
}
// textEncode(string) to encode characters for image processing
export function textEncode(string) {
return string.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;").replaceAll("\\n", "\n").replaceAll("\\:", ":");
}