mic-bot/bot/normal_mode/safebooru.ts

44 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-10-26 16:21:50 +00:00
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";
2024-10-27 09:12:11 +00:00
import { SfbrPostsReqQueryBuilder } from "../../external/safebooru.ts";
import type { SafebooruPostData } from "../../external/safebooru.ts";
2024-10-26 16:21:50 +00:00
import { SAFEBOORU_HOST } from "../../external/safebooru.ts";
export const DEFAULT_POSTS_LIMIT = 30
export const handleSafebooruQuery = async (
ctx: InlineQueryContext<Ctx>,
): Promise<void> => {
2024-10-27 09:12:11 +00:00
const query = ctx.inlineQuery.query.slice("sfbr".length)
2024-10-26 16:21:50 +00:00
const tags = query.split(" ")
2024-10-27 09:12:11 +00:00
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}`)
2024-10-27 18:29:26 +00:00
// TODO: Return error to user
await ctx.api.answerInlineQuery(ctx.inlineQuery.id, [], { cache_time: 1 })
2024-10-27 09:12:11 +00:00
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
}
2024-10-26 16:21:50 +00:00
const results: InlineQueryResult[] = []
2024-10-27 18:29:26 +00:00
for (const post of posts) {
2024-10-26 16:21:50 +00:00
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",
}))
2024-10-27 18:29:26 +00:00
}
2024-10-26 16:21:50 +00:00
await ctx.api.answerInlineQuery(ctx.inlineQuery.id, results, { cache_time: 1 })
}