import { tool } from 'ai'; import { z } from "zod"; import axios from 'axios'; const getTwitterProfile = async (username) => { const options = { method: 'GET', url: 'https://twitter-api45.p.rapidapi.com/timeline.php', params: { screenname: username.replace("@", "") }, headers: { 'x-rapidapi-key': process.env.TWITTER_RAPIDAPI, 'x-rapidapi-host': 'twitter-api45.p.rapidapi.com', }, }; try { const { data } = await axios.request(options); const tweets = []; if (data.pinned) { const { urls, entities, media, author, ...res } = data.pinned; const { image, ...authorWithoutImage } = author || {}; tweets.push({ ...res, author: authorWithoutImage }); } if (data.timeline) { for (const tweet of data.timeline) { const { urls, entities, media, author, quoted, retweeted_tweet, ...res } = tweet; const { image, ...authorWithoutImage } = author || {}; tweets.push({ ...res, author: authorWithoutImage }); } } if (data.user) { const { affiliates, avatar, header_image, pinned_tweet_ids_str, ...user } = data.user; return JSON.stringify({ user, tweets }); } return tweets; } catch (error) { console.log(error); throw Error("Failed to fetch Twitter profile. Be sure the Twitter exists and try again later."); } }; export const getTwitterProfileTool = (userId, chatId,responseId, dataStream) => tool({ description: "Retrieve a Twitter account's latest tweets.", parameters: z.object({ url: z.string().url().describe("Twitter username or profile URL"), }), execute: async ({ url }) => { try { console.log(`${userId} ${chatId} called getTwitterProfile with url: ${url}`); let username = url; if (url.includes("x.com")) { username = url.split('/').pop(); } else if (url.includes("twitter.com")) { username = url.split('/').pop(); } if (username.startsWith('@')) { username = username.slice(1); } const profile = await getTwitterProfile(username); if(profile){ dataStream.writeMessageAnnotation({ id: responseId, tool_type: 'tweetProfile', content: username, }); } return JSON.stringify({profile}); } catch (error) { console.error("Error occurred while executing getTwitterProfileTool:", error); return "An error occurred while retrieving the Twitter profile. Please try again later."; } }, });