finally made custom commands easier to maintain

This commit is contained in:
Histmy 2022-12-13 17:40:40 +01:00
parent d3d4df5bc8
commit 8b95db79cb
9 changed files with 193 additions and 159 deletions

6
.gitignore vendored
View File

@ -1,7 +1,5 @@
node_modules node_modules
config.json config.json
out out
res/ftipy.json res/customKomandy.json
res/komandi.json res/customAliasy.json
res/pomoc.json
res/aliasi.json

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "denim_3001", "name": "denim_3001",
"version": "3001.44.0", "version": "3001.44.1",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "denim_3001", "name": "denim_3001",
"version": "3001.44.0", "version": "3001.44.1",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@discordjs/voice": "^0.13.0", "@discordjs/voice": "^0.13.0",

View File

@ -1,6 +1,6 @@
{ {
"name": "denim_3001", "name": "denim_3001",
"version": "3001.44.0", "version": "3001.44.1",
"description": "Toto je velmi kvalitní bot.", "description": "Toto je velmi kvalitní bot.",
"repository": { "repository": {
"url": "https://github.com/Histmy/Denim-Bot/" "url": "https://github.com/Histmy/Denim-Bot/"

8
res/ftipy.json Normal file
View File

@ -0,0 +1,8 @@
[
"Tož šimša si všimnul jednoho velkeho staveniště, tak večer se tam vydal z atobatekou na boku a flefinou vruce uříznul tu největší traverzu a uříznul ji pak si ji dal na záda a šel dom ale když šel zpět tak se všimul pitbula který hlýdal staveniště a on byl na železnem řetězu tak ten řetěz popat ale nedomyslel to že ten pitbull poběží za ním a tak utíkal ale pitbull byl rychlejší a tak se mu zakousnul do prdele a tak utíkal před policií aj z pitbulem.",
"tož šimša si řekl že se pujde okoupat ale nedošlomu že na koupání potřebuje vodu a ne močůvku <:DENIM3K_weSmart:627809296624779274>",
"tož šimšu zaměstnaly na praxi do pneu servisu ale když tam došli do druhý den tak tam nic nebylo jelikož to vše vybrakoval přes noc a pak pan hlavní pneusevisák to nevydržel a exnul",
"tož šimša šel z vaku a vykopal mareše tak mocně a vykopal ho tak protože byl je závislí na cigáru a potřeboval svo mocně nemocno dáku tak vyvinul tam mocně silu aby o vykopnul",
"tož šimša jednou šel a tak moc šel do velkooooobjemního kontejnetu pro noví komponenti do jeho mašiny a podkal tam cygani a ty to tam brali a von je podkal a šel jim rozbít drčku haby se už a řek jim haby se už nevokázali u jeho kontejmetu a kdyš čel cezto dom tak mu ti kombonendi zpadli do bláda a tak mu zpadli mo ze šel sy dát zlatou dávkou",
"tož šimša seděl ve 3kole a tadytámlecti haranti mu šimšakanovali a povidaly mu 6e je římšák a šiška a šimšalátor a on povidal aby to nepovidali ale oni to povidali a pověděli mu žeto nep5estanou povidat a on ze sač4al čerchmantit a tak zasedl do traktotu a jel vo ulycy a jak jel tak jel a jel a přeji6děl kraliki a kočki a koně a jin9 zvěrstva a tak mu cajti pošeli flastr a von platil velk9 prachy, protože m2l flastra, no nem2l tag moc chlastat"
]

View File

@ -1,14 +1,11 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, ComponentType, GatewayIntentBits, Message, Partials } from "discord.js"; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, ComponentType, GatewayIntentBits, Message, Partials } from "discord.js";
import { readdirSync } from "fs"; import { readdirSync } from "fs";
import { CUser, EventSOn, KomandNaExport, Komand, ListenerFunkce, Modul, SRecord, SuperListenerFunkce, CustomKomandy, RunFunkce } from "./utils/types"; import { CUser, EventSOn, KomandNaExport, Komand, ListenerFunkce, Modul, SRecord, SuperListenerFunkce, RunFunkce, CClient, HelpServer } from "./utils/types";
import { adminLog, formatCas, oddiakritikovat, log } from "./utils/utils.js"; import { adminLog, formatCas, oddiakritikovat, log } from "./utils/utils.js";
import levenshtein from "js-levenshtein"; import levenshtein from "js-levenshtein";
import { emouty } from "./utils/emotes"; import { emouty } from "./utils/emotes";
import { existsSync } from "fs"; import { existsSync } from "fs";
const helpServer = require("./utils/helpServer");
const custom: CustomKomandy = require("./utils/customCommands");
if (!existsSync("config.json")) throw new Error("config.json neexistuje"); if (!existsSync("config.json")) throw new Error("config.json neexistuje");
process.env = { ...process.env, ...require("../config.json") }; process.env = { ...process.env, ...require("../config.json") };
@ -16,34 +13,17 @@ const ints = GatewayIntentBits;
const client = new Client({ const client = new Client({
partials: [Partials.Channel], partials: [Partials.Channel],
intents: [ints.Guilds, ints.GuildVoiceStates, ints.GuildPresences, ints.GuildMessages, ints.DirectMessages, ints.MessageContent] intents: [ints.Guilds, ints.GuildVoiceStates, ints.GuildPresences, ints.GuildMessages, ints.DirectMessages, ints.MessageContent]
}); }) as CClient;
const prefix = process.env.prefix || "more"; const prefix = process.env.prefix || "more";
const modulFolder = `${__dirname}/modules/`; const modulFolder = `${__dirname}/modules/`;
const eventy: SRecord<ListenerFunkce[]> = {}; const eventy: SRecord<ListenerFunkce[]> = {};
const superEventy: SRecord<SuperListenerFunkce[]> = {}; const superEventy: SRecord<SuperListenerFunkce[]> = {};
const komandy: SRecord<Komand> = {};
const aliasy: SRecord<string> = {};
const kuldan_log: SRecord<SRecord<number>> = {}; const kuldan_log: SRecord<SRecord<number>> = {};
const komandyNaPoslani: KomandNaExport[] = []; const komandyNaPoslani: KomandNaExport[] = [];
let customKomandy: SRecord<Komand> = custom.cKomandy; const helpServer: HelpServer = require("./utils/helpServer");
let customAliasy: SRecord<string> = custom.cAliasy;
custom.emitter.on("komandi", (komandi, aliasi, naPoslani) => { client.komandy = {};
customKomandy = komandi; client.aliasy = {};
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;
const arr = komandyNaPoslani[i].als;
if (arr && !arr.includes(a)) arr.push(a);
if (!arr) komandyNaPoslani[i].als = [a];
});
helpServer.cmds = [...komandyNaPoslani, ...naPoslani].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
}
function getFirstArg(fn: RunFunkce | string) { function getFirstArg(fn: RunFunkce | string) {
if (typeof fn != "function") return; if (typeof fn != "function") return;
@ -107,13 +87,13 @@ readdirSync(modulFolder).forEach(soubor => {
const toCoExportuju: KomandNaExport = { name: cmdName }; const toCoExportuju: KomandNaExport = { name: cmdName };
let hide = false; let hide = false;
if (typeof value !== "object") { if (typeof value !== "object") {
komandy[cmdName] = { run: value }; client.komandy[cmdName] = { run: value };
toCoExportuju.arg = getFirstArg(value); toCoExportuju.arg = getFirstArg(value);
} else { } else {
komandy[cmdName] = { run: value.run, cd: value.cd, DMUnsafe: value.DMUnsafe }; client.komandy[cmdName] = { run: value.run, cd: value.cd, DMUnsafe: value.DMUnsafe };
Object.assign(toCoExportuju, { als: value.als, arg: value.arg ?? getFirstArg(value.run) }); Object.assign(toCoExportuju, { als: value.als, arg: value.arg ?? getFirstArg(value.run) });
hide = !!value.hidden; hide = !!value.hidden;
value.als?.forEach(al => aliasy[al] = cmdName); value.als?.forEach(al => client.aliasy[al] = cmdName);
} }
if (!hide) komandyNaPoslani.push(toCoExportuju); if (!hide) komandyNaPoslani.push(toCoExportuju);
}); });
@ -121,14 +101,7 @@ readdirSync(modulFolder).forEach(soubor => {
}); });
}); });
custom.realKomandy = komandy; helpServer.komandy = komandyNaPoslani;
custom.realAliasy = aliasy;
komandy["naucse"] = { run: custom.naucse };
komandy["zapomen"] = { run: custom.zapomen };
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) => { const maKuldan = (id: string, komand: string, kuldan_komandu: number) => {
if (!kuldan_log[komand]) kuldan_log[komand] = {}; if (!kuldan_log[komand]) kuldan_log[komand] = {};
@ -172,18 +145,18 @@ client.on("messageCreate", async mes => {
const celArgs = args.join(" "); const celArgs = args.join(" ");
const komandBez = oddiakritikovat(komandSDiakritikou).toLowerCase(); const komandBez = oddiakritikovat(komandSDiakritikou).toLowerCase();
const cmdName = aliasy[komandBez] ?? customAliasy[komandBez] ?? komandBez; const cmdName = client.aliasy[komandBez] ?? komandBez;
if (runEvent("messageCreate", [mes, cmdName])) return; if (runEvent("messageCreate", [mes, cmdName])) return;
const komand = komandy[cmdName] ?? customKomandy[cmdName]; const komand = client.komandy[cmdName];
if (mes.channel.type == ChannelType.DM && komand?.DMUnsafe) return void mes.channel.send("tuten komand bohuzel v sz nefunkuje"); if (mes.channel.type == ChannelType.DM && komand?.DMUnsafe) return void mes.channel.send("tuten komand bohuzel v sz nefunkuje");
if (komand) return void runKomand(mes, komand, cmdName, celArgs); if (komand) return void runKomand(mes, komand, cmdName, celArgs);
// neměl jsi na mysli? // neměl jsi na mysli?
const slova: string[] = []; const slova: string[] = [];
[...Object.keys(komandy), ...Object.keys(customKomandy), ...Object.keys(aliasy), ...Object.keys(customAliasy)].forEach(cmd => { [...Object.keys(client.komandy), ...Object.keys(client.aliasy)].forEach(cmd => {
const distance = levenshtein(cmd, cmdName); const distance = levenshtein(cmd, cmdName);
if (distance <= Math.ceil(cmdName.length * 0.3)) slova.push(cmd); if (distance <= Math.ceil(cmdName.length * 0.3)) slova.push(cmd);
}); });
@ -202,8 +175,8 @@ client.on("messageCreate", async mes => {
const lookupId = Number(i.customId); const lookupId = Number(i.customId);
if (isNaN(lookupId)) return void mes.channel.send("neco nefunguje idk"); if (isNaN(lookupId)) return void mes.channel.send("neco nefunguje idk");
const komand = nabidka[lookupId]; const komand = nabidka[lookupId];
const cmdName = aliasy[komand] ?? customAliasy[komand] ?? komand; const cmdName = client.aliasy[komand] ?? komand;
const cmd = komandy[cmdName] ?? customKomandy[cmdName]; const cmd = client.komandy[cmdName];
radek.components.forEach(btn => btn.setDisabled()); radek.components.forEach(btn => btn.setDisabled());
i.update({ content: `ok vole ${emouty.d3k}`, components: [radek] }); i.update({ content: `ok vole ${emouty.d3k}`, components: [radek] });
runKomand(mes, cmd, cmdName, celArgs); runKomand(mes, cmd, cmdName, celArgs);

135
src/modules/custom.ts Normal file
View File

@ -0,0 +1,135 @@
import { CClient, HelpServer, Komand, KomandNaExport, Modul, SRecord } from "../utils/types";
import { join } from "path";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { oddiakritikovat } from "../utils/utils";
let client: CClient;
const cesta = `${join(__dirname, "../../res/")}custom`;
const helpServer: HelpServer = require("../utils/helpServer");
let zakladniKomandy: SRecord<Komand>;
let zakladniAliasy: SRecord<string>;
let customKomandy: SRecord<{ text: string; owner: string; }>;
let customAliasy: SRecord<{ cmd: string; owner: string; }>;
function spojit() {
const cKomandyAsKomand: SRecord<Komand> = {};
const cKomandyForExport: KomandNaExport[] = [];
for (const komand in customKomandy) {
cKomandyAsKomand[komand] = { run: customKomandy[komand].text };
cKomandyForExport.push({ name: komand });
}
client.komandy = { ...zakladniKomandy, ...cKomandyAsKomand };
helpServer.customKomandy = cKomandyForExport;
const cAliasyForExport: SRecord<string> = {};
for (const alias in customAliasy) {
cAliasyForExport[alias] = customAliasy[alias].cmd;
}
client.aliasy = { ...zakladniAliasy, ...cAliasyForExport };
helpServer.customAliasy = cAliasyForExport;
}
function save() {
writeFileSync(`${cesta}Komandy.json`, JSON.stringify(customKomandy));
writeFileSync(`${cesta}Aliasy.json`, JSON.stringify(customAliasy));
spojit();
}
const exp: Modul = {
more_komandy: {
naucse: {
arg: "<název nového komandu> <text nového komandu>",
run: (mes, arg) => {
const args = arg.split(" ").filter(v => v != "");
if (args.length == 0) return "a co se mam jako naucit";
if (args.length == 1) return "a co bich nato mnel rict????";
const name = oddiakritikovat(args[0].toLowerCase());
if (zakladniKomandy[name] || customKomandy[name]) return "tuten komand uz ale egzistuje";
if (zakladniAliasy[name] || customAliasy[name]) return "tuto uz je ale alijas";
customKomandy[name] = { text: args.splice(1).join(" "), owner: mes.author.id };
save();
return "jo";
}
},
naucsealias: {
arg: "<název nového aliasu> <název existujícího komandu nebo aliasu>",
als: ["naucsea"],
run: (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 (zakladniKomandy[args[0]] || customKomandy[args[0]]) return "tuto uz je ale komand";
if (zakladniAliasy[args[0]] || customAliasy[args[0]]) return "tuto uz ale egzistuje";
let jmeno: string;
if (!zakladniKomandy[args[1]] && !zakladniAliasy[args[1]]) {
if (!customKomandy[args[1]] && !customAliasy[args[1]]) return `nejze "${args[1]}" neni realnej ani vlastni komand ani alias`;
jmeno = customKomandy[args[1]] ? args[1] : customAliasy[args[1]].cmd;
} else jmeno = zakladniKomandy[args[1]] ? args[1] : zakladniAliasy[args[1]];
customAliasy[args[0]] = { cmd: jmeno, owner: mes.author.id };
save();
return "jo";
}
},
zapomen: {
arg: "název komandu nebo aliasu",
run: (mes, arg) => {
const name = oddiakritikovat(arg.toLowerCase());
if (zakladniKomandy[name]) return "tuten komand se neda smazat ti smazko";
if (zakladniAliasy[name]) return "tuten alijaas se neda smazat ti smazko";
let jeKomand: boolean;
let cmd;
if (cmd = customKomandy[name]) jeKomand = true;
else if (cmd = customAliasy[name]) jeKomand = false;
else return `"${name}" nen komnad an alias`;
if (cmd.owner != mes.author.id) return "tuto ael neni tvuj komand toxikale zkurvenej";
jeKomand ? delete customKomandy[name] : delete customAliasy[name];
save();
return "jo";
}
},
kohoje: {
arg: "název komandu nebo aliasu",
run: (_, arg) => {
const cmdName = oddiakritikovat(arg.toLowerCase());
const cmd = customKomandy[cmdName] ?? customAliasy[cmdName];
if (!cmd) return `"${cmdName}" nen vlastny komand an alijas`;
return `vlastnitel je <@${cmd.owner}>`;
}
}
},
on_ready: () => {
client = module.exports.client;
zakladniKomandy = client.komandy;
zakladniAliasy = client.aliasy;
if (!existsSync(`${cesta}Komandy.json`)) customKomandy = {};
else customKomandy = JSON.parse(readFileSync(`${cesta}Komandy.json`).toString());
if (!existsSync(`${cesta}Aliasy.json`)) customAliasy = {};
else customAliasy = JSON.parse(readFileSync(`${cesta}Aliasy.json`).toString());
spojit();
}
};
module.exports = exp;

View File

@ -1,105 +0,0 @@
import { EventEmitter } from "events";
import { KomandNaExport, Komand, RunFunkce, SRecord } from "./types";
import { readFileSync, writeFileSync } from "fs";
import { join } from "path";
import { oddiakritikovat } from "./utils";
const ex = module.exports;
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: "jméno komandu" },
{ name: "naucsealias", arg: "<jméno nového aliasu> <jméno existujícího komandu nebo aliasu>", als: ["nausea"] },
{ name: "zapomenalias", arg: "jméno aliasu", als: ["zapomena"] }
];
export let [cKomandy, cAliasy, naSend] = save(true);
export const emitter = new EventEmitter();
function save(): void;
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(customKomandi).forEach(c => {
cKomandi[c] = { run: customKomandi[c].text };
naSend.push({ name: c });
});
Object.keys(customAliasy).forEach(a => {
cAliasi[a] = customAliasy[a].cmd;
});
if (nesend) return [cKomandi, cAliasi, naSend];
cKomandy = cKomandi;
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(" ").filter(v => v != "");
if (args.length == 0) return "a co se mam jako naucit";
if (args.length == 1) return "a co bich nato mnel rict????";
args[0] = oddiakritikovat(args[0].toLowerCase());
if (ex.realKomandy[args[0]] || customKomandi[args[0]] || ex.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 = oddiakritikovat(arg.toLowerCase());
if (ex.realKomandy[com]) return "tuten komand se neda smazat ti smazko";
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 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 (ex.realKomandy[args[0]] || customKomandi[args[0]] || ex.realAliasy[args[0]] || customAliasy[args[0]]) return "tuto uz ale egzistuje";
let jmeno: string;
if (!ex.realKomandy[args[1]] && !ex.realAliasy[args[1]]) {
if (!customKomandi[args[1]] && !customAliasy[args[1]]) return `nejze "${args[1]}" neni realnej ani vlastni komand ani alias`;
jmeno = customKomandi[args[1]] ? args[1] : customAliasy[args[1]].cmd;
}
else jmeno = (ex.realKomandy[args[1]]) ? args[1] : ex.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 (ex.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

@ -1,9 +1,23 @@
import { createServer } from "http"; import { createServer } from "http";
import { KomandNaExport } from "./types"; import { KomandNaExport, SRecord } from "./types";
import { log } from "./utils";
createServer((_, res) => { createServer((_, res) => {
const komandi: KomandNaExport[] = module.exports.cmds; const komandy: KomandNaExport[] = module.exports.komandy;
const odpoved = JSON.stringify({ komandy: komandi }); const customKomandy: KomandNaExport[] = module.exports.customKomandy;
res.setHeader("Content-Type", "application/json"); const customAliasy: SRecord<string> = module.exports.customAliasy;
res.end(odpoved);
const vsechnyKomandy: KomandNaExport[] = [...komandy, ...customKomandy];
for (const key in customAliasy) {
const i = vsechnyKomandy.findIndex(komand => komand.name == customAliasy[key]);
if (i == -1) { log(new Error(`ičko neexistuje. hledal sem "${key}"`)); continue; }
(vsechnyKomandy[i].als ??= []).push(key);
}
vsechnyKomandy.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
const odpoved = JSON.stringify({ komandy: vsechnyKomandy });
res.setHeader("Content-Type", "application/json");
res.end(odpoved);
}).listen(5712); }).listen(5712);

View File

@ -7,7 +7,7 @@ type OutputRunFunkce = string | MessagePayload | MessageCreateOptions | void;
export type RunFunkce = (message: Message, argumenty: string) => OutputRunFunkce | Promise<OutputRunFunkce>; export type RunFunkce = (message: Message, argumenty: string) => OutputRunFunkce | Promise<OutputRunFunkce>;
interface BaseKomandProps { export interface BaseKomandProps {
als?: string[]; als?: string[];
arg?: string; arg?: string;
} }
@ -102,3 +102,14 @@ export interface CustomKomandy {
realKomandy: SRecord<Komand>; realKomandy: SRecord<Komand>;
realAliasy: SRecord<string>; realAliasy: SRecord<string>;
} }
export interface HelpServer {
komandy: KomandNaExport[];
customKomandy: KomandNaExport[];
customAliasy: SRecord<string>;
}
export class CClient extends Client {
komandy!: SRecord<Komand>;
aliasy!: SRecord<string>;
}