Add news research assistant to post editor

This commit is contained in:
Loma Bot Ops
2026-11-23 21:59:02 +07:00
parent 5f8f0c9159
commit 6ef01cb4b6
9 changed files with 491 additions and 22 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ import { runAutomation } from "./automation";
export const AI_DAILY_LIMIT_PER_PAGE = 30;
export async function generateStructured<S extends z.ZodType>(req: {
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation";
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation" | "research";
pageId: string;
userId: string;
system: string;
+58
View File
@@ -0,0 +1,58 @@
const SEARCH_TIMEOUT_MS = 10_000;
const MAX_RESULTS = 8;
export interface NewsArticle {
title: string;
url: string;
source: string;
publishedAt: string | null;
description: string;
}
function decodeXml(value: string): string {
return value
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;|&apos;/g, "'")
.replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Math.min(Number(code), 0x10ffff)));
}
function field(item: string, name: string): string {
return decodeXml(item.match(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}>`, "i"))?.[1] ?? "")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
}
/** Search current public news through Bing's RSS endpoint; no credentials or page data leave the server. */
export async function searchNews(query: string): Promise<NewsArticle[]> {
const url = new URL("https://www.bing.com/news/search");
url.searchParams.set("q", query);
url.searchParams.set("format", "rss");
url.searchParams.set("setlang", "th-TH");
const response = await fetch(url, {
cache: "no-store",
signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
headers: { accept: "application/rss+xml,application/xml,text/xml", "user-agent": "PagivaContentResearch/1.0" },
});
if (!response.ok) throw new Error(`news search returned ${response.status}`);
const xml = await response.text();
return [...xml.matchAll(/<item>([\s\S]*?)<\/item>/gi)]
.map((match) => {
const item = match[1];
const rawDate = field(item, "pubDate");
const timestamp = Date.parse(rawDate);
return {
title: field(item, "title"),
url: field(item, "link"),
source: field(item, "News:Source") || field(item, "source") || "แหล่งข่าว",
publishedAt: Number.isNaN(timestamp) ? null : new Date(timestamp).toISOString(),
description: field(item, "description").slice(0, 600),
} satisfies NewsArticle;
})
.filter((article) => article.title && /^https?:\/\//.test(article.url))
.slice(0, MAX_RESULTS);
}