Files
Hotodog-Discord-Bot/src/plugins/rule34/plugin.ts
2025-04-02 16:27:10 +02:00

102 lines
2.8 KiB
TypeScript

import { assert } from "@std/assert/assert";
import { ImageResponse, postUrl, requestJSON } from "./api.ts";
import { Embed, EmbedAuthor, EmbedImage } from "@root/structures/embeds.ts";
const keys = ["limit", "id", "pid", "tags"] as const;
type PostKeys = typeof keys[number];
function isKey(key: string): key is PostKeys {
return keys.includes(key as any);
}
export async function drop() {
try {
const response = await requestJSON<ImageResponse[]>(`${postUrl}&limit=1`);
const img = response[0];
if (img === undefined) throw Error("An undefined Array was given!");
return new Embed(
`ID: ${img.id}`,
img.sample_url,
new EmbedAuthor(img.owner),
// [new EmbedField("Tags", img.tags, true)],
new EmbedImage(img.file_url, img.height, img.width),
);
} catch (e) {
console.error((e as Error).message);
return new Embed(
"Error Message",
"https://gifdb.com/images/thumbnail/nuh-uh-demon-slayer-girl-hm7q3hqa4lnqyl6d.gif",
new EmbedAuthor("fzzinChemical"),
new EmbedImage(
"https://gifdb.com/images/thumbnail/nuh-uh-demon-slayer-girl-hm7q3hqa4lnqyl6d.gif",
250,
250,
),
);
}
}
export async function requestWorker(requestString: string) {
try {
const response = await requestJSON<ImageResponse[]>(
generateRequestURL(requestString),
);
const stack: Embed[] = [];
for (const img of response) {
stack.push(
new Embed(
`ID: ${img.id}`,
img.sample_url,
new EmbedAuthor(img.owner),
// [new EmbedField("Tags", img.tags, true)],
new EmbedImage(img.file_url, img.height, img.width),
),
);
}
return stack;
} catch (e) {
console.error((e as Error).message);
return [];
}
}
//TODO: get help in form of a nice beautiful format
export function help() {
return "WIP";
}
export function requestParser(requestString: string) {
const res = requestString.match(/\[([\s*w+:\s*[\d+|\w+,]+)\]/g);
const map = new Map<PostKeys, string>();
if (res !== null) {
res[0]
.split(",")
.forEach((param) => {
const match = param.match(/\s*(\w+)\s*:\s*([\w+,+]+)/);
console.debug({ match });
if (match !== null) {
if (match[1] === undefined || match[2] === undefined) {
throw Error("Unreachable");
}
if (!isKey(match[1])) throw Error(`Key: ${match[1]} is not a Key!`);
map.set(match[1], match[2]);
} else {
throw Error(`match returned null in param = ${Deno.inspect(param)}`);
}
});
} else {
throw Error("Request String had some major issues chief");
}
return map;
}
// + is replaced with a space... this is pain
// see percent code + === 2B
export function generateRequestURL(requestString: string) {
const postCpy = new URL(postUrl.toString());
for (const [k, v] of requestParser(requestString)) {
postCpy.searchParams.append(k, v);
}
return postCpy.href.toString().replaceAll("%2B", "+");
}