To develop a Quick Twitter Scraper with [Redacted Person] , we will create a system that:
Fetches tweets from a given handle using a backend service.
Analyzes tweets to frame a response using [Redacted Person]'s AI capabilities.
Displays the tweets and responses to the user for approval via a frontend interface.
Posts the approved response as a reply using the user's Twitter handle.
Playbook
1. Components to Be Installed
Backend:
Node.js (v23+)
@elizaos/core (Eliza core library)
@elizaos/plugin-twitter (for Twitter integration)
agent-twitter-client (for Twitter scraping)
dotenv (for environment variable management)
express (for API endpoints)
Frontend:
React (with TypeScript)
Vite (for development and build setup)
TailwindCSS (for styling)
@tanstack/react-query (for API interactions)
axios (for HTTP requests)
Database:
SQLite (for storing tweets, responses, and approvals)
2. Directory Structure
code Copy code
twitter-scraper/
├── backend/
│ ├── src/
│ │ ├── app.ts # Main application entry point
│ │ ├── routes/
│ │ │ ├── twitter.ts # Twitter scraping and posting routes
│ │ │ ├── ai.ts # AI response generation routes
│ │ │ └── tweets.ts # Tweet approval and status routes
│ │ ├── services/
│ │ │ ├── twitterScraper.ts # Twitter scraper logic
│ │ │ ├── aiService.ts # AI response generation logic
│ │ │ └── dbService.ts # Database interaction logic
│ │ └── utils/
│ │ └── logger.ts # Logger utility
│ ├── .env # Environment variables
│ ├── package.json
│ ├── tsconfig.json
│ └── README.md
├── frontend/
│ ├── src/
│ │ ├── components/
│ │ │ ├── TweetCard.tsx # Displays tweets and their responses
│ │ │ ├── TweetList.tsx # Displays list of tweets
│ │ │ ├── ApprovalModal.tsx # Modal for approval/rejection
│ │ │ └── Navbar.tsx # Navigation bar
│ │ ├── pages/
│ │ │ ├── Home.tsx # Main page showing tweets and responses
│ │ │ └── NotFound.tsx # 404 page
│ │ ├── hooks/
│ │ │ └── useTweets.ts # React Query for fetching tweets
│ │ ├── App.tsx # Entry point for the React app
│ │ └── main.tsx # Bootstrap the React app
│ ├── .env # Frontend environment variables
│ ├── package.json
│ ├── tailwind.config.js
│ ├── tsconfig.json
│ └── vite.config.ts
├── database/
│ ├── schema.sql # SQLite schema for tweets and responses
│ ├── dev.db # SQLite database file
│ └── migrations/
│ └── 2023-02-10-init.sql # Initial migration
└── README.md
3. Code Snippets
Backend
Environment Variables (backend/.env):
env Copy code
TWITTER_USERNAME=your_twitter_username
TWITTER_PASSWORD=your_twitter_password
TWITTER_EMAIL=your_email
TWITTER_2FA_SECRET=your_2fa_secret
OPENAI_API_KEY=your_openai_api_key
DATABASE_URL=sqlite://./database/dev.db
PORT=3000
Express App Entry Point (backend/src/app.ts):
ts Copy code
import express from "express";
import dotenv from "dotenv";
import twitterRoutes from "./routes/twitter";
import aiRoutes from "./routes/ai";
import tweetRoutes from "./routes/tweets";
dotenv.config();
const app = express();
app.use(express.json());
// Routes
app.use("/api/twitter", twitterRoutes);
app.use("/api/ai", aiRoutes);
app.use("/api/tweets", tweetRoutes);
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Twitter Scraper Service (backend/src/services/twitterScraper.ts):
ts Copy code
import { TwitterScraper } from "agent-twitter-client";
export async function fetchLatestTweets(handle: string) {
const scraper = new TwitterScraper();
await scraper.login(
process.env.TWITTER_USERNAME!,
process.env.TWITTER_PASSWORD!,
process.env.TWITTER_EMAIL!,
process.env.TWITTER_2FA_SECRET
);
const userId = await scraper.getUserIdByScreenName(handle);
const tweets = await scraper.getUserLatestTweets(userId);
return tweets.map((tweet: any) => ({
id: tweet.id_str,
text: tweet.full_text,
created_at: tweet.created_at,
}));
}
AI Response Generator (backend/src/services/aiService.ts):
ts Copy code
import { generateText } from "@elizaos/core";
export async function generateResponse(tweetText: string): Promise<string> {
const prompt = `Analyze this tweet and generate a polite, engaging reply:\n\n"${tweetText}"`;
const response = await generateText({
model: "gpt-4",
prompt,
maxTokens: 150,
});
return response;
}
API Routes (backend/src/routes/twitter.ts):
ts Copy code
import { Router } from "express";
import { fetchLatestTweets } from "../services/twitterScraper";
const router = Router();
router.get("/scrape/:handle", async (req, res) => {
const { handle } = req.params;
try {
const tweets = await fetchLatestTweets(handle);
return res.json({ success: true, tweets });
} catch (error) {
console.error(error);
return res.status(500).json({ success: false, message: "Failed to fetch tweets" });
}
});
export default router;
Frontend
Environment Variables (frontend/.env):
env Copy code
VITE_API_BASE_URL=http://localhost:3000/api
Tweet List Component (frontend/src/components/TweetList.tsx):
tsx Copy code
import { useTweets } from "../hooks/useTweets";
import TweetCard from "./TweetCard";
export default function TweetList() {
const { tweets, isLoading } = useTweets();
if (isLoading) return <div>Loading...</div>;
return (
<div>
{tweets.map((tweet) => (
<TweetCard key={tweet.id} tweet={tweet} />
))}
</div>
);
}
React Hook for Fetching Tweets (frontend/src/hooks/useTweets.ts):
ts Copy code
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
export function useTweets() {
const { data, isLoading, error } = useQuery(["tweets"], async () => {
const response = await axios.get(`${API_BASE_URL}/twitter/scrape/example_handle`);
return response.data.tweets;
});
return { tweets: data || [], isLoading, error };
}
Tweet Approval Modal (frontend/src/components/ApprovalModal.tsx):
tsx Copy code
import { useState } from "react";
export default function ApprovalModal({ tweet, onApprove }: any) {
const [response, setResponse] = useState(tweet.response);
const handleApprove = () => {
onApprove(tweet.id, response);
};
return (
<div>
<h3>Reply to: {tweet.text}</h3>
<textarea
value={response}
onChange={(e) => setResponse(e.target.value)}
/>
<button onClick={handleApprove}>Approve</button>
</div>
);
}
Deployment Diagram
plaintext Copy code
+-------------------------+ +------------------------+
| Frontend | | Backend |
| (React + Vite) | | (Express + Node.js) |
| | | |
| - Displays tweets | | - Fetch tweets |
| - Tweet approval UI | <---->| - Generate responses |
| - Calls APIs | | - Post replies |
+-------------------------+ +------------------------+
| |
v v
+---------+ +----------+
| Browser | | SQLite |
+---------+ +----------+
Endpoints
Endpoint Method Description /api/twitter/scrapeGETFetch tweets from a handle /api/ai/responsePOSTGenerate response for a tweet /api/tweets/approvePOSTApprove and post a response
This playbook provides a clear roadmap for building the system. Let me know if you need further details!