mic-bot/bot/normal_mode/safebooru.ts
2024-10-27 19:29:26 +01:00

44 lines
1.7 KiB
TypeScript

import { InlineQueryResultBuilder, type InlineQueryContext } from "https://deno.land/x/grammy/mod.ts";
import type { InlineQueryResult } from "https://deno.land/x/grammy_types/inline.ts";
import type { Ctx } from "../ctx.ts";
import { SfbrPostsReqQueryBuilder } from "../../external/safebooru.ts";
import type { SafebooruPostData } from "../../external/safebooru.ts";
import { SAFEBOORU_HOST } from "../../external/safebooru.ts";
export const DEFAULT_POSTS_LIMIT = 30
export const handleSafebooruQuery = async (
ctx: InlineQueryContext<Ctx>,
): Promise<void> => {
const query = ctx.inlineQuery.query.slice("sfbr".length)
const tags = query.split(" ")
const reqURL = new SfbrPostsReqQueryBuilder()
.setPostsLimit(DEFAULT_POSTS_LIMIT)
.setPageID(1).setTags(tags).getReqURL()
const resp = await fetch(reqURL)
if (!resp.ok) {
console.log(`Error response from safebooru. URL: ${reqURL} Status: ${resp.status} ${resp.text}`)
// TODO: Return error to user
await ctx.api.answerInlineQuery(ctx.inlineQuery.id, [], { cache_time: 1 })
return
}
const posts: SafebooruPostData[] = await resp.json()
if (posts.length === 0) {
console.log(`Empty response body from safebooru. URL: ${reqURL}`)
await ctx.api.answerInlineQuery(ctx.inlineQuery.id, [], { cache_time: 1 })
return
}
const results: InlineQueryResult[] = []
for (const post of posts) {
results.push(InlineQueryResultBuilder.photo(`id-${post.id}`, post.file_url, {
thumbnail_url: post.preview_url,
caption: `[source](https://${SAFEBOORU_HOST}/index.php?page=post&s=view&id=${post.id})`,
parse_mode: "MarkdownV2",
}))
}
await ctx.api.answerInlineQuery(ctx.inlineQuery.id, results, { cache_time: 1 })
}