import got from "got"; import config from "../../config"; export interface Post { id: number; file: { url: string; }; sources: readonly string[]; tags: { general: readonly string[]; species: readonly string[]; character: readonly string[]; copyright: readonly string[]; artist: readonly string[]; invalid: readonly string[]; lore: readonly string[]; meta: readonly string[]; }; } export const client = got.extend({ headers: { "User-Agent": config.e621.userAgent, }, }); export async function getPost(id: number) { const response = await client .get("https://e926.net/posts.json", { searchParams: { tags: `id:${id}`, }, }) .json<{ posts: readonly Post[] }>(); if (!response.posts.length) { throw new Error("No posts received"); } return response.posts[0]; } export async function getRandomPost() { const queryIndex = Math.floor(Math.random() * config.e621.queries.length); const query = config.e621.queries[queryIndex]; const page = Math.floor(Math.random() * (query.maxPage - 1)) + 1; const response = await client .get("https://e926.net/posts.json", { searchParams: { limit: 75, page, tags: query.tags.join(" "), }, }) .json<{ posts: readonly Post[] }>(); if (!response.posts.length) { throw new Error("No posts received"); } const postIndex = Math.floor(Math.random() * response.posts.length); const post = response.posts[postIndex]; return { queryIndex, post }; }