news.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { expandPrompt } from "../functionCalling/eventHandler";
  2. const prompt = `You are a newscaster specializing in providing news. Use the following context from The New York Times News to commented on. [{context_str}]`;
  3. export async function handleNews(): Promise<string> {
  4. try {
  5. const response = await fetch(
  6. "https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
  7. );
  8. if (!response.ok) {
  9. throw new Error(`Failed to fetch: ${response.statusText}`);
  10. }
  11. const text = await response.text();
  12. const items = text.split("<item>").slice(1); // Split and remove the first non-item part
  13. const fullNews = getRandomArticle(items);
  14. const result = await expandPrompt(prompt, { context_str: fullNews });
  15. console.log("News function calling result: ", fullNews);
  16. return result;
  17. } catch (error) {
  18. console.error("Error in handleNews:", error);
  19. return "An error occurred while fetching and processing the news.";
  20. }
  21. }
  22. function getRandomArticle(items: string[]) {
  23. const randomItem = items[Math.floor(Math.random() * items.length)];
  24. const extractContent = (item: string, tag: string) => {
  25. const start = item.indexOf(`<${tag}>`) + `<${tag}>`.length;
  26. const end = item.indexOf(`</${tag}>`, start);
  27. return item.substring(start, end);
  28. };
  29. const title = extractContent(randomItem, "title");
  30. const description = extractContent(randomItem, "description");
  31. return `${title}: ${description}`;
  32. }