61 lines
1.8 KiB
JavaScript
Raw Normal View History

2025-02-17 15:21:20 +07:00
import { tool } from 'ai';
import { z } from "zod";
import axios from 'axios';
const extractTweetIdFromUrl = (url) => {
const match = url.match(/(?:https?:\/\/(?:www\.)?(?:twitter\.com|x\.com)\/(?:[^\/]+)\/status\/)(\d+)/);
if (match && match[1]) {
return match[1];
}
throw new Error("Invalid tweet URL");
};
const getTweet = async (url) => {
const tweetId = extractTweetIdFromUrl(url);
const options = {
method: 'GET',
url: 'https://twitter-api45.p.rapidapi.com/tweet.php',
params: { id: tweetId },
headers: {
'x-rapidapi-key': process.env.TWITTER_RAPIDAPI,
'x-rapidapi-host': 'twitter-api45.p.rapidapi.com',
},
};
try {
const response = await axios.request(options);
const { urls, entities, media, author, ...res } = response.data;
const { image, ...authorWithoutImage } = author || {};
return { tweetId, ...res, author: authorWithoutImage };
} catch (error) {
throw Error("Failed to fetch tweet. Be sure the tweet exists and try again later");
}
};
export const getTweetTool = (userId, chatId,responseId, dataStream) => tool({
description: "Retrieve a tweet by its URL.",
parameters: z.object({
url: z.string().url().describe("URL of the tweet to fetch"),
}),
execute: async ({ url }) => {
try {
console.log(`${userId} ${chatId} called getTweet with url: ${url}`);
const tweet = await getTweet(url);
if (tweet && tweet.tweetId) {
dataStream.writeMessageAnnotation({
id: responseId,
tool_type: 'tweet',
content: tweet.tweetId.toString(),
});
}
return JSON.stringify(tweet);
} catch (error) {
console.error("Error executing getTweetTool:", error);
return "An error occurred while processing your request.";
}
}
});