Added support for custom aliases

This commit is contained in:
Histmy 2022-07-18 21:02:39 +02:00
parent f75c79f76a
commit f45a59ada7
4 changed files with 147 additions and 79 deletions

View File

@ -1,4 +1,4 @@
import { Client, Intents, MessageActionRow, MessageButton } from "discord.js";
import { Client, Intents, Message, MessageActionRow, MessageButton } from "discord.js";
import { readdirSync } from "fs";
import { CUser, EventSOn, KomandNaExport, Komand, ListenerFunkce, Modul, SRecord, SuperListenerFunkce, CustomKomandy } from "./utils/types";
import { adminLog, getFirstArg, formatCas, loadEnv, oddiakritikovat, sortArr } from "./utils/utils.js";
@ -24,12 +24,23 @@ const aliasy: SRecord<string> = {};
const kuldan_log: SRecord<SRecord<number>> = {};
const komandyNaPoslani: KomandNaExport[] = [];
let customKomandy: SRecord<Komand> = custom.cKomandy;
let customAliasy: SRecord<string> = custom.cAliasy;
custom.emitter.on("komandi", (komandi, naPoslani) => {
custom.emitter.on("komandi", (komandi, aliasi, naPoslani) => {
customKomandy = komandi;
helpServer.cmds = sortArr([...komandyNaPoslani, ...naPoslani]);
customAliasy = aliasi;
zpracovatAliasyAKomandy(aliasi, naPoslani);
});
function zpracovatAliasyAKomandy(aliasi: SRecord<string>, naPoslani: KomandNaExport[]) {
Object.keys(aliasi).forEach((a: string) => {
const i = komandyNaPoslani.findIndex(k => k.name == aliasi[a]);
if (!komandyNaPoslani[i]) return;
komandyNaPoslani[i].als ? komandyNaPoslani[i].als?.push(a) : komandyNaPoslani[i].als = [a];
});
helpServer.cmds = sortArr([...komandyNaPoslani, ...naPoslani]);
}
const runEvent = (name: string, args: unknown[]) => {
for (const listener of superEventy[name] || []) {
if (!listener) continue; // [after] pozice v superEventy arrayi se dají nastavovat a teoreticky může nastat mezera
@ -99,9 +110,13 @@ readdirSync(modulFolder).forEach(soubor => {
});
custom.realKomandy = komandy;
custom.realAliasy = aliasy;
komandy["naucse"] = { run: custom.naucse };
komandy["zapomen"] = { run: custom.zapomen };
helpServer.cmds = sortArr([...komandyNaPoslani, ...custom.naSend]);
komandy["kohoje"] = { run: custom.kohoje };
komandy["naucsealias"] = { run: custom.naucsealias };
komandy["zapomenalias"] = { run: custom.zapomenalias };
zpracovatAliasyAKomandy(custom.cAliasy, custom.naSend);
const maKuldan = (id: string, komand: string, kuldan_komandu: number) => {
if (!kuldan_log[komand]) kuldan_log[komand] = {};
@ -114,6 +129,25 @@ const maKuldan = (id: string, komand: string, kuldan_komandu: number) => {
return 0;
};
async function runKomand(mes: Message, cmd: Komand, cmdName: string, arg: string) {
if (cmd.cd) {
const zbyva = Math.round(maKuldan(mes.author.id, cmdName, cmd.cd));
if (zbyva) return void mes.channel.send(`si kkt vole maz kuldan jeste ${formatCas(zbyva)}`);
}
const akce = cmd.run;
if (typeof akce == "string") return void mes.channel.send(akce);
try {
const result = await akce(mes, arg);
if (result) mes.channel.send(result);
} catch (e) {
if (process.env.dieOnError) throw e;
console.log("error pri spousteni akce", e);
const admin = process.env.adminID;
mes.channel.send(`pri spousteni thohoto komandu nastala chyba ${admin ? `<@${admin}> uz?` : ""}`);
}
}
client.on("messageCreate", async mes => {
if (process.env.ignoreMess) return;
@ -125,44 +159,28 @@ client.on("messageCreate", async mes => {
}
const celArgs = args.join(" ");
const komandBez = oddiakritikovat(komandSDiakritikou).toLowerCase();
const cmdName = aliasy[komandBez] ?? customAliasy[komandBez] ?? komandBez;
async function runKomand(cmd: Komand, cmdName: string) {
if (cmd.cd) {
const zbyva = Math.round(maKuldan(mes.author.id, cmdName, cmd.cd));
if (zbyva) return void mes.channel.send(`si kkt vole maz kuldan jeste ${formatCas(zbyva)}`);
}
const akce = cmd.run;
if (typeof akce === "string") return void mes.channel.send(akce);
try {
const result = await akce(mes, celArgs);
if (result && !(result instanceof Promise)) mes.channel.send(result);
} catch (e) {
if (process.env.dieOnError) throw e;
console.log("error pri spousteni akce", e);
const admin = process.env.adminID;
mes.channel.send(`pri spousteni thohoto komandu nastala chyba ${admin ? `<@${admin}> uz?` : ""}`);
}
}
const komand = oddiakritikovat(komandSDiakritikou).toLowerCase();
const cmdName = aliasy[komand] ?? komand;
if (runEvent("message", [mes, cmdName])) return;
const cmd = komandy[cmdName] ?? customKomandy[cmdName];
if (cmd?.DMUnsafe && mes.channel.type == "DM") return void mes.channel.send("tuten komand bohuzel v sz nefunkuje");
if (!cmd) {
const komand = komandy[cmdName] ?? customKomandy[cmdName];
if (mes.channel.type == "DM" && komand?.DMUnsafe) return void mes.channel.send("tuten komand bohuzel v sz nefunkuje");
if (komand) return void runKomand(mes, komand, cmdName, celArgs);
// neměl jsi na mysli?
const slova: string[] = [];
[...Object.keys(komandy), ...Object.keys(customKomandy), ...Object.keys(aliasy)].forEach(cmnd => {
const distance = levenshtein(cmnd, cmdName);
if (distance <= Math.ceil(cmdName.length * 0.3)) slova.push(cmnd);
[...Object.keys(komandy), ...Object.keys(customKomandy), ...Object.keys(aliasy), ...Object.keys(customAliasy)].forEach(cmd => {
const distance = levenshtein(cmd, cmdName);
if (distance <= Math.ceil(cmdName.length * 0.3)) slova.push(cmd);
});
if (!slova.length) return void mes.channel.send("co to znamena ti gadzovko");
const nabidka = slova.sort().slice(0, 5);
const nabidka = slova.sort().slice(0, 5);
const radek = new MessageActionRow();
nabidka.forEach((cmnd, i) => {
const nazev = cmnd.length > 80 ? `${cmnd.slice(0, 77)}...` : cmnd;
nabidka.forEach((cmd, i) => {
const nazev = cmd.length > 80 ? `${cmd.slice(0, 77)}...` : cmd;
radek.addComponents(new MessageButton({ customId: `${i}`, label: nazev, style: "PRIMARY" }));
});
@ -172,21 +190,17 @@ client.on("messageCreate", async mes => {
const lookupId = Number(i.customId);
if (isNaN(lookupId)) return void mes.channel.send("neco nefunguje idk");
const komand = nabidka[lookupId];
const cmdName = aliasy[komand] ?? komand;
const cmdName = aliasy[komand] ?? customAliasy[komand] ?? komand;
const cmd = komandy[cmdName] ?? customKomandy[cmdName];
radek.components.forEach(btn => btn.setDisabled());
i.update({ content: `ok vole ${emouty.d3k}`, components: [radek] });
runKomand(cmd, cmdName);
runKomand(mes, cmd, cmdName, celArgs);
});
collector.on("end", c => {
if (c.size) return;
radek.components.forEach(btn => btn.setDisabled());
zprava.edit({ content: "pozde", components: [radek] });
});
return;
}
runKomand(cmd, cmdName);
});
// Simulation of userPresenceUpdate event

View File

@ -4,47 +4,96 @@ import { readFileSync, writeFileSync } from "fs";
import { join } from "path";
import { oddiakritikovat } from "./utils";
const cesta = join(__dirname, "../../res/komandi.json");
const komandi: SRecord<{ text: string; owner: string; }> = JSON.parse(readFileSync(cesta).toString());
const cesta = join(__dirname, "../../res/");
const customKomandi: SRecord<{ text: string; owner: string; }> = JSON.parse(readFileSync(`${cesta}komandi.json`).toString());
const customAliasy: SRecord<{ cmd: string; owner: string; }> = JSON.parse(readFileSync(`${cesta}aliasi.json`).toString());
const baseNaSend: KomandNaExport[] = [
{ name: "naucse", arg: "<jméno nového komandu> <obsah nového komandu>" },
{ name: "zapomen", arg: "název komandu" }
{ name: "zapomen", arg: "jméno komandu" },
{ name: "naucsealias", arg: "<jméno nového aliasu> <jméno existujícího komandu nebo aliasu>", als: ["nausea"] },
{ name: "naucsealias", arg: "jméno aliasu", als: ["zapomena"] }
];
export let [cKomandy, naSend] = save(true);
export let [cKomandy, cAliasy, naSend] = save(true);
export const emitter = new EventEmitter();
function save(): void;
function save(nesend: true): [SRecord<Komand>, KomandNaExport[]];
function save(nesend: true): [SRecord<Komand>, SRecord<string>, KomandNaExport[]];
function save(nesend?: true) {
const cKomandi: SRecord<Komand> = {};
const cAliasi: SRecord<string> = { naucsea: "naucsealias", zepomena: "zapomenalias" };
const naSend = baseNaSend;
Object.keys(komandi).forEach(c => {
cKomandi[c] = { run: komandi[c].text };
Object.keys(customKomandi).forEach(c => {
cKomandi[c] = { run: customKomandi[c].text };
naSend.push({ name: c });
});
if (nesend) return [cKomandi, naSend];
Object.keys(customAliasy).forEach(a => {
cAliasi[a] = customAliasy[a].cmd;
});
if (nesend) return [cKomandi, cAliasi, naSend];
cKomandy = cKomandi;
emitter.emit("komandi", cKomandy, naSend);
writeFileSync(cesta, JSON.stringify(komandi));
emitter.emit("komandi", cKomandy, cAliasi, naSend);
writeFileSync(`${cesta}komandi.json`, JSON.stringify(customKomandi));
writeFileSync(`${cesta}aliasi.json`, JSON.stringify(customAliasy));
}
export const naucse: RunFunkce = (mes, arg) => {
const args = arg.split(" ");
if (module.exports.realKomandy[args[0]] || komandi[args[0]]) return "tuten komand uz ale egzistuje";
if (!args.length) return "a co se mam jako naucit";
if (arg.length == 1) return "a co bich nato mnel rict????";
komandi[oddiakritikovat(args[0].toLowerCase())] = { text: args.splice(1).join(" "), owner: mes.author.id };
const args = arg.split(" ").filter(v => v != "");
args[0] = oddiakritikovat(args[0].toLowerCase());
if (args.length == 0) return "a co se mam jako naucit";
if (args.length == 1) return "a co bich nato mnel rict????";
if (module.exports.realKomandy[args[0]] || customKomandi[args[0]] || module.exports.realAliasy[args[0]] || customAliasy[args[0]]) return "tuten komand uz ale egzistuje";
customKomandi[args[0]] = { text: args.splice(1).join(" "), owner: mes.author.id };
save();
return "jo";
};
export const zapomen: RunFunkce = (mes, arg) => {
const com = arg.toLowerCase();
const com = oddiakritikovat(arg.toLowerCase());
if (module.exports.realKomandy[com]) return "tuten komand se neda smazat ti smazko";
const cmd = komandi[com];
const cmd = customKomandi[com];
if (!cmd) return `komand "${arg}" neznam`;
if (cmd.owner != mes.author.id) return "tuto ael neni tvuj komand toxikale zkurvenej";
delete komandi[com];
delete customKomandi[com];
save();
return "jo";
};
export const kohoje: RunFunkce = (_, arg) => {
const cmdName = oddiakritikovat(arg.toLowerCase());
const cmd = customKomandi[cmdName] ?? customAliasy[cmdName];
if (!cmd) return `"${cmdName}" nen ani komand an alijas`;
return `vlastnitel je <@${cmd.owner}>`;
};
export const naucsealias: RunFunkce = (mes, arg) => {
const args = arg.split(" ").filter(v => v != "").map(e => oddiakritikovat(e).toLowerCase());
if (args.length == 0) return "a co se mam jako naucit";
if (args.length == 1) return "a co to ma znamenat????";
if (module.exports.realKomandy[args[0]] || customKomandi[args[0]] || module.exports.realAliasy[args[0]] || customAliasy[args[0]]) return "tuto uz ale egzistuje";
if (!module.exports.realKomandy[args[1]] && !module.exports.realAliasy[args[1]]) return `nejze "${arg}" neni realnej komand ani alias`;
const jmeno = (module.exports.realKomandy[args[1]]) ? args[1] : module.exports.realAliasy[args[1]];
customAliasy[args[0]] = { cmd: jmeno, owner: mes.author.id };
save();
return "jo";
};
export const zapomenalias: RunFunkce = (mes, arg) => {
const al = oddiakritikovat(arg.toLowerCase());
if (module.exports.realAliasy[al]) return "tutn alijas se ale neda smazat ty smazenice";
const als = customAliasy[al];
if (!als) return `alijas "${al}" neznam`;
if (als.owner != mes.author.id) return "tuto ael neni tvuj alijas toxikale zkurvenej";
delete customAliasy[al];
save();
return "jo";
};

View File

@ -91,9 +91,14 @@ export interface CUser extends User {
export interface CustomKomandy {
cKomandy: SRecord<Komand>;
cAliasy: SRecord<string>;
emitter: EventEmitter;
naucse: RunFunkce;
zapomen: RunFunkce;
kohoje: RunFunkce;
naucsealias: RunFunkce;
zapomenalias: RunFunkce;
naSend: KomandNaExport[];
realKomandy: SRecord<Komand>;
realAliasy: SRecord<string>;
}

View File

@ -13,7 +13,7 @@ export const oddiakritikovat = (a: string) => {
.replace(/[çćĉċč]/g, "c")
.replace(/[ďđ]/g, "d")
.replace(/[èéêëðēĕėęě]/g, "e")
.replace(/[ĝğġģ]/g, "g")
.replace(/[ĝğġģǵ]/g, "g")
.replace(/[ĥħ]/g, "h")
.replace(/[ìíîïĩīĭįı]/g, "i")
.replace(/[ĵ]/g, "j")