přihlásit se

DENIM 3001DENIM 3001 návrhy

Implementováno[IMPLEMENTOVÁNO] source kód (DN0268)

:lajk:2:lajk:0:alert:Upozornění vypnuto

kiwaki
2023-11-19 13:18:29
Vážený/á [Jméno příjemce],

obracím se na Vás s žádostí o poskytnutí source kódu pro projekt Denim3001. Jsem přesvědčen/á, že získání přístupu k tomuto kódu bude prospěšné nejen pro mou práci, ale také pro další rozvoj a vylepšení tohoto projektu.

Mým cílem je lépe porozumět implementaci a architektuře Denim3001 a přispět k jeho dalšímu rozvoji. Jsem si vědom/á, že každý projekt může mít svá specifika ohledně poskytování kódu a jsem připraven/á dodržovat všechny podmínky, které s tím souvisejí.

Zároveň jsem ochoten/á podepsat jakékoliv dohody o zachování důvěrnosti nebo jiné právní dokumenty, které jsou pro poskytnutí source kódu nezbytné.

Pokud máte jakékoli otázky nebo pokyny ohledně tohoto požadavku, rád/á se jimi řídím. Těším se na Vaši odpověď a děkuji za čas, který věnujete této žádosti.

S pozdravem,

[Vaše jméno]
[Váš kontakt na e-mail nebo telefon]


Petr Hybeš
tvojemam@preceroliky.cz
zbyvaj
2023-11-19 13:21:02
ok



import { ChannelType, Client, CommandInteraction, GatewayIntentBits, InteractionReplyOptions, Message, Partials } from "discord.js";
import { readdirSync } from "fs";
import { CUser, KomandNaExport, Komand, ListenerFunkce, Modul, SRecord, SuperListenerFunkce, CClient, HelpServer, KomandRaw } from "./utils/types";
import { adminLog, formatCas, oddiakritikovat, log, rand, prefix, nabidni } from "./utils/utils.js";
import levenshtein from "js-levenshtein";
import { emouty } from "./utils/emotes";
import { lidiCoMajDenimPremium, setClient } from "./utils/denim-Spravce";

const ints = GatewayIntentBits;
const client = new Client({
partials: [Partials.Channel],
intents: [ints.Guilds, ints.GuildVoiceStates, ints.GuildPresences, ints.GuildMessages, ints.DirectMessages, ints.MessageContent]
}) as CClient;
const DJ_PREFIX = "dj:";
const modulFolder = `${__dirname}/modules/`;
const eventy: SRecord<ListenerFunkce<any>[]> = {};
const superEventy: SRecord<SuperListenerFunkce<any>[]> = {};
const kuldan_log: SRecord<SRecord<number>> = {};
const komandyNaPoslani: KomandNaExport[] = [];
const helpServer: HelpServer = require("./utils/helpServer");

client.komandy = {};
client.aliasy = {};
setClient(client);

function getFirstArg(fn: KomandRaw["run"]) {
if (typeof fn != "function") return;
return fn.toString()
.match(/(?:function\s.*?)?\(([^)]*)\)|\w+ =>/)![1]
?.split(",")[1]
?.trim();
}

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
try {
if (listener(...args)) return true; // if listener returns true, it means, we shouldn't continue with execustion
} catch (e) {
if (process.env.dieOnError) throw e;
log("error pri spusteni super listeneru", e as Error);
adminLog(client, "error pri supereventu", e as Error);
}
}

eventy[name]?.forEach(listener => {
try {
listener(...args);
} catch (e) {
if (process.env.dieOnError) throw e;
log("error pri spousteni eventu", e as Error);
adminLog(client, "error pri eventu", e as Error);
}
});
};

// Loading of modules
readdirSync(modulFolder).forEach(soubor => {
if (!soubor.endsWith(".js")) return;
const modul: Modul = require(`${modulFolder}${soubor}`);
log(`Loaded: ${modulFolder}${soubor}`);

modul.client = client;
for (const klic in modul) {
const prefix = /^(?<s>super_)?on_(?<h>.+)/.exec(klic);
if (prefix) {
const groups = prefix.groups!;
const ev = groups.s ? superEventy : eventy;
if (!ev[groups.h]) {
ev[groups.h] = [];
if (!["messageCreate", "userPresenceUpdate"].includes(groups.h)) client.on(groups.h, (...args) => void runEvent(groups.h, args));
}

// Bohužel typescript je tupá píča a musíme mu vysvětlit, že to vlastně jde
const n = modul[klic as Exclude<keyof Modul, "client" | "more_komandy">]!;
if (typeof n == "object") {
const prev = ev[groups.h][n.pos];
ev[groups.h][n.pos] = n.fun;
if (prev) ev[groups.h].push(prev);
}
else ev[groups.h].push(n);
} else if (klic == "more_komandy") {
const n = modul[klic]!;
Object.keys(n).forEach(cmdName => {
const value = n[cmdName];
const toCoExportuju: KomandNaExport = { name: cmdName };
let hide = false;
if (typeof value !== "object") {
client.komandy[cmdName] = { run: value };
toCoExportuju.arg = getFirstArg(value);
} else {
client.komandy[cmdName] = { run: value.run, slashRun: value.slashRun, cd: value.cd, DMUnsafe: value.DMUnsafe, premium: value.premium };
Object.assign(toCoExportuju, { als: value.als, arg: value.arg ?? getFirstArg(value.run) });
hide = !!value.hidden;
value.als?.forEach(al => client.aliasy[al] = cmdName);
}
if (!hide) komandyNaPoslani.push(toCoExportuju);
});
}
}
});

helpServer.komandy = komandyNaPoslani;

const maKuldan = (id: string, komand: string, kuldan_komandu: number) => {
if (!kuldan_log[komand]) kuldan_log[komand] = {};

const cas_ted = Date.now() / 1000;
const rozdil = cas_ted - kuldan_log[komand][id];
if (rozdil < kuldan_komandu) return kuldan_komandu - rozdil;

kuldan_log[komand][id] = cas_ted;
return 0;
};

function assume(cond: boolean, msg: string) {
if (!cond) throw msg;
}

function prase(expression: string, i: number, terminators: string[], args: string[]): [string, number, string?] {
let ret = "";
let escaped = false;

while (i < expression.length) {
const char = expression[i];
i++;

if (escaped) {
escaped = false;
ret += char;
continue;
}

switch (char) {
case "~": // eskejp
escaped = true;
break;

case "[": { // RNG vyber
let option: string, term: string | undefined;
const options: string[] = [];

do {
[option, i, term] = prase(expression, i, ["|", "]"], args);
options.push(option);
} while (term == "|");

if (options.length > 0)
ret += options[rand(options.length)];

break;
}

case "<": { // RNG cislo
let min: string, max: string;
[min, i] = prase(expression, i, [","], args);
[max, i] = prase(expression, i, [">"], args);

const imin = parseInt(min);
const imax = parseInt(max);

assume(!Number.isNaN(min), "RNG cislo: Min neni integer");
assume(!Number.isNaN(max), "RNG cislo: Max neni integer");

ret += rand(imax - imin + 1) + imin;

break;
}

case "{": {// ARG
let argId: string;
[argId, i] = prase(expression, i, ["}"], args);

if (argId === "*") { // join args
ret += args.join(" ");
} else if (argId === "#") { // number of args
ret += args.length;
} else { // arg id #
const numArgId = parseInt(argId);
assume(!Number.isNaN(numArgId) && numArgId > 0 && numArgId <= args.length, "ARG: Neplatnej index argumentu");
zbyvaj
2023-11-19 13:21:07
ret += args[numArgId - 1];
}

break;
}

default:
for (const terminator of terminators) {
if (terminator == char)
return [ret, i, char];
}

ret += char;
break;
}
}

assume(terminators.length == 0, "Neocekavanej konec vejrazu");

return [ret, expression.length - 1];
}

function renderMessage(expression: string, args: string[]) {
if (!expression.toLowerCase().startsWith(DJ_PREFIX))
return expression;

expression = expression.substring(DJ_PREFIX.length);

try {
return prase(expression, 0, [], args)[0];
} catch (ex) {
return `Chyba: ${ex}`;
}
}

function handle(e: unknown, mesOrInt: Message | CommandInteraction) {
if (process.env.dieOnError) throw e;
log("error pri spousteni akce", e as Error);
const admin = process.env.adminID;

const txt = `pri spousteni thohoto komandu nastala chyba ${admin ? `<@${admin}> uz?` : ""}`;
if (mesOrInt instanceof Message) return void mesOrInt.channel.send(txt);
mesOrInt.reply(txt);
}

async function runKomand(mes: Message, cmd: Komand, cmdName: string, arg: string): Promise<void>;
async function runKomand(interaction: CommandInteraction, cmd: Komand, cmdName: string): Promise<void>;
async function runKomand(mesOrInt: Message | CommandInteraction, cmd: Komand, cmdName: string, arg?: string) {
const jeMes = mesOrInt instanceof Message;

if (cmd.cd && jeMes) {
const zbyva = Math.round(maKuldan(mesOrInt.author.id, cmdName, cmd.cd));
if (zbyva) return void mesOrInt.channel.send(`si kkt vole maz kuldan jeste ${formatCas(zbyva)}`);
}

if (cmd.premium && !lidiCoMajDenimPremium.includes((mesOrInt instanceof Message) ? mesOrInt.author.id : mesOrInt.member?.user.id || "")) {
return void mesOrInt.channel?.send("sorka bracho tuto je koamnd jenom pro curaki co platy");
}

const akce = jeMes
? cmd.run
: cmd.slashRun!;

if (typeof akce == "string") {
const res = renderMessage(akce, arg?.split(" ") || []);
if (mesOrInt instanceof Message) return void mesOrInt.channel.send(res);
return void mesOrInt.reply(res);
}

try {
// Je to absolutní fekálie, ale alespoň to je kompilovatelný narozdíl od předchozí verze (commit 08fde76 a předchozí)
const result = await akce(mesOrInt as never, arg || "");
if (!result) return;

if (jeMes) return void mesOrInt.channel.send(result)
.catch(e => handle(e, mesOrInt));
// další feklo
mesOrInt.reply(result as InteractionReplyOptions);
} catch (e) {
handle(e, mesOrInt);
}
}

client.on("messageCreate", async mes => {
if (process.env.ignoreMess) return;

const [mesPrefix, komandSDiakritikou, ...args] = mes.content.split(" ");

const prefixDiff = levenshtein(oddiakritikovat(mesPrefix.toLowerCase()), prefix);
if (prefixDiff > 0) {
if (!runEvent("messageCreate", [mes]) && prefixDiff <= 1 && mes.author.id != client.user!.id) mes.channel.send(`${prefix}*`);
return;
}

if (!komandSDiakritikou) {
if (!runEvent("messageCreate", [mes])) mes.channel.send("coe voe");
return;
}

const celArgs = args.join(" ");
const komandBez = oddiakritikovat(komandSDiakritikou).toLowerCase();
const cmdName = client.aliasy[komandBez] ?? komandBez;

if (runEvent("messageCreate", [mes, cmdName])) return;

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 (komand) return void runKomand(mes, komand, cmdName, celArgs);

// neměl jsi na mysli?
const slova: string[] = [];
[...Object.keys(client.komandy), ...Object.keys(client.aliasy)].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);

nabidni({
nabidka,
channel: mes.channel,
zpravec: { content: "nemnel sy na misli:" },
onCollect: (i, lookupId, radek) => {
if (i.member?.user.id != mes.author.id) return;
const komand = nabidka[lookupId];
const cmdName = client.aliasy[komand] ?? komand;
const cmd = client.komandy[cmdName];
radek.components.forEach(btn => btn.setDisabled());
i.update({ content: `ok vole ${emouty.d3k}`, components: [radek] });

if (!cmd) return void mes.channel.send("bohuzel negdo sy ze mi dela prel");

if (mes.channel.type == ChannelType.DM && cmd?.DMUnsafe) return void mes.channel.send("tuten komand bohuzel v sz nefunkuje");

runKomand(mes, cmd, cmdName, celArgs);
},
konecnaZprava: "pozde"
});
});

// Simulation of userPresenceUpdate event
client.on("presenceUpdate", (bef, aft) => {
const user = aft.user as CUser | null;
if (!user) return;
if (!user.presence) user.presence = {};

if (JSON.stringify(aft.clientStatus) == JSON.stringify(user.presence)) return;
user.presence = aft.clientStatus || {};

runEvent("userPresenceUpdate", [bef, aft]);
});

client.on("interactionCreate", async int => {
if (process.env.ignoreMess || !int.isCommand()) return;

const cmdName = int.commandName.slice(prefix.length);

const command = client.komandy[cmdName];
if (!command) return void int.reply(`komand nenalezen ${emouty.lukiw}`);

runKomand(int, command, cmdName);
});

client.login(process.env.token);
zbyvaj
2023-11-19 13:22:57
// Tento modul je zasvěcen komandům, které je potřeba zachovat a jsou tak primitivní, že se dají zkombinovat do jednoho kompaktního souboru.

import { ActivityType, ChannelType, Message, PresenceStatusData } from "discord.js";
import { emouty } from "../utils/emotes";
import { Modul } from "../utils/types";
import { formatCas, ping, rand } from "../utils/utils";

const pomoc: [string[], Record<string, unknown>] = require("../../res/pomoc.json");
const ftipy: string[] = require("../../res/ftipy.json");

const delAndReturn = (mes: Message, co: string) => {
if (mes.channel.type != ChannelType.DM) mes.delete();
return co;
};

const changeStatus = (mes: Message, status: PresenceStatusData) => {
mes.client.user?.setStatus(status);
return "ano pane";
};

const changeActivity = (mes: Message, activity: Exclude<ActivityType, ActivityType.Custom> | undefined = undefined, txt: string = "") => {
mes.client.user?.setActivity(txt, { type: activity });
mes.react(emouty.d3k);
return "ano pane";
};

const choose = (arr: string[]) => arr[rand(arr.length)];

const exp: Modul = {
more_komandy: {
vole: "coe voe more gadzo",

kobel: "kde?",

ano: {
als: ["jo", "ne"],
run: "ok"
},

rekt: "**ouuuuuuuuuuuuuuuuuuuuu**",

omegasmart: "<:DENIM3K_OMEGASMART1:638103812892131328><:DENIM3K_OMEGASMART2:638104266195861514><:DENIM3K_OMEGASMART3:638104266178822155>\n<:DENIM3K_OMEGASMART4:638104266246062180><:DENIM3K_OMEGASMART5:638104266241867787><:DENIM3K_OMEGASMART6:638104265889546241>\n<:DENIM3K_OMEGASMART7:638104266267033610><:DENIM3K_OMEGASMART8:638104266271096882><:DENIM3K_OMEGASMART9:638104266258513960>",

lag: "protoze to spousti na tich stravberi",

triggered: "toto me trickeruje",

slak: "te natahne\nhttps://tenor.com/view/tired-done-imdone-afterschool-school-gif-5682065";,

pomoc: pomoc[0].join("\n"),

pomoc2: () => { return { embeds: [pomoc[1]] }; },

pomoc3: `${emouty.lukiw} :point_right: https://denim3001.deadfish.cz/morepomoc`,

verze: () => `${require("../../package.json").version}\nčenžlog mas tady https://denim3001.deadfish.cz/morehovna`,

navrh: "tadi mas prostor https://navrhy.denim3001.deadfish.cz/";,

uptime: () => `uz jedu ${formatCas(Math.round(globalThis.performance.now() / 1000))}`,

rekni: (mes, co) => {
if (mes.author.bot) return "ne";
return delAndReturn(mes, co || `co mam jako rict ${mes.author}`);
},

clap: (mes, text) => {
return delAndReturn(mes, `${text} ${emouty.clap}`);
},

clap2: (mes, text) => {
return delAndReturn(mes, `${emouty.clap2} ${text}`);
},

voliz: (mes, co) => {
return delAndReturn(mes, `${emouty.lickL}${co}${emouty.lickR}`);
},

pozdrav: (_, koho) => `zdravim ${koho}`,

zhejti: (_, koho) => `${koho} je pycovina zasrana vimrdana`,

uraz: (_, koho) => `${koho} , u suck`,

online: {
als: ["onlajn", "zelenej"],
run: mes => changeStatus(mes, "online")
},
idle: {
als: ["zlutej", "afk", "idle", "nepritomnej"],
run: mes => changeStatus(mes, "idle")
},
dnd: {
als: ["nerusit", "cervenej"],
run: mes => changeStatus(mes, "dnd")
},
offline: {
als: ["oflajn", "neviditelnej"],
run: mes => changeStatus(mes, "invisible")
},

hraj: (mes, co) => changeActivity(mes, ActivityType.Playing, co),
sleduj: (mes, co) => changeActivity(mes, ActivityType.Watching, co),
poslouchej: (mes, co) => changeActivity(mes, ActivityType.Listening, co),
soutez: (mes, vcem) => changeActivity(mes, ActivityType.Competing, vcem),
nedelej: mes => changeActivity(mes),

vtip: {
als: ["ftip"],
run: () => choose(ftipy)
},

kam: () => choose(["na šroťák", "na vrakoviště", "na smetiště", "do kontejneru", "na skládku", "do kriminálu", "pod most", "do sběru", "do hospody", "do najt klubu", "na folmavu"]),

je: {
arg: "kdo/co",
run: () => rand(2) ? "jo je" : "ne neni"
},

ma: {
arg: "kdo/co",
run: () => rand(2) ? "jo ma" : "ne nema"
},

nazor: {
arg: "koho/co",
run: (_, arg) => rand(2) ? `mam rad ${arg}` : `${arg} je picovina`
},

si: {
als: ["jsi"],
run: (_, co) => {
const corict = co.replace(/\?/g, "");
return rand(2) ? `jo sem ${corict}` : `ne nejsem ${corict}`;
}
},

mas: (_, co) => {
const corict = co.replace(/\?/g, "");
return rand(2) ? `jo mam ${corict}` : `ne nemam ${corict}`;
},

jakmoc: {
run: (_, co) => `${co} na ${rand(101)}%`
},


jakmoc0: {
run: (_, co) => `${co} na ${rand(1001)}‰`
},

uz: {
als: ["uz?"],
run: () => choose(["ne", "jeste ne", "jiz brzy", "za chvili", "vubec", "nikdy", "za dlouho", "za 5 let", "zejtra", "davno", "jo", "mozna"])
},

vyber: {
arg: "co (odděleno čárkami nebo \"|\")",
run: (_, arg) => {
if (!arg.length) return "co vole";
const moznosti = arg.split(arg.indexOf("|") > -1 ? "|" : ",").filter(m => m.length);
return choose(moznosti) || "kokot";
}
},

fight: {
als: ["figh", "fajt"],
run: (mes, skym) => {
if (!ping.test(skym)) return "tak si kokot ti kokote";

const vyherce = Math.random() < 0.5 ? mes.author : skym;
return `tento figh vyhrál: ${vyherce}!`;
}
}
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:23:08
// Modul na komand "anketa"

import { ActionRowBuilder, APIEmbed, APIEmbedField, ButtonBuilder, ButtonStyle, CommandInteraction, ComponentType, InteractionResponse, Message, MessageComponentInteraction, MessageEditOptions } from "discord.js";
import { Modul, SRecord } from "../utils/types";
import { formatter } from "../utils/utils";

function parseMoznosti(moznostiStr: string) {
return moznostiStr.split(moznostiStr.includes("|") ? "|" : ",").reduce<string[]>((acc, c) => {
if (c.length) acc.push(c.trim());
return acc;
}, []);
}

async function zbytek(settings: { time: number; immediateShow: boolean; listNames: boolean; }, moznosti: string[], mesOrInt: Message | CommandInteraction) {
if (moznosti.length < 2) return "zadej alespo%n dve moznosti";
if (moznosti.length > 25) return "toje moc";

const jeMes = mesOrInt instanceof Message;

const konec = new Date();
konec.setSeconds(konec.getSeconds() + settings.time);

const embed: APIEmbed = {
title: "Hlasování",
description: settings.immediateShow ? `Končí ${formatter(konec)}` : `Výsledky se zobrazí ${formatter(konec)}`
};
const fildy: APIEmbedField[] = [];
const radky: ActionRowBuilder<ButtonBuilder>[] = [];
const odpovedi: SRecord<number> = {};

function prepocitat(int?: MessageComponentInteraction) {
const celkem = Object.keys(odpovedi).length;
fildy.forEach((f, i) => {
const hovn = Object.values(odpovedi).filter(n => n == i);
const dylka = hovn.length;
const p = Math.floor(dylka / celkem * 10) || 0;
const people = Object.keys(odpovedi).reduce<string[]>((pr, cur) => {
if (odpovedi[cur] == i) pr.push(cur);
return pr;
}, []);
const kindo = people.map(w => mesOrInt.guild?.members.cache.get(w)?.displayName);
f.value = `${"█".repeat(p)}${"░".repeat(10 - p)} ${Math.round(dylka / celkem * 100) || 0}% (${dylka}) ${settings.listNames ? " (" + kindo.join(", ") + ")" : ""}`;
});
int?.update({ embeds: [embed] });
}

moznosti.forEach((h, i) => {
const mnam = (i - (i % 5)) / 5;
if (i % 5 == 0) radky[mnam] = new ActionRowBuilder<ButtonBuilder>;
fildy.push({ name: h, value: "" });
radky[mnam].addComponents(new ButtonBuilder({ customId: `${i}`, label: h, style: ButtonStyle.Primary }));
});
prepocitat();
if (settings.immediateShow) embed.fields = fildy;

let zprava: Message<boolean> | InteractionResponse;
let edit: (c: MessageEditOptions) => void;

if (jeMes) {
zprava = await mesOrInt.channel.send({ embeds: [embed], components: radky });
edit = content => { zprava.edit(content); };
} else {
zprava = await mesOrInt.reply({ embeds: [embed], components: radky });
zprava;
edit = content => { mesOrInt.editReply(content); };
}
const collector = zprava.createMessageComponentCollector<ComponentType.Button>({ time: settings.time * 1000 });

collector.on("collect", d => {
if (!(d.message instanceof Message)) return;
const i = Number(d.customId);
const prev = odpovedi[d.user.id];
if (prev == i) return void d.deferUpdate();
odpovedi[d.user.id] = i;
if (!settings.immediateShow) return void d.deferUpdate();
prepocitat();
d.update({ embeds: [embed] });
});

collector.on("end", () => {
embed.description = `Skončilo ${formatter(konec)}`;
prepocitat();
embed.fields = fildy;
edit({ components: [], embeds: [embed] });
});
}

const exp: Modul = {
more_komandy: {

anketa: {
arg: "([nastaveni]) moznosti...",
DMUnsafe: true,
run: async (mes, arg) => {

const settings = {
time: 60,
immediateShow: true,
listNames: false
};

let huuuuuu = -1;
if (arg.startsWith("[")) {
huuuuuu = arg.indexOf("]");
const hovn = arg.slice(1, huuuuuu);
const f = hovn.split(" ");
for (const s of f) {
const t = Number(s);
if (!Number.isNaN(t)) settings.time = t;
else if (s == "jmena") settings.listNames = true;
else if (s == "neprubezny") settings.immediateShow = false;
else return `"${s}" neznam znam jenom jmena a neprubezny`;
}
}

const moznosti = parseMoznosti(arg.slice(huuuuuu + 1));

return await zbytek(settings, moznosti, mes);
},

slashRun: async int => {

const opt = int.options;
const settings = {
time: opt.get("cas")?.value as number || 60,
immediateShow: !opt.get("neprubezny")?.value as boolean,
listNames: !!opt.get("jmena")?.value as boolean
};

const moznosti = parseMoznosti(opt.get("moznosti")!.value as string);

return await zbytek(settings, moznosti, int);
}

}
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:23:20
import { CClient, HelpServer, Komand, KomandNaExport, Modul, SRecord } from "../utils/types";
import { join } from "path";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { oddiakritikovat, prefix, strankovani } from "../utils/utils";
import { APIEmbed } from "discord.js";

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, custom: true });
}

client.komandy = { ...cKomandyAsKomand, ...zakladniKomandy };

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();
}

function komandNeboAlias(nazev: string) {
if (customKomandy[nazev]) return { jeKomand: true, cmd: customKomandy[nazev] };
if (customAliasy[nazev]) return { jeKomand: false, cmd: customAliasy[nazev] };
return { jeKomand: false };
}

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 (name == "") return "a co mam jako zapomenout";

if (zakladniKomandy[name]) return "tuten komand se neda smazat ti smazko";
if (zakladniAliasy[name]) return "tuten alijaas se neda smazat ti smazko";

const { jeKomand, cmd } = komandNeboAlias(name);
if (!cmd) return `"${name}" nen komnad an alias`;

if (cmd.owner != mes.author.id) return "tuto ael neni tvoje 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}>`;
}
},

mojekomandy: async mes => {
const arr = ["tovje koamdy:\n"];

for (const key in customKomandy) {
if (customKomandy[key].owner == mes.author.id) arr.push(key);
}

arr.push("\ntovje ajilasy:\n");

for (const key in customAliasy) {
if (customAliasy[key].owner == mes.author.id) arr.push(key);
}

let text = "";
arr.forEach(element => {
if (text.length + element.length > 2000) {
mes.channel.send({ content: text, allowedMentions: { users: [] } });
text = "";
}
text += `${element}\n`;
});

return { content: text, allowedMentions: { users: [] } };
},

jehokomandy: {
DMUnsafe: true,
run: () => {
const client: CClient = module.exports.client;

return `tuto je novej komand a histmaj mrdal aby to slo i takhle proste pouzij </${prefix}jehokomandy:${client.slashCommandy[`${prefix}jehokomandy`]}>`;
},

slashRun: int => {
const kdoId = int.options.get("gdo")!.value as string;
const kdo = client.users.cache.get(kdoId);

if (!kdo) return "tutoko kokota neznam";

const arr = [`koamdy kkta ${kdo.username}:\n`];

for (const key in customKomandy) {
if (customKomandy[key].owner == kdo.id) arr.push(key);
}

arr.push("\njeho ajilasy:\n");

for (const key in customAliasy) {
if (customAliasy[key].owner == kdo.id) arr.push(key);
}

function send(text: string, i: number) {
if (i == 0) int.reply({ content: text, allowedMentions: { users: [] } });
else int.channel!.send({ content: text, allowedMentions: { users: [] } });
}

let text = "";
let i = 0;
arr.forEach(element => {
if (text.length + element.length > 2000) {
send(text, i);
text = "";
i++;
}
text += `${element}\n`;
});

send(text, i);
}
},

uprav: {
arg: "název komandu",
run: (mes, arg) => {
const args = arg.split(" ").filter(v => v != "");

if (args.length == 0) return "a co mam jako vopravit";
if (args.length == 1) return "a co bich nato mnel rict????";

const name = oddiakritikovat(args[0].toLowerCase());

if (zakladniKomandy[name]) return "tuten komand se neda vopravit";
if (zakladniAliasy[name]) return "tuten alijaas se neda vopravit";

const { jeKomand, cmd } = komandNeboAlias(name);
if (!cmd) return `"${name}" nen komnad an alias`;

if (cmd.owner != mes.author.id) return "tuto ael neni tvoe toxikale zkurvenej";

jeKomand ? delete customKomandy[name] : delete customAliasy[name];

customKomandy[name] = { text: args.splice(1).join(" "), owner: mes.author.id };
save();
return "jo";
}
},

uprava: {
arg: "název aliasu",
run: (mes, arg) => {
const args = arg.split(" ").filter(v => v != "").map(v => oddiakritikovat(v));
const name = args[0];

if (args.length == 0) return "a co mam jako vopravit";
if (args.length == 1) return "a co to ma znamenat????";

if (zakladniKomandy[name]) return "tuten komand se neda vopravit";
if (zakladniAliasy[name]) return "tuten alijaas se neda vopravit";

const { jeKomand, cmd } = komandNeboAlias(name);
if (!cmd) return `"${name}" nen komnad an alias`;

if (cmd.owner != mes.author.id) return "tuto ael neni tvoe toxikale zkurvenej";

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]];

jeKomand ? delete customKomandy[name] : delete customAliasy[name];

customAliasy[args[0]] = { cmd: jmeno, owner: mes.author.id };
save();
return "jo";
}
},

aliasy: (mes, arg) => {
const name = arg.toLowerCase();
const cmdName = client.aliasy[name] ?? name;

let celkovadylka = 0;
const stranky: string[][] = [[]];
let aktualniStranka = 0;
for (const key in client.aliasy) {
const val = client.aliasy[key];
if (val != cmdName) continue;

const dylka = key.length + 3;
celkovadylka += dylka;
if (celkovadylka > 1024 || stranky[aktualniStranka].length == 20) {
aktualniStranka++;
celkovadylka = dylka;
}

const stranka = stranky[aktualniStranka] ??= [];
stranka.push(key);
}

if (!celkovadylka) return `"${name}" bud nen9 komand ani ajilas nebo nema ajilasi vubec`;

const zacatekNazvu = `alijasy pro **${cmdName}**:`;
const embed: APIEmbed = {
color: 13697024,
fields: [{ name: zacatekNazvu, value: `• ${stranky[0].join("\n• ")}` }]
};

if (stranky.length == 1) return { embeds: [embed] };

embed.fields![0].name += ` (1/${stranky.length})`;

strankovani(mes.channel, embed, zacatekNazvu, stranky);
}
},

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;
zbyvaj
2023-11-19 13:23:29
import { getVoiceConnection } from "@discordjs/voice";
import { Modul } from "../utils/types";
import { renameSync, rmSync, readdirSync, writeFileSync } from "fs";
import { join } from "path";
import { Priority, novejPlay } from "../utils/voice";
import { lidiCoMajDenimPremium } from "../utils/denim-Spravce";
import fetch from "node-fetch";
import { exec } from "child_process";
import { log } from "../utils/utils";

const kmenovaCesta = join(__dirname, `../../zvuky/priVstupu`);
const formaty = ["mp3", "wav", "ogg"];

function vymaz(path: string) {
try {
rmSync(path);
} catch { }
}

const exp: Modul = {
more_komandy: {

zmenitvstupnizvuk: {
premium: true,
run: async mes => {

const soubor = mes.attachments.first();

if (!soubor) return "tak pico ael na co";

if (!formaty.includes(soubor.name.slice(-3))) return "tuten format nechcy";
if (soubor.size > 2_097_152) return "min nes dva mebagajyt pls";

// Stahnout dočasně
const typ = soubor.name.slice(-3);
const docasnaCesta = `${kmenovaCesta}/temp${Math.round(Math.random() * 1000)}.${typ}`;

const odpoved = await fetch(soubor.url).then(r => r.arrayBuffer());
writeFileSync(docasnaCesta, new DataView(odpoved));

// Zjistit running-time
exec(`ffprobe -i ${docasnaCesta} -show_entries format=duration -v quiet -of csv="p=0"`, (error, stdout) => {
if (error) {
log("chyba pri ffprobe", error);

mes.channel.send("bohuzel chiba");
vymaz(docasnaCesta);
return;
}

// Maximum
if (Number(stdout) > 13) {
mes.channel.send("13 se kund maks");
vymaz(docasnaCesta);
return;
}

// Smazat starej (nevíme formát, tak musíme zkust všechny)
const zaklad = `${kmenovaCesta}/${mes.author.id}`;
for (const format of formaty) {
vymaz(`${zaklad}.${format}`);
}

renameSync(docasnaCesta, `${zaklad}.${typ}`);

mes.channel.send("ej tot am");
});
}
}
},

on_voiceStateUpdate: (bef, aft) => {
const conn = getVoiceConnection(aft.guild.id);

// Jestli vůbec zvuk zahrát
if (!conn || conn.joinConfig.channelId != aft.channelId || !lidiCoMajDenimPremium.includes(aft.id) || !aft.channelId || bef.channelId == aft.channelId) return;

// Najít zvuk k přehrání
for (const soubor of readdirSync(kmenovaCesta)) {
if (!soubor.startsWith(aft.id)) continue;

novejPlay(aft.guild.id, `${kmenovaCesta}/${soubor}`, Priority.Time);
return;
}

}
};

module.exports = exp;
zbyvaj
2023-11-19 13:23:39
// Komandy, co maj víc než "pár" řádek, a který si nezaslouží vlastní soubor

import { ChannelType, Message, MessageReaction } from "discord.js";
import { emouty } from "../utils/emotes";
import { Modul, SRecord } from "../utils/types";
import { formatter, ping } from "../utils/utils";

const exp: Modul = {
more_komandy: {

status: (mes, koho) => {
if (!ping.test(koho)) return "tak si kokot ti kokote";

const uzivatel = mes.mentions.members!.first()!;
const embed = {
title: `Informace o statusech pro ${uzivatel.displayName}:`,
color: 431075,
description: ""
};
const presence = uzivatel.presence?.clientStatus;
if (!(presence && Object.keys(presence).length)) {
embed.description = "*Všude je offline*";
} else {
const zarizeni: SRecord<string> = { desktop: "Počítač", mobile: "Mobil", web: "Web" };
const statusy = { online: "🟢", idle: "🟡", dnd: "🔴" };
const uStatusy: string[] = [];
const klice = Object.keys(presence) as ("web" | "mobile" | "desktop")[];
klice.forEach(status => {
uStatusy.push(`${zarizeni[status]}: ${statusy[presence[status]!]}`);
});
embed.description = uStatusy.join("\n");
}
return { embeds: [embed] };
},

zareaguj: {
als: ["react"],
arg: "emout/emouty",
run: async (mes, arg) => {
const emouty = arg.split(" ");

let naCo: Message;
if (mes.reference) {
naCo = await mes.channel.messages.fetch(mes.reference.messageId!);
} else {
const msgs = [...mes.channel.messages.cache.values()];
if (msgs.length < 2) {
naCo = (await mes.channel.messages.fetch({ limit: 2 })).at(1)!;
}
else naCo = msgs[msgs.length - 2];
}

const reakce: Promise<void | MessageReaction>[] = [];
if (mes.channel.type != ChannelType.DM) mes.delete();
emouty.forEach(emout => {
reakce.push(naCo.react(emout)
.catch(() => { }));
});

if (!(await Promise.all(reakce)).every(r => !!r != false)) return "retarde";
}
},

odpocitej: mes => {
const randomshit = (mes: Message, argument: string[]) => {
mes.edit(argument[0]);
argument.splice(0, 1);
if (argument.length) setTimeout(() => randomshit(mes, argument), 1000);
};
mes.channel.send(":stop_button:").then(mes => randomshit(mes, [":five:", ":four:", ":three:", ":two:", ":one:", ":ok:"]));
},

pocasi: () => {
const embed = {
title: "Počasí",
image: { url: "attachment://pocasi.png" }
};
return { embeds: [embed], files: ["https://util.deadfish.cz/morepocasi/v/49.4348358/12.8147250/pocasi.png";] };
},

pockej: {
als: ["cekej"],
arg: "počet sekund",
run: async (mes, arg) => {
if (mes.author.id == mes.client.user?.id) return emouty.sjeta;
let cas: number;
if (arg.length) {
cas = Number(arg);
if (isNaN(cas)) return "cos to tam napsal ty kkt";
} else {
cas = Math.floor(Math.random() * 10740 + 60);
}

try {
await mes.author.send(`test ${emouty.d3k}`);
} catch {
return "ja ti ale napsat nemuzu ti kundo";
}

setTimeout(async () => {
for (let i = 0; i < 15; i++) {
await mes.author.send("uz?");
}
}, cas * 1000);

const datum = new Date();
datum.setSeconds(datum.getSeconds() + cas);
return `doufam ze v ${formatter(datum)} to uz bude`;
}
}
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:23:49
// Tady bude muzika, vole

import { AudioPlayerStatus, VoiceConnectionStatus } from "@discordjs/voice";
import { Client } from "discord.js";
import { search, soundcloud, stream, validate, video_basic_info } from "play-dl";
import { emouty } from "../utils/emotes";
import { Modul } from "../utils/types";
import { adminLog, log } from "../utils/utils";
import { getConn, novejJoin, novejPlay, Priority, stopPlayer } from "../utils/voice";

const guildy = new Map<string, { kju: { name: string; url: string; }[]; loop: boolean; }>();

async function playNext(guildId: string, seek?: number) {
try {
const guilda = guildy.get(guildId)!;
const kju = guilda.kju;
const item = kju[0];

const src = await stream(item.url, { seek });
novejPlay(guildId, { src: src.stream, volume: 1, type: src.type }, Priority.Music)
.then(state => {
if (state.status != AudioPlayerStatus.Idle) return;

if (!guilda.loop) kju.shift();

if (kju.length)
return playNext(guildId);
})
.catch(e => {
log("chyba v muziki", e);
});
} catch (e) {
if (e instanceof Error && e.message.startsWith("Seeking beyond limit"))
return stopPlayer(guildId, Priority.Music);

log(e);
const client: Client = module.exports.client;
adminLog(client, "error v hani muziky", e as Error);
}
}

const exp: Modul = {
more_komandy: {
zahraj: {
DMUnsafe: true,
run: async (mes, txt) => {
const kanel = mes.member?.voice.channelId;
if (!kanel) return "nejsi ve vojsu ty kkt";

const guildId = mes.guildId!;
const ajtem = { name: "", url: "" };
const druh = await validate(txt);
if (druh && druh != "search") {
if (druh != "yt_video" && druh != "so_track") return "tuto neumim zahrat";
ajtem.url = txt;
if (druh == "yt_video") {
try {
const video = await video_basic_info(txt);
ajtem.name = video.video_details.title!;
} catch (e) {
return "sorka bracho ael tuto je ajdzreztrigtnuti";
}
if (typeof ajtem.name == "undefined") {
const client: Client = module.exports.client;
adminLog(client, "video nemá název");
}
mes.channel.send(`zahraju \`${ajtem.name}\``);
} else {
const sound = await soundcloud(txt);
ajtem.name = sound.name;
mes.channel.send(`zahraju \`${ajtem.name}\``);
}
} else {
const msg = mes.channel.send("hledam");
const hledani = await search(txt, { limit: 1 });
if (!hledani[0]) return "nic sem nenašel";
ajtem.url = hledani[0].url;
ajtem.name = hledani[0].title!;
msg.then(m => void m.edit(`zahraju \`${ajtem.name}\``));
}

if (!guildy.has(guildId)) {
guildy.set(guildId, { kju: [], loop: false });
}
const kju = guildy.get(guildId)!.kju;
kju.push(ajtem);

if (kju.length != 1) return;

await novejJoin(mes.guild!, kanel);
getConn(guildId)?.once(VoiceConnectionStatus.Destroyed, () => {
kju.length = 0;
});
playNext(guildId);
}
},

queue: {
als: ["q", "kju"],
DMUnsafe: true,
run: mes => {
const kju = guildy.get(mes.guildId!)?.kju;
if (!kju?.length) return "nehraje nic";

return `tuto je kurentni repertoar:\n${kju.reduce((acc, cur, i) => {
const jmeno = `${cur.name} (<${cur.url}>)`;
return `${acc}\n${i ? `${i}. ${jmeno}` : `-- *${jmeno}* --`}`;
}, "")}`;
}
},

skip: {
DMUnsafe: true,
run: mes => {
const kju = guildy.get(mes.guildId!)?.kju;
if (!kju?.length) return "nehraje nic";

stopPlayer(mes.guildId!, Priority.Music);
mes.react(emouty.d3k);
}
},

remove: {
DMUnsafe: true,
als: ["odebrat"],
run: (mes, arg) => {
const numero = Number(arg);
if (isNaN(numero)) return "cokundo?";

const kju = guildy.get(mes.guildId!)?.kju;
if (!kju?.length) return "nehraje nic";

if (kju.length <= numero) return "tolik toho nehrae";

kju.splice(numero, 1);
mes.react(emouty.d3k);
}
},

seek: {
DMUnsafe: true,
run: (mes, arg) => {
const numero = Number(arg);
if (isNaN(numero)) return "huh?";

const kju = guildy.get(mes.guildId!)?.kju;
if (!kju?.length) return "nehraje nic";

playNext(mes.guildId!, numero);
mes.react(emouty.d3k);
}
},

loop: {
DMUnsafe: true,
run: mes => {
if (!guildy.has(mes.guildId!)) {
guildy.set(mes.guildId!, { kju: [], loop: false });
}

const guilda = guildy.get(mes.guildId!)!;

guilda.loop = !guilda.loop;

return `lup je ${guilda.loop ? "zapnutej" : "ukoncen"}`;
}
}
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:23:59
import { ApplicationCommandOptionType, REST, RESTPostAPIChatInputApplicationCommandsJSONBody, Routes } from 'discord.js';
import { CClient, Modul, SRecord } from '../utils/types';
import { log, prefix } from '../utils/utils';

const komandy: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [
{
name: `${prefix}anketa`,
description: "udelam fajnonovou anketu haby sy moch myt zbitecny anzori ostatnich",
dm_permission: false,
options: [
{
name: "moznosti",
description: "mezi cim maj ty morove vibirat (odeluj carkama nebo pipama)",
type: ApplicationCommandOptionType.String,
required: true
},
{
name: "cas",
description: "jak dlouho budem cekat na ti bridili nez se rozhodnou",
type: ApplicationCommandOptionType.Integer
},
{
name: "jmena",
description: "jestli chces strapnovat ostatni jejich vibjerem tak tuto zapni",
type: ApplicationCommandOptionType.Boolean
},
{
name: "neprubezny",
description: "jestli chces haby bili visledky vydet hned nebo az potom co bude pozde sy to rozmyslet",
type: ApplicationCommandOptionType.Boolean
}
]
},

{
name: `${prefix}vyhledej`,
description: "vihledavani tak dobri ze je dyckscord muze jenom zavydet",
dm_permission: false,
options: [
{
name: "kontent",
description: "nejaki pysmenka kteri ve spravje jsou v tutom poradi",
type: ApplicationCommandOptionType.String,
required: false
},
{
name: "regex",
description: "regulerni exprese ktera se aplykuje na obsach spravy (hestly nevys co to je pouzij radsi 'kontent')",
type: ApplicationCommandOptionType.String,
required: false
},
{
name: "uzivatel",
description: "kerej kokot spavu posral",
type: ApplicationCommandOptionType.User,
required: false
},
{
name: "od",
description: "vihledat zpravy mladsy nez tuten datum\npotporuju vsechni formati jako new Date() v jávaskryptech",
type: ApplicationCommandOptionType.String,
required: false
},
{
name: "do",
description: "vihledat zpravy starsi nez tuten datum\npotporuju vsechni formati jako new Date() v jávaskryptech",
type: ApplicationCommandOptionType.String,
required: false
},
{
name: "obrasek",
description: "estli sprava ma nejakej obrasek (a jakoze fakt vobrasek, ne otkas na gif)",
type: ApplicationCommandOptionType.Boolean,
required: false
},
{
name: "link",
description: "estli sprava ma link",
type: ApplicationCommandOptionType.Boolean,
required: false
},
{
name: "seradit",
description: "jak visletki poskladat",
type: ApplicationCommandOptionType.String,
choices: [{
name: "ot polen co nejlip horej",
value: "ASC"
},
{
name: "ot tech nejvic fres",
value: "DESC"
}
],
required: false
},
{
name: "ma_soubor",
description: "estli je u spravi nejakej souor",
type: ApplicationCommandOptionType.Boolean,
required: false
},
{
name: "nazev_souboru",
description: "vihledat spravi se souborem s takovim nazvem",
type: ApplicationCommandOptionType.String,
required: false
},
]
},

{
name: `${prefix}jehokomandy`,
description: "napysu ti koamndy kteri udelal kkt kteriho viberes",
dm_permission: false,
options: [
{
name: "gdo",
description: "ten kkt",
type: ApplicationCommandOptionType.User,
required: true
}
]
}
];

const exp: Modul = {
on_ready: async () => {
const client = module.exports.client as CClient;
client.slashCommandy = {};

// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(process.env.token!);

// and deploy your commands!
try {
// The put method is used to fully refresh all commands in the guild with the current set
const data = (await rest.put(
Routes.applicationCommands(client.user!.id),
{ body: komandy },
)) as SRecord<string>[] | undefined;

data?.forEach(command => {
client.slashCommandy[command.name] = command.id;
});
} catch (error) {
// And of course, make sure you catch and log any errors!
log("Chyba při refreshování aplikačních (/) komandů", error);
}

}
};

module.exports = exp;
zbyvaj
2023-11-19 13:24:21
// Jo, šachec,

import { APIEmbed, Message } from "discord.js";
import { Modul, SRecord } from "../utils/types";
import { fokinLookupTable, klikance, pocetKeStrane } from "../utils/sachyEtc";
import { emiter } from "../utils/sachyServer";

const hry: SRecord<Hra> = {};
const hraci: SRecord<string> = {};

const smery = [-8, 1, 8, -1, -7, 9, 7, -9];

const mkPis = (barva: Figurka["barva"], typ: Figurka["typ"]) => ({ barva, typ, netahnuta: true, enPassantovatelna: false });

function createGame(kanel: string, bilej: string, cernej: string, mes: Message) {

const deska: Deska = [...new Array(64)];

for (let i = 0; i < 8; i++) {
deska[i + 8] = mkPis("cerna", "pawn");
deska[i + 48] = mkPis("bila", "pawn");
}

deska[0] = mkPis("cerna", "rook");
deska[7] = mkPis("cerna", "rook");
deska[56] = mkPis("bila", "rook");
deska[63] = mkPis("bila", "rook");

deska[1] = mkPis("cerna", "knight");
deska[6] = mkPis("cerna", "knight");
deska[57] = mkPis("bila", "knight");
deska[62] = mkPis("bila", "knight");

deska[2] = mkPis("cerna", "bishop");
deska[5] = mkPis("cerna", "bishop");
deska[58] = mkPis("bila", "bishop");
deska[61] = mkPis("bila", "bishop");

deska[4] = mkPis("cerna", "king");
deska[60] = mkPis("bila", "king");

deska[3] = mkPis("cerna", "queen");
deska[59] = mkPis("bila", "queen");

const hra: Hra = {
bila: bilej,
cerna: cernej,
deska,
hraje: "bila",
tahy: [],
message: mes
};

hry[kanel] = hra;

return hra;
}

function jeCheck(barva: Hra["hraje"], deska: Deska) {

let check = false;
const index = deska.findIndex(pis => pis?.typ == "king" && pis.barva == barva);

// Od tahačů
for (let smer = 0; smer < 8; smer++) {
for (let n = 1; n <= pocetKeStrane[index][smer]; n++) {

const target = index + smery[smer] * n;
const pisNaTargetu = deska[target];

if (pisNaTargetu?.barva != barva && [(smer < 4 ? "rook" : "bishop"), "queen"].includes(pisNaTargetu?.typ || "")) return true;

if (pisNaTargetu) break;
}
}

// Od koliků
[[-1, 2], [1, 2], [-2, 1], [2, 1], [-2, -1], [2, -1], [-1, -2], [1, -2]].forEach(smery => {

const x = smery[0] > 0 ? 1 : 3;
const y = smery[1] > 0 ? 2 : 0;

// Estli je mimo board
if (pocetKeStrane[index][x] < Math.abs(smery[0]) || pocetKeStrane[index][y] < Math.abs(smery[1])) return;

const target = index + (8 * smery[1] + smery[0]);
const pis = deska[target];

// Estli už tam felí náš
if (pis?.barva == barva) return;

if (pis?.typ == "knight") check = true;
});

// od pawnů
[7, 9].forEach(i => {
const pis = deska[index - i];
if (pis?.typ == "pawn" && pis.barva != barva) check = true;
});

// od králika
for (let smer = 0; smer < 8; smer++) {
if (pocetKeStrane[index][smer] == 0) continue;

if (deska[index + smery[smer]]?.typ == "king") return true;
}

return check;
}

function tahyProJezdiciPisi(index: number, pis: "queen" | "bishop" | "rook", deska: Deska) {

const tahy: number[] = [];
const barva = deska[index]!.barva;

const startSmer = pis == "bishop" ? 4 : 0;
const endSmer = pis == "rook" ? 4 : 8;

for (let smer = startSmer; smer < endSmer; smer++) {
for (let n = 1; n <= pocetKeStrane[index][smer]; n++) {

const target = index + smery[smer] * n;
const pisNaTargetu = deska[target];

if (pisNaTargetu?.barva == barva) break;

tahy.push(target);

if (pisNaTargetu && pisNaTargetu.barva != barva) break;
}
}

return tahy;
}

function tahyProKoniky(index: number, deska: Deska) {

const tahy: number[] = [];
const barva = deska[index]!.barva;

[[-1, 2], [1, 2], [-2, 1], [2, 1], [-2, -1], [2, -1], [-1, -2], [1, -2]].forEach(smery => {

const x = smery[0] > 0 ? 1 : 3;
const y = smery[1] > 0 ? 2 : 0;

// Estli je mimo board
if (pocetKeStrane[index][x] < Math.abs(smery[0]) || pocetKeStrane[index][y] < Math.abs(smery[1])) return;

const target = index + (8 * smery[1] + smery[0]);
const pis = deska[target];

// Estli už tam felí náš
if (pis?.barva == barva) return;

tahy.push(target);
});

return tahy;
}

function tahyProPawny(index: number, deska: Deska) {

const tahy: number[] = [];
const barva = deska[index]!.barva;

// Takey
if (index % 8 != 0 && deska[index - 9] && deska[index - 9]!.barva != barva)
tahy.push(index - 9);

if (index % 8 != 7 && deska[index - 7] && deska[index - 7]!.barva != barva)
tahy.push(index - 7);

// Blokáda
if (deska[index - 8])
return tahy;

tahy.push(index - 8);

// Double-advance
if (deska[index]?.netahnuta && !deska[index - 16])
tahy.push(index - 16);

// en croassant
if (deska[index - 1]?.enPassantovatelna)
tahy.push(index - 9);

if (deska[index + 1]?.enPassantovatelna)
tahy.push(index - 7);

return tahy;
}

function tahyProKrale(index: number, deska: Deska) {

const tahy: number[] = [];
const barva = deska[index]!.barva;

for (let smer = 0; smer < 8; smer++) {
const target = index + smery[smer];
if (pocetKeStrane[index][smer] != 0 && deska[target]?.barva != barva) tahy.push(target);
}

// Castling
if (jeCheck(barva, deska)) return tahy;
for (let strana = 0; strana < 2; strana++) {

const offset = (barva == "bila" ? (strana ? 3 : -4) : (strana ? 4 : -3));
const rook = deska[index + offset];

if (deska[index]!.netahnuta && rook?.typ == "rook" && rook.netahnuta) {
let muze = true;
for (let i = (strana > 0 ? 1 : -1); (strana > 0 ? i < offset : i > offset); strana > 0 ? i++ : i--) {
if (deska[index + i]) {
muze = false;
break;
}

const novaDeska = [...deska];
novaDeska[index + i] = deska[index];
novaDeska[index] = undefined;
if (jeCheck(barva, novaDeska))
muze = false;
}

if (muze) tahy.push(index + (2 * (offset > 0 ? 1 : -1)));
}
}

return tahy;
}

function legalniTahy(index: number, deska: Deska) {

let tahy: number[];
const pis = deska[index]!;

if (pis.typ == "queen" || pis.typ == "bishop" || pis.typ == "rook")
tahy = tahyProJezdiciPisi(index, pis.typ, deska);

else if (pis.typ == "knight")
tahy = tahyProKoniky(index, deska);

else if (pis.typ == "pawn")
tahy = tahyProPawny(index, deska);

else
tahy = tahyProKrale(index, deska);


// Otestovat jestli jsou fakt legální
for (let i = 0; i < tahy.length; i++) {
const tah = tahy[i];

if (jeCheck(pis.barva, udelejTah(index, tah, deska))) {
tahy.splice(i, 1);
i--;
}
}

return tahy;
}

function udelejTah(z: number, kam: number, deska: Deska, fakt?: true) {

const mojeDeska = [...deska];
const pis = mojeDeska[z]!;

if (fakt) pis.netahnuta = false;

mojeDeska[kam] = pis;
mojeDeska[z] = undefined;

// croassant
if (pis.typ == "pawn" && mojeDeska[kam + 8]?.enPassantovatelna)
mojeDeska[kam + 8] = undefined;

if (fakt)
mojeDeska.forEach(pole => {
if (!pole) return;

pole.enPassantovatelna = false;
});

if (fakt && pis.typ == "pawn" && z - kam == 16) pis.enPassantovatelna = true;


// Castling
const rozdil = z - kam;
if (pis.typ == "king" && Math.abs(rozdil) == 2) {
const i = (rozdil > 0 ? 56 : 63);
mojeDeska[(rozdil > 0 ? kam + 1 : kam - 1)] = mojeDeska[i];
mojeDeska[i] = undefined;
}

return mojeDeska;
}

function renderHra(hra: Hra, konec?: true) {
const deska = [...hra.deska];
const vybranejPis = hra.vybranejPis;

const embed: APIEmbed = {
fields: [
{
name: "Sachy sou",
value: "",
inline: true
},
{
name: "gamesa vole",
value: "",
inline: true
}
]
};
zbyvaj
2023-11-19 13:24:28

hra.tahy = [];

if (typeof vybranejPis == "number") hra.tahy = legalniTahy(vybranejPis, deska);

for (let i = 0; i < 64; i++) {
const figurka = deska[i];
const klikanec = klikance[i];

const prvniDuhy = (i % 8) < 4 ? 0 : 1;
const field = embed.fields![prvniDuhy];

const cernyPozadi = (Math.floor(i / 8) + (i % 8)) % 2;

if (!figurka) {

field.value += hra.tahy.includes(i)
? (cernyPozadi ? `[<:h:1066376051422404628>](http://šach.ml/${klikanec})` : `[<:h:1066376343807336488>](http://šach.ml/${klikanec})`)
: (cernyPozadi ? "🟩" : "⬜");

} else {

let klic = (cernyPozadi ? "g" : "w") + (figurka.barva == "bila" ? "w" : "b") + figurka.typ;
if (hra.tahy.includes(i)) klic += "t";
if (figurka.typ == "king" && figurka.barva == hra.hraje && jeCheck(figurka.barva, deska)) klic += "c";
const emout = fokinLookupTable[klic];
const figurkaStr = `<:h:${emout}>`;

if (!konec && figurka.barva == hra.hraje || hra.tahy.includes(i)) {
field.value += `[${figurkaStr}](http://šach.ml/${klikanec})`;
} else {
field.value += figurkaStr;
}

}

if (i % 8 == 3 || i % 8 == 7) field.value += "\n";

}

return embed;

}

function konec(mes: Message, hra: Hra, duvod: string) {
mes.edit({ content: `hra zkoncila ${duvod}`, embeds: [renderHra(hra, true)] });

delete hraci[hra.bila];
delete hraci[hra.cerna];
delete hry[mes.channelId];
}

function prekreslitHru(hra: Hra) {
const mes = hra.message;

// Checkmate
if (jeCheck(hra.hraje, hra.deska)) {
let mat = true;

hra.deska.forEach((pole, i) => {
if (!pole || pole.barva != hra.hraje) return;

if (legalniTahy(i, hra.deska).length != 0) mat = false;
});

if (mat)
return konec(mes, hra, `${hra.hraje} je zasachmatovana`);

}

// Stalemate
let pat = true;
hra.deska.forEach((pole, i) => {
if (!pole || pole.barva != hra.hraje) return;

if (legalniTahy(i, hra.deska).length != 0) pat = false;
});

if (pat)
return konec(mes, hra, `achylova sytuace`);

mes.edit({ content: "", embeds: [renderHra(hra)] });
}

emiter.on("tah", (hrac, policko, respond, promo) => {
const channelId = hraci[hrac];
if (!channelId) return respond("Však vůbec nehraješ ty magore");

const hra = hry[channelId];
const barva = hra.bila == hrac ? "bila" : "cerna";
if (hra.hraje != barva) return respond("Teď nehraješ ty ty magore");

const index = klikance.findIndex(e => e == policko);

if (typeof index != "number") return respond("Co to meleš za hovna?");

// Kliknul na stejnej pis
if (hra.vybranejPis == index) {

hra.vybranejPis = undefined;

prekreslitHru(hra);
return respond();
}

// Kliknul nějakej pis
const pis = hra.deska[index];
if (pis && pis.barva == barva) {

hra.vybranejPis = index;

prekreslitHru(hra);
return respond();
}

// Táhnul
if (typeof hra.vybranejPis == "number" && hra.tahy.includes(index)) {

// Promotuje
if (hra.deska[hra.vybranejPis!]?.typ == "pawn" && index < 8) {
if (!promo) return respond("--promote--");

const promoNa = promo == "q" ? "queen" :
promo == "r" ? "rook" :
promo == "n" ? "knight" :
promo == "b" ? "bishop" : undefined;

if (!promoNa) return respond("Co to meleš za hovna?");

hra.deska[hra.vybranejPis] = mkPis(barva, promoNa);
}

hra.deska = udelejTah(hra.vybranejPis, index, hra.deska, true);

hra.vybranejPis = undefined;

hra.hraje = barva == "bila" ? "cerna" : "bila";

hra.deska = hra.deska.reduce<Deska>((acc, item) => [item].concat(acc), []);

prekreslitHru(hra);
return respond();
}

respond("cos to tam zandal");
});

const exp: Modul = {
more_komandy: {

sachy: {
DMUnsafe: true,
run: async mes => {

if (hry[mes.channelId]) return "nejze tady se us hraej";

const druhej = mes.mentions.members?.first()?.id;
if (!druhej) return "no sam asi hrat nebudez vet";

for (const player of [mes.author.id, druhej]) {
if (hraci[player]) return "zakaz symultanki";
}

const message = await mes.channel.send("hraj zopiciva");

const hra = createGame(mes.channelId, mes.author.id, druhej, message);
hraci[mes.author.id] = mes.channelId;
hraci[druhej] = mes.channelId;

message.edit({ content: "", embeds: [renderHra(hra)] });

}
},

jasevzdavam: mes => {

if (!hraci[mes.author.id]) return "vsak nehrajes magore";

const hra = hry[mes.channelId];
if (!hra) return "tadi nehrajes";

konec(hra.message, hra, `${mes.author} je pusi`);
}

}
};

module.exports = exp;

type Hra = {
bila: string;
cerna: string;
deska: Deska;
hraje: "bila" | "cerna";
tahy: number[];
vybranejPis?: number;
message: Message;
};

type Deska = (Figurka | undefined)[];

type Figurka = {
barva: "bila" | "cerna";
typ: "pawn" | "rook" | "knight" | "bishop" | "queen" | "king";
netahnuta: boolean;
enPassantovatelna: boolean;
};
zbyvaj
2023-11-19 13:24:55
// Modul dedikovaný funkci spinkáček

import { ChannelType, Message, Role, TextBasedChannel, User } from "discord.js";
import fetch from "node-fetch";
import { emouty } from "../utils/emotes";
import { Modul, Spinkackar, SRecord } from "../utils/types";
import { formatCas, formatter, log, oddiakritikovat, ping, sendDM } from "../utils/utils";

let spinkacky: SRecord<Spinkackar>;
const budouciSpinky: SRecord<NodeJS.Timeout> = {};
const autoSpinky: SRecord<[boolean, TextBasedChannel]> = {};

const contactSpinkServer = async (akce: string, id: string, nick: string = "", avatar: string | null = "") => {
const options = `heslo=${process.env.spinkPass}&akce=${akce}&id=${id}&nick=${encodeURIComponent(nick)}&avatar=${encodeURIComponent(avatar ?? "")}`;
return fetch(`https://spinkacek.deadfish.cz/extapi.php?${options}`)
.then(r => r.text());
};

const syncSpink = () => {
fetch("https://spinkacek.deadfish.cz/api/spinkacky";)
.then(r => r.json() as Promise<{ spinkacky: SRecord<Spinkackar>; }>)
.then(d => {
const data = d.spinkacky;
const keys = Object.keys(data);
const values = Object.values(data);
spinkacky = {};

for (let i = 0; i < keys.length; i++) {
const k = keys[i];
if (k[0] != "d") continue;
const vstav = values[i].timeup;
spinkacky[k.slice(8)] = { spinkacek: values[i].spinkacek, timeup: vstav === false ? false : vstav * 1000 };
}
});
};

if (!process.env.ignoreSpink)
syncSpink();

const handleSpink = async (act: "spinkacek" | "vstavacek", user: User) => {
const ok = act == "spinkacek"
? await contactSpinkServer(act, user.id, user.username, user.avatarURL())
: await contactSpinkServer(act, user.id);
return ok.startsWith("OK") ? ok : false;
};

const ifUzRemove = (m: Message) => {
const id = m.author.id;
const uzPgn = budouciSpinky[id];
if (uzPgn) {
clearTimeout(uzPgn);
delete budouciSpinky[id];
return true;
}
return false;
};

const tovjemamvolepreceroliky = async (roliky: User, rictCas?: boolean) => {
const odpoved = await handleSpink("vstavacek", roliky);
if (!odpoved) return "uz jsi vzhuru ty hajzle";
const cas = Number(odpoved.slice(3));
const formatedCas = formatCas(cas);

const zacatek = `dobry rano hajzle ${roliky}`;
if (!rictCas) return zacatek;

let zpr = "";
if (cas >= 57600) zpr = "mas dat more vstavacek uz kdyz vstanes retarde";
else if (cas >= 43200) zpr = "extrémní bídák";
else if (cas >= 36000) zpr = "fakt bídák";
else if (cas < 30) zpr = "dobrej mikrospánek debile";
else if (cas < 10800) zpr = "dobrej fake spink debile";

return `${zacatek}\nspal sy ${formatedCas}\n${zpr}`;
};

function hmsToCislo(reg: RegExpExecArray | null) {
if (!reg || reg.input == "") return NaN;
const g = reg.groups!;
return (Number(g.h) * 3600 || 0) + (Number(g.m) * 60 || 0) + (Number(g.s) || 0);
}

const exp: Modul = {
more_komandy: {

spinkacek: {
als: ["spink", "spoink", "spinkake", "spoinkacek", "gn", emouty.spinkacek, emouty.gn],
run: async mes => {
if (mes.author.bot) return `až někdy${emouty.kapp}`;
if (await handleSpink("spinkacek", mes.author)) {
mes.react(emouty.spinkacek);
ifUzRemove(mes);
}
else return 'nespis uz?????';
}
},

vstavacek: {
als: ["vstavcacek", "gm", "unspinkacek"],
run: async (mes, arg) => {
if (mes.author.bot) return emouty.sjeta;

return tovjemamvolepreceroliky(mes.author, arg.toLowerCase() != "fejk");
}
},

pgn: {
als: [`p${emouty.gn}`],
run: (mes, kdy) => {
if (mes.author.bot) return emouty.sjeta;

const ted = new Date();
const tedT = Number(ted);
const spink = new Date();
let random = false;

if (kdy.startsWith("random")) {
random = true;
let rozdil = 540;
let min = 60;
if (kdy.length > 7) {
const t = kdy.slice(7).replace(/ /g, "").split("-");
if (t.length != 2) return "cos to napsal kkte";
const regex = /^(?:(?<h>\d+)h)?(?:(?<m>\d+)m)?(?:(?<s>\d+)s?)?$/;
const [from, to] = [regex.exec(t[0]), regex.exec(t[1])].map(v => hmsToCislo(v));
if (Number.isNaN(from) || Number.isNaN(to)) return "cislo musy bit v formate xh xm xs";
if (to <= from) return "ja teda nevim jestli ti vys jak funguje cas ael vym ze tam mas chibu";

rozdil = to - from;
min = from;
}
spink.setTime(tedT + (Math.random() * rozdil + min) * 1000);
log(`random spink pro ${oddiakritikovat(mes.member?.displayName || "neznamejmeno")} byl nastaven na ${formatter(spink)}`);
} else if (/^\d+$/.test(kdy) || !kdy)
spink.setTime(tedT + Number(kdy || 7200) * 1000);
else {
const cojavim = /^((?<d>\d+)\. ?((?<mo>\d+)\.)? ?)?(?<h>\d+)(:(?<m>\d+)(:(?<s>\d+))?)? ?(?<p>am|pm)?$/.exec(kdy.toLowerCase());
if (!cojavim) return `cos to tam napsal ty kokote?`;

const g = cojavim.groups!;
if (g.d) spink.setDate(Number(g.d));
if (g.mo) spink.setMonth(Number(g.mo) - 1);
const h = Number(g.h);
spink.setHours(g.p == "pm" && h < 12 ? h + 12 : h);
spink.setMinutes(Number(g.m) || 0);
spink.setSeconds(Number(g.s) || 0);
if (Number(spink) < tedT) spink.setDate(ted.getDate() + 1);
}

ifUzRemove(mes);

budouciSpinky[mes.author.id] = setTimeout(() => {
handleSpink("spinkacek", mes.author);
mes.react(emouty.spinkacek);
}, Number(spink) - tedT);
if (!random) return `tvuj spinkacek byl naplanovan na ${formatter(spink)}`;
mes.react(emouty.lajk);
}
},

ps: {
als: ["poslednispink"],
arg: "kdo (nepovinné)",
run: (mes, arg) => {
const f = arg != "";
if (!ping.test(arg) && f) return "sikkt";
const id = f ? mes.mentions.members?.first()?.id : mes.author.id;
const tajmUp = spinkacky[id ?? ""]?.timeup;
if (tajmUp == undefined) return `tuten kkt jeste nespal ${emouty.lukiw}`;
if (!tajmUp) return "ten kkt jiz ickon spi";
const cas = Number(new Date()) - Number(new Date(tajmUp));
return `uz ${f ? "je" : "jsi"} vzhuru ${formatCas(cas / 1000)}`;
}
},

zruspgn: {
als: ["zpgn", "cancelpgn", "cpgn", "unpgn", `unp${emouty.gn}`],
run: mes => {
if (!ifUzRemove(mes)) return `spinkacek ale nemas naplanovanej ty kkte ${mes.author}`;
return "to bylo teda trapny debile";
}
},

autospink: mes =>
`autospink je ${autoSpinky[mes.author.id] ? (delete autoSpinky[mes.author.id], "vypnut") : (autoSpinky[mes.author.id] = [true, mes.channel], "zapnut")}`,

autoautospink: {
als: ["🚗🚗spink"],
run: mes =>
`autoautospink je ${autoSpinky[mes.author.id] ? (delete autoSpinky[mes.author.id], "vypnut") : (autoSpinky[mes.author.id] = [false, mes.channel], "zapnut")}`
}
},

on_voiceStateUpdate: (bef, aft) => {
if (!aft.channel || bef.channel) return;
if (spinkacky[aft.id]?.spinkacek) aft.disconnect("spinkacek")
.catch(err => log("spinkacek odpojit se nepovedlo nebo co:", err));
},

super_on_messageCreate: (mes, cmd?: string) => {
if (mes.author.id === '831318260493844494') {
syncSpink();
const uzivatel = mes.content.match(/(?<=discord_)\d+/)?.[0];
if (!uzivatel) return false;
for (const [, guild] of mes.client.guilds.cache) {
const member = guild.members.cache.get(uzivatel);
if (!member) continue;

const c = guild.roles.cache;
const spinkRole = c.find(r => r.name == "spink");
const adminRole = c.find(r => r.name == "admin");

const make = (akce: "a" | "r", role: Role) => {
const handle = (e: Error) => {
if (["Missing Permissions", "Missing Access"].includes(e.message)) return;
log("chyba pri davani/odebirani role", e);
};
if (akce == "a") member.roles.add(role).catch(handle);
else member.roles.remove(role).catch(handle);
};

if (mes.content[0] == "s") {
if (spinkRole) make("a", spinkRole);
if (adminRole) make("r", adminRole);
} else {
if (spinkRole) make("r", spinkRole);
if (adminRole) make("a", adminRole);
continue;
}
for (const [, channel] of guild.channels.cache) {
if (channel.type != ChannelType.GuildVoice) continue;
for (const [, member] of channel.members) {
if (member.id !== uzivatel) continue;
member.voice.disconnect("spinkacek");
return false;
}
}
}
} else if (spinkacky[mes.author.id]?.spinkacek && cmd != "vstavacek") {
if (mes.channel.type == ChannelType.DM) {
mes.channel.send("drz hubu");
return true;
}

mes.delete().catch((e: Error) => {
if (e.name == "DiscordAPIError[5OO13]") return;
log("chyba pri mazani", e);
});
sendDM(mes.author, "spis tak nepis");
return true;
}

return false;
},

// autoSpink handeler
on_userPresenceUpdate: async (bef, aft) => {
if (!bef) return;
const befoff = bef.status == "offline";
const aftoff = aft.status == "offline";
const prop = autoSpinky[aft.userId];
if (!prop) return;
if (!befoff && aftoff) {
handleSpink("spinkacek", aft.member!.user);
}
if (befoff && !aftoff) {
if (prop[0]) delete autoSpinky[aft.userId];
const kanel = prop[1];
if (kanel?.type == ChannelType.GuildText) kanel.send(await tovjemamvolepreceroliky(aft.member!.user));
}
}
};

if (!process.env.ignoreSpink)
module.exports = exp;
zbyvaj
2023-11-19 13:25:04
// Trekování statusů všech lidí o kterých bot ví
import { Client, Guild, Presence } from "discord.js";
import fetch from "node-fetch";
import { FakePresence, Modul, SRecord, StatusyINaFounu, UserChange, ZmenovejObjekt } from "../utils/types";
import { adminLog, log } from "../utils/utils";

const statusy = { Offline: "0", Online: "1", Idle: "2", DND: "3", OnlinePhone: "11", IdlePhone: "12", DNDPhone: "13" };
const prepSend = (zmeny: UserChange[]) => {
const changes: ZmenovejObjekt[] = [];

zmeny.forEach(zmena => {
const us = zmena.user;
const objekt: ZmenovejObjekt = { id: us.id };
if (zmena.ch === "user" || !zmena.ch) {
objekt.nick = us.username;
objekt.pfp = us.avatar ?? "";
}
if (zmena.ch === "stat" || !zmena.ch) {
objekt.status = zmena.stat;
}
changes.push(objekt);
});

poslatData({ changes });
};

const poslatData = (data: SRecord<unknown>) => {
data.pwd = process.env.statPass;
fetch("http://deadfish.cz:4629/endpoint-pro-denimka/";, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
.catch(err => {
log("err:", err);
const client: Client<boolean> = module.exports.client;
adminLog(client, "stat nejede");
});
};

const ziju = () => {
poslatData({ nejsemPoslej: !0 });
setTimeout(ziju, 60_000);
};

if (!process.env.ignorePresence) ziju();

const getRole = (status: StatusyINaFounu, server: Guild) =>
server.roles.cache.find(role => role.name === `Status${status}`);

function statusOnFoun(bef: FakePresence | null, aft: FakePresence) {
const role = { online: "Online", idle: "Idle", dnd: "DND", offline: "Offline" };

if (!bef) bef = { status: 'offline', clientStatus: {} };
const predAPo: StatusyINaFounu[] = [];

[bef, aft].forEach((s, i) => {
const mobile = s.clientStatus?.mobile;
const deskotopy = s.clientStatus?.web
? s.clientStatus.desktop == "online" ? s.clientStatus.desktop : s.clientStatus.web
: s.clientStatus?.desktop;

if (mobile && mobile != deskotopy && (!deskotopy || deskotopy == "idle")) {
predAPo[i] = `${role[mobile]}Phone` as StatusyINaFounu;
} else {
predAPo[i] = role[s.status] as StatusyINaFounu;
}
});

return predAPo;
}


const exp: Modul = {

// Změna rolí podle statusu a odeslání statusu
on_presenceUpdate: (bef, aft) => {
if (process.env.ignorePresence) return;

const [statusPred, statusPo] = statusOnFoun(bef as FakePresence, aft as FakePresence);
if (statusPred === statusPo) return;
const rolePred = getRole(statusPred, aft.guild!);
const rolePo = getRole(statusPo, aft.guild!);


if (rolePred) aft.member!.roles.remove(rolePred);
if (rolePo) aft.member!.roles.add(rolePo);

prepSend([{ ch: "stat", user: aft.user!, stat: statusy[statusPo] }]);
},

// Odeslání statusů při startu bota
on_ready: () => {
if (process.env.ignorePresence) return;

const client: Client = module.exports.client;
const guildy = client.guilds.cache;
const userove = client.users.cache.clone();
const presence: Presence[] = [];
const changes: UserChange[] = [];

guildy.each(guilda => {
guilda.presences.cache.each(pres => {
if (!presence.filter(prs => prs.userId === pres.userId).length) presence.push(pres);
});
});

presence.forEach(presenc => {
const status = statusOnFoun(null, presenc as FakePresence)[1];
changes.push({ user: userove.get(presenc.userId)!, stat: statusy[status] });
userove.delete(presenc.userId);
});

userove.each(member => {
changes.push({ user: member, stat: "0" });
});

prepSend(changes);
},

// Odeslání statusu při změně jména nebo profilovky
on_userUpdate: (bef, aft) => {
if (!process.env.ignorePresence && bef.id != aft.client.user?.id)
prepSend([{ ch: "user", user: aft }]);
}
};

module.exports = exp;
kiwaki
2023-11-19 13:25:15
dyk ejh mor
zbyvaj
2023-11-19 13:25:16
// Cokoliv co má něco společnýho s vojsem

import { getVoiceConnection } from "@discordjs/voice";
import { ChannelType, GuildMember, Message, VoiceChannel } from "discord.js";
import { emouty } from "../utils/emotes";
import { CClient, Modul } from "../utils/types";
import { log, rand } from "../utils/utils";
import { handlePrevVoice, Hratelny, novejJoin, novejLeave, novejPlay, Priority } from "../utils/voice";

const muty: string[] = [];
let neodposlouchavani = false;

const vytahnout = (member: GuildMember, patro: number) => {
const vojs = member.voice.channel;
if (!vojs) return;

const aktPatro = Number(vojs.name) || 0;
let dalsiPatro: number | string = aktPatro;
if (patro < aktPatro) dalsiPatro--; else if (patro > aktPatro) dalsiPatro++; else return;
if (dalsiPatro === 0) dalsiPatro = "P";

const dalsiVojs = member.guild.channels.cache.filter(channel => channel.type == ChannelType.GuildVoice && channel.name === String(dalsiPatro)).first() as VoiceChannel | undefined;
if (!dalsiVojs) return;

member.voice.setChannel(dalsiVojs);
setTimeout(() => vytahnout(member, patro), 1e3);
};

async function playAndFukOff(mes: Message, jinak: string, zvuk: string | Hratelny[]) {
const channel = mes.member?.voice.channel;
if (!channel) return jinak;

const prev = await novejJoin(mes.guild!, channel.id);

await novejPlay(mes.guildId!, zvuk, Priority.Etc)
.catch(e => {
log("Pičo chyba při fukofování", e);
});

handlePrevVoice(prev, mes.guild!);
}

const exp: Modul = {
more_komandy: {

wojs: mes => `vojs se pise s normalnim v ti kriple ${mes.author}`,

vojs: {
arg: "potichu (nepovinné)",
DMUnsafe: true,
run: (mes, arg) => {
const channel = mes.member?.voice.channel;
if (!channel) return `di si tam sam ne ty gadzo ${mes.author}`;

const nahlas = !arg.startsWith("potichu");
if (nahlas) mes.channel.send("<@&591306633196339261> vojs");

novejJoin(mes.guild!, channel.id)
.then(prev => {
if (prev != true && nahlas) novejPlay(mes.guildId!, "zvuky/nazdar.ogg", Priority.Etc);
});
}
},

vypadni: {
als: ["odejdi", "disconnect", "leave", "odpoj", "votpoj", "vodpoj", "vodprejskni", "tahni"],
DMUnsafe: true,
run: mes => {
if (!novejLeave(mes.guildId!)) return "nejsem ve vojsu";
mes.react(emouty.purfieRIP);
}
},

vytah: {
als: ["vitah"],
DMUnsafe: true,
run: (mes, parto) => {
if (!mes.member?.voice.channel) return `nejsi ve vojsu ty gadzo ${mes.author}`;
if (!parto) return `napis do jakiho patra ${mes.author}`;

vytahnout(mes.member, Number(parto) || 0);
}
},

krkacek: {
als: ["krk", "grg", "grgnisi", "krknisi", "grgacek"],
run: mes =>
playAndFukOff(mes, "***grrrrrrrrg***", "zvuky/grg.mp3")

},

cas: {
cd: 5,
run: async mes => {
const date = new Date();
const h = date.getHours();
const m = date.getMinutes();
const pre = "zvuky/cas/";

const addSuffix = (prefix: string, hodnota: number) => {
const koncovka = hodnota == 1 ? "a" : hodnota > 1 && hodnota < 5 ? "y" : "";
return `${prefix}${koncovka}`;
};
const rozdelAPridej = (cislo: number) => {
if (cislo == 2) return zvuky.push({ src: `${pre}dvě.mp3`, volume: 2.5 });
if (cislo < 20) return zvuky.push({ src: `${pre}${cislo}.mp3`, volume: 2.5 });
const text = String(cislo);
zvuky.push({ src: `${pre}${text[0]}0.mp3`, volume: 2.5 });
if (text[1] != "0") zvuky.push({ src: `${pre}${text[1]}.mp3`, volume: 2.5 });
};

const hod = addSuffix("hodin", h);
const min = addSuffix("minut", m);
const je = h > 1 && h < 5 ? "jsou" : "je";

const channel = mes.member?.voice.channel;
if (!channel) return;

const zvuky: Hratelny[] = [{ src: `${pre}${je}.mp3`, volume: 2.5 }];

rozdelAPridej(h);
zvuky.push({ src: `${pre}${hod}.mp3`, volume: 2.5 });
if (m > 0) {
rozdelAPridej(m);
zvuky.push({ src: `${pre}${min}.mp3`, volume: 2.5 });
}

playAndFukOff(mes, `${je} ${h} ${hod} ${m} ${min}`, zvuky);
}
},

outro: {
hidden: true,
run: mes =>
playAndFukOff(mes, "co to znamena ti gadzovko", "zvuky/pocasi/outro.mp3")

},

auto: mes =>
playAndFukOff(mes, "vžum", "zvuky/auto.ogg"),

reknivtip: mes => {
const zvuk = ["a_jednou_sel_a_tak_moc_sel", "a_sedel", "a_sel_z_vaku_a_vykopal_marese", "a_si_rekl", "a_si_vsimnul", "u_zamestnaly_na_praxi"][rand(7)];
const client: CClient = module.exports.client;
return playAndFukOff(mes, (client.komandy["vtip"].run as (() => string))(), `zvuky/ftipy/toz_sims${zvuk}.mp3`);
},

zmenneodposlouchavani: () => {
neodposlouchavani = !neodposlouchavani;
return `Funkce NEOTPOSLOUCHAAVEJJJ!!§!§ je ${neodposlouchavani ? "nastartovana" : "chcipnuta"}`;
}

},

// Neodposlouchávej
on_voiceStateUpdate: (bef, aft) => {
const conn = getVoiceConnection(aft.guild.id);
if (!aft.channel || !conn || aft.member?.user.id == aft.client.user?.id) return;

if (neodposlouchavani && aft.selfMute && !aft.deaf) {
novejPlay(aft.channel.guildId, { src: "./zvuky/neodposlouchavej.ogg", volume: 0.38 }, Priority.Etc)
.then(() => {
if (!aft.selfMute) return;
aft.setDeaf(true, "otposlouchávala ta gadza");
if (!muty.includes(aft.member!.id)) muty.push(aft.member!.id);
})
.catch(e => {
log("chyb při neodposlouchavej", e);
});
}

if (!bef.channel) return;
if (bef.mute && bef.deaf && !aft.mute && aft.serverDeaf && muty.includes(aft.member!.id)) {
aft.setDeaf(false, "us muze poslouchat gadza");
muty.splice(muty.indexOf(aft.member!.id), 1);
}
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:25:27
import { GuildScheduledEventEntityType, GuildScheduledEventPrivacyLevel, TextChannel } from "discord.js";
import fetch from "node-fetch";
import { CClient, Modul } from "../utils/types";
import { log } from "../utils/utils";

let client: CClient;

async function ziskatNazev() {
const stranka = await fetch("https://voyo.nova.cz/api/v1/show/content?showId=1&type=episodes&season=5836&count=24&offset=0&url=%2Fserialy%2F1-ordinace-v-ruzove-zahrade-2";)
.then(r => r.text())
.catch(e => log("chyba pri accessovani VOYO stránky", e));

const nazevFull = /h3 class=\"title\">.+?>(.+?)<\//s.exec(stranka || "");

if (!nazevFull) {
log(new Error("neni nazev"));
return "Vordinačka";
}

const nazevCasti = /(?<cislo>\d+). díl - (?<nazev>.+)/.exec(nazevFull[1]);

return nazevCasti ? `${nazevCasti.groups!.cislo}. ${nazevCasti.groups!.nazev}` : nazevFull[1];
}

async function naplanovat() {
const datum = new Date();
const den = datum.getDay();

if (!(den == 1 && datum.getHours() < 12))
datum.setDate(datum.getDate() + ((den == 0 ? 1 : 8) - den));

datum.setHours(13);
datum.setMinutes(0);
datum.setSeconds(0);

setTimeout(urobit, Number(datum) - Number(new Date()));
}

async function urobit() {
const guilda = client.guilds.cache.get("555779161067749446");

if (!guilda) return log(new Error("dobytcarna nenalezena"));

const kdyToBude = new Date();
kdyToBude.setHours(20);
kdyToBude.setSeconds(0);

const event = await guilda.scheduledEvents.create({
name: await ziskatNazev(),
scheduledStartTime: kdyToBude,
entityType: GuildScheduledEventEntityType.Voice,
privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly,
channel: "891067481651839037"
});

const general = guilda.channels.cache.get("555779161067749448") as TextChannel;

if (!general) return log(new Error("general nenalezen"));

general.send(`<@&1123186280843444274> ${event.url}`);
}

const exp: Modul = {
more_komandy: {
dalsiordinacka: () => `dalsi ordnacka <t:${Math.ceil((Date.now() - 410400000) / 604800000) * 604800 + 410400}:R>`
},

on_ready: () => {
client = module.exports.client;

naplanovat();
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:25:37
/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/

import { APIEmbed, CommandInteractionOption, Message, TextBasedChannel } from "discord.js";
import { CClient, Modul } from "../utils/types";
import { createPool } from "mysql";
import { log, strankovani } from "../utils/utils";

// Připojení do databáze
const pool = createPool({
host: "127.0.0.1",
user: process.env.DBUser,
password: process.env.DBPwd,
database: "zalohaGeneralu",
charset: "utf8mb4_unicode_ci"
});

const zpracovatZpravu = (mes: Message) => new Promise<void>(async (res, rej) => {
if ([6, 7, 8, 9, 10, 11, 18, 23].includes(mes.type)) return res();
if (mes.type != 0 && mes.type != 20 && mes.type != 19) throw new Error("Neznámej message type " + mes.type.toString());

const reference = mes.reference?.messageId;
const attachments: { name: string; file: string; }[] = [];

if (mes.attachments.size != 0) {

for (const [, attachment] of mes.attachments) {
attachments.push({ name: attachment.name, file: attachment.id });
}
}

const sql = `INSERT INTO Zpravy (ID, Content, Author ${reference ? ", Reference" : ""} , Attachments) VALUES (${mes.id}, ?, ${mes.author.id} ${reference ? `,${reference}` : ""} , ?)`;

pool.query({ sql, values: [mes.content, JSON.stringify(attachments)] }, err => {
if (err) rej(err);
res();
});
});

const porovnat = (filtr: CommandInteractionOption): string[] => {
switch (filtr.name) {
case "kontent": return [`Content LIKE ?`, `%${filtr.value}%`];
case "regex": return [`Content REGEXP ?`, `${filtr.value}`];
case "uzivatel": return [`Author=?`, `${filtr.user!.id}`];
case "od":
case "do": {
const datum = new Date(filtr.value as string);
const cislo = (Number(datum) - 1420070400000) * 4194304;
return [`ID ${filtr.name == "od" ? ">" : "<"} ${cislo}`];
}
case "obrasek": return [`${filtr.value ? "" : " NOT "}Attachments REGEXP "\.(png|jpe?g|gif|webp)"`];
case "obrazekOdkaz": return [`${filtr.value ? "" : " NOT "}Content REGEXP "\.(png|jpe?g|gif|webp)"`];
case "link": return [`${filtr.value ? "" : " NOT "}Content REGEXP "https?://"`];
case "ma_soubor": return [`${filtr.value ? "" : " NOT "}Attachments != "[]"`];
case "nazev_souboru": return [`Attachments LIKE ?`, `%${filtr.value}%`];
}
return [""];
};

const exp: Modul = {
more_komandy: {
vyhledej: {
run: () => {
const client: CClient = module.exports.client;

return `tuto je novej komand a histmaj mrdal aby to slo i takhle proste pouzij </morevyhledej:${client.slashCommandy["morevyhledej"]}>`;
},

slashRun: async int => {
const moznosti = int.options;
const filtry = moznosti.data;
if (!filtry.length) return "co takhle tam alespon jeden filtr";

// Nelgel kombinace a tak
if (moznosti.get("kontent") && moznosti.get("regex")) return "kontent a regex nejde kombynovat";
const od = moznosti.get("od");
if (od && isNaN(Number(new Date(od.value as string)))) return "od neny platni datum";
const dod = moznosti.get("do");
if (dod && isNaN(Number(new Date(dod.value as string)))) return "do neny platni datum";

const parsedFiltry: string[] = [];
const mista: string[] = [];
let seradit = "DESC";

for (const filtr of filtry) {
if (filtr.name != "seradit") {
const [parsed, misto] = porovnat(filtr);
parsedFiltry.push(parsed);
if (misto) mista.push(misto);
} else {
seradit = filtr.value as string;
}
}

const odpoved = await int.reply("hledam");

const sql = `SELECT CONVERT(ID, CHAR) as idcko, SUBSTRING(Content, 1, 20) AS kontent FROM Zpravy WHERE ${parsedFiltry.join(" AND ")} ORDER BY ID ${seradit}`;
pool.query({ sql, values: mista }, (err, res?: { idcko: string; kontent: string; }[]) => {
if (err) return odpoved.edit(`chyba: ${err}`);

if (!res || !res.length) return odpoved.edit("nic takoviho sem nenasel");

odpoved.edit("nasel sem tuto:");

let celkovadylka = 0;
const stranky: string[][] = [[]];
let aktualniStranka = 0;
for (const row of res) {
const vlozka = `[${row.kontent}] https://discord.com/channels/555779161067749446/555779161067749448/${row.idcko}`;

const dylka = vlozka.length + 3;
celkovadylka += dylka;
if (celkovadylka > 1024 || stranky[aktualniStranka].length == 20) {
aktualniStranka++;
celkovadylka = dylka;
}

const stranka = stranky[aktualniStranka] ??= [];

stranka.push(vlozka);
}

const zacatekNazvu = "visltki";
const embed: APIEmbed = {
color: Math.random() * 16777215,
fields: [{ name: zacatekNazvu, value: `• ${stranky[0].join("\n• ")}` }]
};

if (stranky.length == 1) return int.channel?.send({ embeds: [embed] });

embed.fields![0].name += ` (1/${stranky.length})`;

strankovani(int.channel!, embed, zacatekNazvu, stranky);
});
}
}
},

on_ready: () => {
const client = module.exports.client as CClient;

client.channels.fetch("555779161067749448")
.then(async ch => {
const channel = ch as TextBasedChannel;
let posledni: string | undefined;

while (true) {
const msgs = await (channel.messages.fetch(posledni ? { before: posledni } : undefined));

for (const [, mes] of msgs) {

try {
await zpracovatZpravu(mes);
} catch {
log("general sync kompletni");
return;
}
}

posledni = msgs.last()!.id;

// Radši
await new Promise(res => setTimeout(res, 500));
}

});
},

on_messageCreate: mes => {
if (mes.channelId == "555779161067749448")
zpracovatZpravu(mes);
}
};

module.exports = exp;
zbyvaj
2023-11-19 13:25:45
import { getVoiceConnections } from "@discordjs/voice";
import { emouty } from "../utils/emotes";
import { Modul } from "../utils/types";
import { prefix } from "../utils/utils";
import { novejLeave } from "../utils/voice";

let spim = false;

const exp: Modul = {
super_on_messageCreate: {
pos: 0,
fun: mes => {
const cont = mes.content.toLowerCase();
if (cont == `${prefix} zapni se`) {
if (spim) {
spim = false;
mes.client.user?.setStatus("online");
mes.channel.send("dobré ráno magoří");
}
else mes.channel.send("tak jsi kokot?");
} else if (!spim) {
if (cont == `${prefix} vypni se`) {
mes.react(emouty.purfieRIP);
getVoiceConnections().forEach(con => novejLeave(con.joinConfig.guildId));
mes.client.user?.setStatus("invisible");
spim = true;
}
else return false;
}
return true;
}
},
};

module.exports = exp;
kiwaki
2023-11-19 13:25:51
milujem ťa nadovšetko
zbyvaj
2023-11-19 13:25:54
// Komandy nebo handelery který se nikam jinam nehodí

import { getVoiceConnections } from "@discordjs/voice";
import { Client, TextChannel, } from "discord.js";
import { createServer } from "http";
import { Modul } from "../utils/types";
import fetch from "node-fetch";
import { adminLog, formatCas, log, nabidni, sendDM } from "../utils/utils";
import { emouty } from "../utils/emotes";
import { readFileSync } from "fs";

const zpravy = new Map<string, Map<string, number[]>>();
const dobaOmezení = 20_000;
let client: Client;

const exp: Modul = {
more_komandy: {

debug_log: {
hidden: true,
run: (_, arg) => {
log("log:", arg);
return "je to v konzoli";
}
},

update: {
als: ["apdejt"],
run: async mes => {
const sudo = mes.channel.id == process.env.adminChannel || mes.author.id == process.env.adminID;
if (!sudo) {
const verze = await fetch("https://denim3001.deadfish.cz/version.txt";)
.then(r => r.text());
if (verze == require("../../package.json").version) return `ale ja se nemam co priucit vole kkte ${mes.author}`;
}

getVoiceConnections().forEach(con => con.destroy());
client.user?.setStatus("invisible");
mes.react("👋")
.then(() => process.exit());
}
},

restartujsetykurvozasrana: {
als: ["restart"],
run: mes => {
const sudo = mes.channel.id == process.env.adminChannel || mes.author.id == process.env.adminID;

function udelat() {
getVoiceConnections().forEach(con => con.destroy());
client.user?.setStatus("invisible");
mes.react("👋")
.then(() => process.exit(69));
}

if (!sudo) {
const souhlasatori: string[] = [mes.author.id];

nabidni({
channel: mes.channel,
nabidka: ["souhlasim"],
zpravec: { content: "jelikoz nesi hlava zpravne namazana musi se z tebou zhotnout jeste 2 hajzlaty do 60 se kund" },
onCollect: i => {
if (souhlasatori.includes(i.member!.user.id)) return i.reply({
ephemeral: true,
content: "ti us sy na to klyknul ti suraku"
});

souhlasatori.push(i.member!.user.id);

if (souhlasatori.length == 3) udelat();
else i.update({ content: "heste jeden" });
},
konecnaZprava: "restart se nekona, ste kundi so se neumy dohodnout",
timeout: 6e4,
stejne: true
});
return;
}

udelat();
}
},

lastuptime: () => {
const sekundy = Number(process.argv[3]);
if (!sekundy) return "aj forgor 💀";
return `naposled jsem jel ${formatCas(sekundy)}`;
}
},

super_on_messageCreate: {
pos: 1,
fun: mes => {
const ted = Date.now();
const autor = mes.author.id;

if (!zpravy.has(autor)) {
zpravy.set(autor, new Map());
}

const uzivatel = zpravy.get(mes.author.id)!;
const timestampy = uzivatel.get(mes.content) ?? [];

const aktualni = timestampy.filter(timestamp => ted - timestamp < dobaOmezení);
aktualni.push(ted);
uzivatel.set(mes.content, aktualni);

const pocet = aktualni.length;
if (pocet < 7) return false;

(async () => {
if (mes.author.id == client.user?.id) return mes.channel.send("uz nechci");
const adminRole = mes.member?.roles.cache.find(r => r.name == "admin");
if (adminRole) {
await mes.member?.roles.remove(adminRole).catch(e => log("nejde odebrat admin", e));
}

await mes.member?.timeout(60_000, "spamer zasranej").catch(e => log("nejde timeoutnout zmrd", e));
if (adminRole) setTimeout(() => {
mes.member?.roles.add(adminRole);
}, 60_000);
mes.channel.send(emouty.fu);
})();

return true;
}
},

on_ready: () => {
// Nastavení clienta
client = module.exports.client;

// OG onReady++
log("A jedeš!");
if (process.argv[2] == "1") {
const duvod = readFileSync("logs/recent.txt").toString();
adminLog(client, "pošel jsem", duvod);
}

// Server na navrhy
createServer((req, res) => {
res.statusCode = 400;
if (req.socket.remoteAddress != "::1") return res.end("di doprdele dyk ne more");

const sp = new URL(req.url!, `http://${req.headers.host}`).searchParams;
const { userID, content } = Object.fromEntries(sp.entries());
if (!userID || !content) return res.end("gde mas userID a content????");

const user = client.users.cache.get(userID);
if (!user) return res.end("takovyho kkta neznam");

user.createDM().then(async dm => {
await dm.send(content);
res.statusCode = 200;
res.end("OK");
}).catch((e: Error) => {
if (e.message.search("2000 or fewer")) return res.end("content je moc dlouhej");
log("error pri posilani upozorneni", e);
res.statusCode = 500;
res.end("neco se posralo");
});
}).listen(1298);

// Garbage-colector na `zpravy`
setInterval(() => {
const ted = Date.now();
zpravy.forEach((mapa, uzivatel) => {
mapa.forEach((pocet, zprava) => {
const aktualni = pocet.filter(timestamp => ted - timestamp < dobaOmezení);
if (!aktualni.length) mapa.delete(zprava);
});
if (!mapa.size) zpravy.delete(uzivatel);
});
}, 60_000);
},

on_userUpdate: (bef, aft) => {
if (bef.avatar == aft.avatar) return;

sendDM(aft, "cus bracho vydim ze sis zmenim profilofku na dalsi mrdku estli chces abi se ukazovala na na v3ech sr4kach kterz sou na dedfis.cy tak se tam prosymte prihlas haby se mohla zmnenit syk");
},

on_userPresenceUpdate: (bef, aft) => {
if (aft.user?.id != "355053867265818635" || bef?.status == "online" || aft.status != "online") return;

(client.channels.cache.get("555779161067749448") as TextChannel)
.send("https://tenor.com/view/pavel-is-online-gif-21604335";);
}
};

module.exports = exp;
kiwaki
2023-11-19 13:25:58
ty kokotko
kiwaki
2023-11-19 13:26:41
Jsi užitečný asi jako automat na kondomy ve Vatikánu
zbyvaj
2023-11-19 13:26:55
@kiwaki
kiwaki
2023-11-19 13:27:20
🍔
kiwaki
2023-11-19 13:27:30
🥙
kiwaki
2023-11-19 13:27:40
kebab :)
zbyvaj
2023-11-19 13:28:44
histmy
2023-11-24 21:26:30
nebo zkráceně takhle: https://gitea.deadfish.cz/Histmy/Denim-Bot

Přidat komentář

Tento návrh je uzavřený

:sjeta: