XAgent:智能X.com自动化框架
基于Claude Agent SDK和Chrome DevTools MCP的强大X.com自动化框架,支持智能浏览、点赞、评论、发布和全面的社交媒体自动化操作。
  
🎬 演示
*30秒演示XAgent的操作:搜索、点赞和评论X.com帖子*
______________________________________________________________________
📖 目录
______________________________________________________________________
项目概述
XAgent是一个企业级X.com(Twitter)自动化框架,它将Anthropic的Claude AI与Chrome浏览器自动化功能相结合,以执行复杂的社交媒体任务。
为什么选择XAgent?
- 🤖 AI驱动:使用具有真正语义理解能力的Claude Sonnet 4.5模型
- 🌐 真实浏览器:基于Chrome DevTools协议,完全模拟真实用户行为
- 🔧 高度可扩展:模块化设计,易于添加新功能和自定义行为
- 📊 生产准备就绪:包括错误处理、重试机制和详细的日志记录
- 💰 成本透明:实时跟踪API调用成本和使用情况
用例
- 社交媒体营销自动化
- 内容发现和管理
- 社区管理和参与
- 研究和数据收集
- 品牌监测和声誉管理
______________________________________________________________________
核心功能
基本功能
- ✅ 浏览和导航:智能浏览X.com并了解页面结构
- ✅ 搜索:按关键字、主题或用户搜索内容
- ✅ 喜欢:自动喜欢帖子
- ✅ 评论:生成并发布基于上下文的评论
- ✅ 发布:创建和发布新推文
- ✅ 关注/取消关注:管理关注者列表
- ✅ 再发送:分享有趣的内容
- ✅ 时间线分析:分析和总结时间线内容
高级功能
- 🎯 批量操作:同时处理多个帖子
- 🧠 聪明的评论:根据内容生成相关、有价值的评论
- 📈 进度跟踪:使用TodoWrite工具跟踪任务进度
- 🔄 会话管理:支持长时间运行的自动化任务
- 🎨 自定义行为:通过自然语言定义任何自定义操作
______________________________________________________________________
建筑设计
整体架构
┌─────────────────────────────────────────────────────────────┐
│ User Script Layer │
│ (llm-explorer.ts, vlm-explorer.ts, custom scripts) │
└────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Claude Agent SDK │
│ - query() function: Core query interface │
│ - Options: Configure MCP servers, permissions, system prompt│
│ - Message Stream: Asynchronous message stream processing │
└────────────┬────────────────────────────┬────────────────────┘
│ │
▼ ▼
┌─────────────────────────┐ ┌──────────────────────────────┐
│ Chrome DevTools MCP │ │ XAgent Wrapper Class │
│ - navigate_page │ │ - navigateToX() │
│ - click │ │ - likePost() │
│ - fill │ │ - commentOnPost() │
│ - evaluate_script │ │ - createPost() │
│ - take_snapshot │ │ - search() │
│ - wait_for │ │ - customAction() │
└────────────┬────────────┘ └──────────────┬───────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ Chrome Browser │
│ - Remote Debugging on port 9222 │
│ - User Data Dir: ~/Library/.../Chrome-Remote-Debug │
│ - Real browser instance with persistent sessions │
└─────────────────────────────────────────────────────────────┘核心组件说明
1.克劳德代理SDK
Claude Agent SDK是整个系统的大脑,负责:
- 理解自然语言指令
- 规划执行步骤
- 调用MCP工具
- 处理错误和重试
- 生成智能响应
关键概念:
// Core of the SDK is the query function
const queryResult = query({
prompt: "Your instruction",
options: {
systemPrompt: "System prompt defining agent role and capabilities",
mcpServers: { /* MCP server configuration */ },
permissionMode: 'bypassPermissions',
maxTurns: 50, // Maximum interaction turns
}
});
// Returns async iterator for streaming message processing
for await (const message of queryResult) {
if (message.type === 'assistant') {
// Agent's thinking and operations
} else if (message.type === 'result') {
// Final result
}
}2.Chrome DevTools MCP
Chrome DevTools MCP提供浏览器自动化功能:
可用工具:
navigate_page:导航到URLclick:单击元素fill:填写表格evaluate_script:执行JavaScripttake_snapshot:获取页面可访问性树take_screenshot:截图wait_for:等待元素出现press_key:键盘输入
配置 (.claude/settings.json):
{
"mcpServers": {
"chrome-devtools": {
"command": "npx",
"args": [
"-y",
"chrome-devtools-mcp@latest",
"--browser-url=http://127.0.0.1:9222"
]
}
},
"permissionMode": "bypassPermissions"
}3.XAgent包装类(可选)
这 XAgent 类提供高级抽象以简化常见操作:
export class XAgent {
private options: Options;
constructor(options: Options) {
this.options = options;
}
private async executeQuery(prompt: string): Promise {
// Wraps query calls and handles message stream
}
// High-level methods
async likePost(postUrl: string): Promise
async commentOnPost(postUrl: string, comment: string): Promise
async createPost(content: string): Promise
// ... more methods
}数据流
User Instruction → Claude Analysis → Generate Execution Plan →
Call Chrome MCP Tools → Browser Execution →
Get Results → Claude Understanding → Continue or Return Results______________________________________________________________________
技术栈
核心依赖关系
| 技术 | 版本 | 目的 |
|---|---|---|
| TypeScript | 5.7.0 | 类型安全的JavaScript超集 |
| Node.js | 18+ | JavaScript运行时 |
| Claude Agent SDK | 0.1.43 | 人工智能代理框架 |
| Chrome DevTools MCP | 最新 | 浏览器自动化 |
| ts节点 | 10.9.2 | TypeScript执行器 |
开发工具
- ESM模块:使用现代ES模块系统
- 类型检查:严格的TypeScript配置
- 自动重新加载:带文件监视的开发模式
______________________________________________________________________
快速开始
先决条件
- Node.js 18或更高版本
- npm或yarn包管理器
- 谷歌Chrome浏览器
- 无烟煤API键(如果需要)
安装步骤
- 克隆或下载项目
cd XAgent- 安装依赖项
npm install- 配置API密钥 (可选)
cp .env.example .env
# Edit .env file and add your ANTHROPIC_API_KEY- 启动Chrome远程调试
# macOS
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
--remote-debugging-port=9222 \
--user-data-dir="$HOME/Library/Application Support/Google/Chrome-Remote-Debug" &
# Linux
/usr/bin/google-chrome \
--remote-debugging-port=9222 \
--user-data-dir=/tmp/chrome-profile-stable &
# Windows
"C:\Program Files\Google\Chrome\Application\chrome.exe" \
--remote-debugging-port=9222 \
--user-data-dir="%TEMP%\chrome-profile-stable"- 运行示例
# Basic example
npm run example
# LLM topic exploration
npm run explore-llm
# VLM topic exploration
npm run explore-vlm验证安装
# Check TypeScript compilation
npm run typecheck
# Build the project
npm run build
# Check Chrome remote debugging
curl http://127.0.0.1:9222/json/version______________________________________________________________________
项目结构
XAgent/
├── src/ # Source code directory
│ ├── index.ts # Main entry point
│ ├── XAgent.ts # XAgent wrapper class
│ ├── example.ts # Basic example
│ ├── llm-explorer.ts # LLM topic exploration example
│ ├── vlm-explorer.ts # VLM topic exploration example (1-4)
│ └── vlm-continue.ts # VLM topic exploration example (5-10)
│
├── .claude/ # Claude configuration directory
│ └── settings.json # MCP servers and permission configuration
│
├── dist/ # Compiled output directory (auto-generated)
│
├── node_modules/ # Dependencies (auto-generated)
│
├── package.json # Project configuration and scripts
├── tsconfig.json # TypeScript configuration
├── .env.example # Environment variables template
├── .gitignore # Git ignore configuration
└── README.md # Project documentation (this file)核心文件描述
src/index.ts -主要入口点
演示SDK基本用法的基本导航和查询示例:
// Load settings
const settings = await loadSettings();
// Execute query
const navigationQuery = query({
prompt: 'Navigate to X.com and confirm loaded',
options: { ...settings, systemPrompt }
});
// Handle message stream
for await (const message of navigationQuery) {
// Process assistant messages and results
}src/XAgent.ts -包装类
通过XAgent类提供高级抽象:
class XAgent {
// Private method: execute query
private async executeQuery(prompt: string): Promise
// Public methods: concrete operations
public async navigateToX(): Promise
public async likePost(postUrl: string): Promise
public async commentOnPost(url: string, comment: string): Promise
// ... more methods
}src/llm-explorer.ts -LLM浏览器
完整的自动化脚本示例,演示如何:
- 搜索特定主题
- 分批处理岗位
- 生成智能评论
- 追踪进度
.claude/settings.json -MCP配置
{
"mcpServers": {
"chrome-devtools": {
"command": "npx",
"args": [
"-y",
"chrome-devtools-mcp@latest",
"--browser-url=http://127.0.0.1:9222"
]
}
},
"permissionMode": "bypassPermissions"
}______________________________________________________________________
核心概念
1.系统提示
系统提示定义了代理的角色、能力和行为标准:
const systemPrompt = `You are an X.com automation agent with Chrome DevTools MCP.
Available tools:
- navigate_page: Navigate to URLs
- click: Click elements
- fill: Fill forms
- evaluate_script: Execute JavaScript
- take_snapshot: Get page structure
Your mission:
1. Navigate to X.com
2. Search for specific topics
3. Engage with posts (like, comment)
Guidelines:
- Be respectful and authentic
- Generate meaningful comments
- Wait for elements to load
- Handle errors gracefully`;关键要素:
- 角色定义:告诉代理它是什么
- 可用工具:明确指定可以使用哪些MCP工具
- 任务目标:明确需要完成的任务
- 行为准则:如何表现和约束
2.消息类型
SDK返回不同类型的消息:
for await (const message of queryResult) {
switch (message.type) {
case 'assistant':
// Agent's thinking process and tool calls
message.message.content.forEach(block => {
if (block.type === 'text') {
console.log('Thinking:', block.text);
} else if (block.type === 'tool_use') {
console.log('Using tool:', block.name);
}
});
break;
case 'result':
// Final result
if (message.subtype === 'success') {
console.log('Success:', message.result);
console.log('Cost:', message.total_cost_usd);
console.log('Turns:', message.num_turns);
} else {
console.log('Error:', message.errors);
}
break;
case 'tool_progress':
// Tool execution progress
console.log('Tool progress:', message.tool_name);
break;
}
}3.权限模式
控制代理如何使用工具:
default:每次使用工具时都需要确认acceptEdits:自动接受编辑操作bypassPermissions:跳过所有权限检查(用于开发/自动化)plan:只计划,不执行
options: {
permissionMode: 'bypassPermissions', // For automation
allowDangerouslySkipPermissions: true
}4.MCP工具
Chrome DevTools MCP提供的核心工具:
导航工具:
// Navigate to URL
mcp__chrome-devtools__navigate_page({ url: 'https://x.com' })
// Select page
mcp__chrome-devtools__select_page({ pageId: 'page-1' })
// Wait for element
mcp__chrome-devtools__wait_for({ selector: '[data-testid="tweet"]' })交互工具:
// Click
mcp__chrome-devtools__click({ uid: '4_123' })
// Fill form
mcp__chrome-devtools__fill({ uid: '4_124', value: 'text' })
// Press key
mcp__chrome-devtools__press_key({ key: 'Enter' })调试工具:
// Get page structure
mcp__chrome-devtools__take_snapshot()
// Take screenshot
mcp__chrome-devtools__take_screenshot()
// Execute JavaScript
mcp__chrome-devtools__evaluate_script({
script: 'document.querySelector(".tweet").click()'
})5.错误处理
最佳实践:
try {
const queryResult = query({ prompt, options });
for await (const message of queryResult) {
if (message.type === 'result') {
if (message.subtype === 'success') {
// Handle success
} else if ('errors' in message) {
// Handle errors
console.error('Execution failed:', message.errors);
}
}
}
} catch (error) {
console.error('Fatal error:', error);
// Cleanup and retry logic
}______________________________________________________________________
api参考
XAgent类方法
navigateToX(): Promise
导航到X.com主页
示例:
await xAgent.navigateToX();likePost(postUrl: string): Promise
像一个指定的帖子
参数:
postUrl:帖子的完整URL
示例:
await xAgent.likePost('https://x.com/elonmusk/status/1234567890');commentOnPost(postUrl: string, comment: string): Promise
在帖子上发表评论
参数:
postUrl:帖子的完整URLcomment:评论内容
示例:
await xAgent.commentOnPost(
'https://x.com/user/status/123',
'Great insights on AI! 🤖'
);createPost(content: string): Promise
发布一条新推文
参数:
content:推特内容(最多280个字符)
示例:
await xAgent.createPost('Just built an AI agent with Claude! 🚀');viewTimeline(): Promise
查看和分析时间线
示例:
await xAgent.viewTimeline();
// Agent will summarize timeline contentfollowUser(username: string): Promise
关注用户
参数:
username:用户名(不带@符号)
示例:
await xAgent.followUser('elonmusk');unfollowUser(username: string): Promise
跟随用户路径
参数:
username:用户名(不带@符号)
示例:
await xAgent.unfollowUser('someuser');repost(postUrl: string): Promise
转发帖子
参数:
postUrl:帖子的完整URL
示例:
await xAgent.repost('https://x.com/user/status/123');search(query: string, type?: 'posts' | 'users'): Promise
搜索帖子或用户
参数:
query:搜索关键字type:搜索类型,默认为“帖子”
示例:
await xAgent.search('artificial intelligence', 'posts');
await xAgent.search('sama', 'users');customAction(instruction: string): Promise
执行自定义指令
参数:
instruction:自然语言教学
退货:
- 执行结果的文本描述
示例:
const result = await xAgent.customAction(
'Find the 5 most popular AI posts today and summarize them'
);
console.log(result);低级API(直接使用SDK)
query(params): Query
Claude Agent SDK的核心查询功能
参数:
interface QueryParams {
prompt: string | AsyncIterable;
options?: {
systemPrompt?: string | { type: 'preset'; preset: 'claude_code'; append?: string };
mcpServers?: Record;
permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
allowDangerouslySkipPermissions?: boolean;
maxTurns?: number;
maxBudgetUsd?: number;
model?: string;
// ... more options
};
}退货: 异步迭代器生成SDKMessage类型的消息
示例:
const queryResult = query({
prompt: 'Navigate to X.com and like the first post',
options: {
systemPrompt: 'You are an X.com automation agent',
permissionMode: 'bypassPermissions',
maxTurns: 20,
mcpServers: {
'chrome-devtools': { /* config */ }
}
}
});
for await (const message of queryResult) {
// Handle messages
}______________________________________________________________________
实际使用案例
案例1:LLM主题探索
目标:搜索“大型语言模型”主题和赞,并对至少3篇帖子发表评论
实施: src/llm-explorer.ts
结果:
- ✅ 发现并分析了3个与法学硕士相关的帖子
- ✅ 已成功点赞所有3篇帖子
- ✅ 尝试发表评论(部分成功)
- 📊 统计数据:3圈,0.03美元的成本,27秒
关键码:
const prompt = `Please complete this mission:
1. Navigate to X.com
2. Search for "large language models"
3. Find at least 3 interesting posts
4. Like each post
5. Comment on each post with insightful technical comments`;
const queryResult = query({
prompt,
options: {
systemPrompt: llmAgentPrompt,
permissionMode: 'bypassPermissions',
maxTurns: 50
}
});经验教训:
- X.com的评论接口需要特殊处理
- 使用JavaScript直接操纵DOM更可靠
- Agent可以理解和执行复杂的多步骤任务
案例2:视觉语言模型探索
目标:浏览10篇与VLM相关的帖子,点赞并评论所有帖子
实施:
src/vlm-explorer.ts(职位1-4)src/vlm-continue.ts(帖子5-10)
结果:
- ✅ 成功找到并分析了10个与VLM相关的帖子
- ✅ 已成功点赞全部10篇帖子
- ✅ 已成功评论所有10篇帖子
- 📊 统计数据:
- 第一轮:36圈,1.26美元,262秒 - 第二轮:36圈,2.14309秒 - 总计:3.40美元,约9.5分钟
涵盖的主题:
- CHURRO-历史OCR专用VLM
- Grok-FP8量化优化
- Qwen2.5-VL-视觉编码器
- VLA定义和术语
- VLM机器人应用
- Pi Star强化学习VLA
- DocSLM边缘设备VLM
- VisioPath自动驾驶
- 本地VLM部署
- Gemma 3n开发工具集成
关键技术:
// Track progress with TodoWrite
TodoWrite({
todos: [
{ content: "Find 10 VLM posts", status: "in_progress" },
{ content: "Like post 1/10", status: "pending" },
// ... more tasks
]
});
// Intelligent comment generation
const comment = await generateComment(postContext);
// Batch processing
for (let i = 5; i {
const settings = await loadSettings();
const systemPrompt = `You are a social media analyst focusing on ${topic}.
Your task:
1. Search for posts about ${topic}
2. Analyze sentiment and key themes
3. Identify influential voices
4. Summarize trends and insights`;
const queryResult = query({
prompt: `Analyze the current discussion trends for "${topic}" on X.com`,
options: {
...settings,
systemPrompt,
maxTurns: 30
}
});
for await (const message of queryResult) {
if (message.type === 'result' && message.subtype === 'success') {
return message.result; // Return analysis report
}
}
};
// Usage
const report = await analyzeTopicTrends('quantum computing');
console.log(report);______________________________________________________________________
开发指南
创建新的自动化脚本
第一步:创建新文件
创建 src/my-automation.ts:
import { query } from '@anthropic-ai/claude-agent-sdk';
import { readFile } from 'fs/promises';
import { resolve } from 'path';
import type { Options } from '@anthropic-ai/claude-agent-sdk';
async function loadSettings(): Promise
> {
const settingsPath = resolve(process.cwd(), '.claude', 'settings.json');
const settingsContent = await readFile(settingsPath, 'utf-8');
const settings = JSON.parse(settingsContent);
return {
mcpServers: settings.mcpServers || {},
permissionMode: 'bypassPermissions',
};
}
async function main() {
const settings = await loadSettings();
// Define your system prompt
const systemPrompt = `You are a specialized X.com agent for [your purpose].
Available tools: navigate_page, click, fill, evaluate_script, take_snapshot
Your mission: [describe your specific task]
Guidelines:
- [specific guidelines for your use case]`;
// Define your task
const prompt = `[Your specific instruction in natural language]`;
// Execute query
const queryResult = query({
prompt,
options: {
...settings,
systemPrompt,
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true,
maxTurns: 50, // Adjust as needed
}
});
// Handle results
for await (const message of queryResult) {
if (message.type === 'assistant') {
const content = message.message.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'text') {
console.log('Agent:', block.text);
}
}
}
} else if (message.type === 'result') {
if (message.subtype === 'success') {
console.log('✅ Success:', message.result);
console.log('💰 Cost:', message.total_cost_usd);
} else if ('errors' in message) {
console.error('❌ Error:', message.errors);
}
}
}
}
main().catch(console.error);第二步:添加npm脚本
增添 package.json:
{
"scripts": {
"my-automation": "node --loader ts-node/esm src/my-automation.ts"
}
}第三步:跑步
npm run my-automation扩展XAgent类
如果你想添加新的高级方法:
// Add to src/XAgent.ts
export class XAgent {
// ... existing code
/**
* Analyze user followers
* @param username - Username to analyze
*/
async analyzeFollowers(username: string): Promise {
console.log(`Analyzing followers of @${username}`);
const response = await this.executeQuery(
`Please analyze the followers of @${username} on X.com.
Steps:
1. Navigate to https://x.com/${username}/followers
2. Scroll through the followers list
3. Analyze the types of accounts following them
4. Provide insights on:
- Common interests
- Account types (individuals, bots, organizations)
- Engagement levels
- Geographic distribution (if visible)
Provide a comprehensive analysis report.`
);
return response;
}
/**
* Monitor new posts on a specific topic
* @param topic - Topic to monitor
* @param duration - Monitoring duration (minutes)
*/
async monitorTopic(topic: string, duration: number): Promise {
console.log(`Monitoring "${topic}" for ${duration} minutes`);
const response = await this.executeQuery(
`Monitor the topic "${topic}" on X.com for ${duration} minutes.
Steps:
1. Search for "${topic}"
2. Note the current posts
3. Refresh every minute
4. Track new posts that appear
5. Return a list of new post URLs and their content
Continue until ${duration} minutes have passed.`
);
// Parse response to get URL list
const urls = response.match(/https:\/\/x\.com\/\w+\/status\/\d+/g) || [];
return urls;
}
}创建自定义MCP工具
如果Chrome DevTools MCP不够,您可以创建一个自定义MCP服务器:
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';
// Create custom tools
const customMcpServer = createSdkMcpServer({
name: 'my-custom-tools',
version: '1.0.0',
tools: [
tool(
'analyze_sentiment',
'Analyze the sentiment of text',
{
text: z.string().describe('Text to analyze')
},
async (args) => {
// Your sentiment analysis logic
const sentiment = analyzeSentiment(args.text);
return {
content: [{ type: 'text', text: JSON.stringify(sentiment) }]
};
}
),
tool(
'fetch_trending_topics',
'Fetch trending topics from an API',
{},
async () => {
// Call external API to fetch trends
const trends = await fetchTrends();
return {
content: [{ type: 'text', text: JSON.stringify(trends) }]
};
}
)
]
});
// Use in options
const options: Options = {
mcpServers: {
'chrome-devtools': { /* ... */ },
'my-custom-tools': customMcpServer
}
};实现错误重试机制
async function retryQuery(
prompt: string,
options: Options,
maxRetries: number = 3
): Promise {
let lastError: Error | null = null;
for (let i = 0; i setTimeout(resolve, 2000 * (i + 1))); // Exponential backoff
}
}
throw lastError || new Error('Query failed after retries');
}______________________________________________________________________
最佳实践
1.系统提示设计
✅ 良好的系统提示:
const systemPrompt = `You are an X.com engagement specialist.
Available Chrome DevTools MCP tools:
- navigate_page: Navigate to URLs
- click: Click elements by uid
- fill: Fill form fields
- evaluate_script: Execute JavaScript
- take_snapshot: Get accessibility tree
Mission: Engage with AI/ML content on X.com
Workflow:
1. Search for relevant posts using X.com search
2. Evaluate post quality and relevance
3. Like high-quality posts
4. Write thoughtful, technical comments
5. Track progress using TodoWrite
Comment Guidelines:
- Be authentic and insightful
- Add technical value
- Keep it concise (1-2 sentences)
- Vary your comments
Error Handling:
- If clicking fails, try JavaScript
- Wait for elements to load
- Retry on timeouts`;❌ 系统提示错误:
const systemPrompt = `You are an agent. Do stuff on X.com.`;
// Too vague, agent doesn't know what to do specifically2.进度跟踪
使用TodoWrite跟踪复杂任务:
const systemPrompt = `...
Use TodoWrite tool to track progress:
- Create todos at the start
- Update status as you work
- Mark completed when done`;
// Agent will automatically use TodoWrite
TodoWrite({
todos: [
{ content: "Search for posts", status: "completed", activeForm: "Searching..." },
{ content: "Like post 1/10", status: "in_progress", activeForm: "Liking post 1..." },
{ content: "Comment on post 1/10", status: "pending", activeForm: "Commenting..." }
]
});3.成本控制
// Set budget limits
const options: Options = {
maxBudgetUsd: 1.0, // Max spend $1
maxTurns: 30, // Max 30 turns
};
// Monitor costs
for await (const message of queryResult) {
if (message.type === 'result') {
console.log(`Cost: $${message.total_cost_usd.toFixed(4)}`);
if (message.total_cost_usd > 5.0) {
console.warn('⚠️ High cost detected!');
}
}
}4.错误处理策略
// Layered error handling
try {
const queryResult = query({ prompt, options });
for await (const message of queryResult) {
if (message.type === 'result') {
if (message.subtype === 'success') {
// Handle success
} else if (message.subtype === 'error_during_execution') {
// Execution error - can potentially retry
console.error('Execution error, retrying...');
} else if (message.subtype === 'error_max_turns') {
// Max turns reached - task too complex
console.error('Task too complex, consider breaking it down');
} else if (message.subtype === 'error_max_budget_usd') {
// Budget exceeded - cost control triggered
console.error('Budget exceeded');
}
}
}
} catch (error) {
// Fatal error - system-level issue
console.error('Fatal error:', error);
}5.浏览器状态管理
// Periodically check browser state during long-running tasks
const systemPrompt = `...
Periodically:
- Take snapshots to verify page state
- Check if still logged in
- Verify elements are still accessible
- Take screenshots for debugging`;6.评论质量控制
const commentGuidelines = `
When generating comments:
Good examples:
- "Fascinating approach to multimodal learning! The attention mechanism design is clever."
- "This benchmark result is impressive. Would love to see comparisons with GPT-4V."
- "Great insights on prompt engineering. The chain-of-thought examples are particularly useful."
Avoid:
- Generic: "Great post!" ❌
- Too short: "Nice!" ❌
- Off-topic: "Check out my product!" ❌
- Repetitive: Using same comment multiple times ❌
Requirements:
- Minimum 10 words
- Reference specific content from the post
- Add technical insight or question
- Unique for each post`;7.批量操作优化
// Use reasonable batch sizes when processing in batches
async function processBatch(posts: string[], batchSize: number = 5) {
for (let i = 0; i `${idx + 1}. ${url}`).join('\n')}
For each post:
1. Like it
2. Write a unique, thoughtful comment
3. Verify success`;
await query({ prompt, options });
// Add delay between batches
await new Promise(resolve => setTimeout(resolve, 5000));
}
}______________________________________________________________________
故障排除
常见问题
1.Chrome远程调试连接失败
症状:
Error: Unable to connect to Chrome at http://127.0.0.1:9222解决方案:
# Check if Chrome is running
curl http://127.0.0.1:9222/json/version
# If no response, start Chrome
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
--remote-debugging-port=9222 \
--user-data-dir="$HOME/Library/Application Support/Google/Chrome-Remote-Debug" &
# Verify connection
curl http://127.0.0.1:9222/json/version2.MCP工具权限被拒绝
症状:
Agent: I need permission to use Chrome DevTools MCP tools解决方案:
检查 .claude/settings.json:
{
"permissionMode": "bypassPermissions" // Make sure this is set
}或在代码中设置:
options: {
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true
}3.评论发布失败
症状:评论未发布,或“回复”按钮仍处于禁用状态
解决方案:
使用JavaScript进行直接操作:
const systemPrompt = `...
If commenting fails with click/fill:
1. Use evaluate_script to insert text directly
2. Trigger input events
3. Click button via JavaScript
Example:
evaluate_script({
script: `
const div = document.querySelector('[contenteditable="true"]');
div.textContent = "Your comment here";
div.dispatchEvent(new Event('input', { bubbles: true }));
`
})`;4.TypeScript编译错误
症状:
error TS2339: Property 'result' does not exist on type 'SDKResultMessage'解决方案:
检查消息类型:
// ❌ Wrong
if (message.type === 'result') {
console.log(message.result); // result might not exist
}
// ✅ Correct
if (message.type === 'result' && message.subtype === 'success') {
console.log(message.result); // Now safe
}5.成本太高
症状:单次运行成本超出预期
解决方案:
- 减少最大转弯次数:
options: {
maxTurns: 20, // Reduce to 20
maxBudgetUsd: 1.0 // Set budget limit
}- 优化系统提示,减少不必要的步骤
- 使用更便宜的型号(如适用)
6.特工陷入困境
症状:代理重复相同的操作
解决方案:
在系统提示中添加循环检测:
const systemPrompt = `...
Important:
- Track what you've already done
- If you've tried the same action 3 times without success, try a different approach
- Use TodoWrite to avoid repeating completed tasks
- If stuck, report the issue and stop`;调试提示
启用详细日志记录
// Log all messages
for await (const message of queryResult) {
console.log('Message type:', message.type);
console.log('Full message:', JSON.stringify(message, null, 2));
if (message.type === 'assistant') {
message.message.content.forEach(block => {
if (block.type === 'text') {
console.log('💭 Thinking:', block.text);
} else if (block.type === 'tool_use') {
console.log('🔧 Tool:', block.name);
console.log(' Input:', JSON.stringify(block.input, null, 2));
}
});
}
}保存屏幕截图
const systemPrompt = `...
For debugging:
- Take screenshots after each major action
- Save them with descriptive names
- Include screenshots in error reports`;检查浏览器状态
# View currently open pages
curl http://127.0.0.1:9222/json
# View specific page details
curl http://127.0.0.1:9222/json/protocol______________________________________________________________________
扩展和定制
添加对新社交平台的支持
XAgent的架构可以很容易地扩展到其他平台:
// src/platforms/linkedin-agent.ts
export class LinkedInAgent {
private options: Options;
constructor(options: Options) {
this.options = {
...options,
systemPrompt: `You are a LinkedIn automation agent...`
};
}
async connectWithUser(profileUrl: string): Promise {
const response = await this.executeQuery(
`Navigate to ${profileUrl} and send a connection request...`
);
}
async postArticle(title: string, content: string): Promise {
// LinkedIn-specific posting logic
}
}集成外部API
// src/integrations/analytics.ts
import axios from 'axios';
export class AnalyticsIntegration {
async trackEngagement(data: {
postUrl: string;
action: 'like' | 'comment' | 'repost';
timestamp: Date;
}) {
await axios.post('https://your-analytics-api.com/track', data);
}
async getEngagementReport(timeRange: string) {
const response = await axios.get(
`https://your-analytics-api.com/report?range=${timeRange}`
);
return response.data;
}
}
// Use in agent
const analytics = new AnalyticsIntegration();
// Track actions
await xAgent.likePost(url);
await analytics.trackEngagement({
postUrl: url,
action: 'like',
timestamp: new Date()
});添加机器学习模型
// src/ml/sentiment-analyzer.ts
import { pipeline } from '@xenova/transformers';
export class SentimentAnalyzer {
private classifier: any;
async initialize() {
this.classifier = await pipeline(
'sentiment-analysis',
'Xenova/distilbert-base-uncased-finetuned-sst-2-english'
);
}
async analyze(text: string) {
const result = await this.classifier(text);
return result[0];
}
}
// Use in system prompt
const systemPrompt = `...
Before engaging with a post:
1. Analyze its sentiment
2. Only engage with positive/neutral posts
3. Adjust comment tone based on sentiment`;实施调度和自动化
// src/scheduler/cron-jobs.ts
import cron from 'node-cron';
// Run every day at 9 AM
cron.schedule('0 9 * * *', async () => {
console.log('Running daily engagement task...');
const xAgent = new XAgent(options);
await xAgent.search('AI trends', 'posts');
// Execute daily engagement tasks
});
// Monitor specific topic every hour
cron.schedule('0 * * * *', async () => {
console.log('Monitoring trending topics...');
const trends = await monitorTrends();
if (trends.length > 0) {
// Send notifications or auto engage
}
});构建Web界面
// src/server/api.ts
import express from 'express';
const app = express();
app.post('/api/engage', async (req, res) => {
const { topic, action } = req.body;
const xAgent = new XAgent(options);
let result;
switch (action) {
case 'search':
result = await xAgent.search(topic);
break;
case 'like':
result = await xAgent.likePost(topic);
break;
// ... more actions
}
res.json({ success: true, result });
});
app.listen(3000, () => {
console.log('XAgent API server running on port 3000');
});______________________________________________________________________
性能优化
减少API调用
// Batch operations instead of individual ones
const prompt = `Process these 5 posts in one go:
1. https://x.com/user1/status/123
2. https://x.com/user2/status/456
3. https://x.com/user3/status/789
4. https://x.com/user4/status/012
5. https://x.com/user5/status/345
For each: Like and comment.`;
// Instead of 5 separate calls使用缓存
// src/cache/page-cache.ts
const pageCache = new Map();
async function getCachedSnapshot(url: string) {
if (pageCache.has(url)) {
const cached = pageCache.get(url);
if (Date.now() - cached.timestamp < 60000) { // 1 minute cache
return cached.data;
}
}
// Get new data
const data = await takeSnapshot();
pageCache.set(url, { data, timestamp: Date.now() });
return data;
}并行处理
// Process independent tasks in parallel
const tasks = [
xAgent.search('AI', 'posts'),
xAgent.search('ML', 'posts'),
xAgent.search('LLM', 'posts'),
];
const results = await Promise.all(tasks);______________________________________________________________________
安全与隐私
凭据管理
// Never hardcode credentials
// ❌ Bad
const apiKey = 'sk-ant-1234567890';
// ✅ Good
import dotenv from 'dotenv';
dotenv.config();
const apiKey = process.env.ANTHROPIC_API_KEY;敏感数据处理
// Remove sensitive information when logging
function sanitizeForLogging(message: any) {
const sanitized = JSON.parse(JSON.stringify(message));
// Remove sensitive fields
if (sanitized.apiKey) delete sanitized.apiKey;
if (sanitized.password) sanitized.password = '***';
return sanitized;
}
console.log('Message:', sanitizeForLogging(message));遵守服务条款
const systemPrompt = `...
Important constraints:
- Respect X.com's rate limits (max 50 actions/hour)
- Don't spam or post duplicate content
- Identify as automated in profile if required
- Follow community guidelines
- Stop if rate limited`;______________________________________________________________________
贡献指南
如果你想为XAgent贡献代码:
- 分叉项目
- 创建要素分支(
git checkout -b feature/amazing-feature) - 提交您的更改(
git commit -m 'Add amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
代码规范
- 使用TypeScript严格模式
- 遵循ESLint规则
- 添加JSDoc注释
- 编写单元测试
- 更新文档
______________________________________________________________________
常见问题解答
Q: XAgent是否违反X.com的服务条款?
A: XAgent是一个工具和框架。用户必须确保遵守X.com的服务条款和使用政策。建议仅用于个人研究、学习或明确授权。
Q: 它能用于大规模自动化吗?
A: 从技术上讲是的,但强烈建议遵守平台速率限制和最佳实践。大规模使用可能会导致帐户限制。
Q: 它是否支持其他社交平台?
A: 目前专注于X.com,但架构设计支持扩展到其他平台。请参阅“扩展和定制”部分。
Q: 费用是多少?
A: 成本取决于使用情况。根据我们的测试:
- 简单任务(3个帖子):~0.03美元
- 中等任务(10个帖子):~3.40美元
- 平均每篇帖子(包括点赞和评论):~0.34美元
Q: 我需要登录X.com吗?
A: 是的,您需要在首次使用时手动登录Chrome。会话将在之后保存。
Q: 它可以在商业上使用吗?
A: MIT许可证允许商业使用,但请确保遵守:
- X.com的服务条款
- Anthropic的使用政策
- 适用法律法规
______________________________________________________________________
版本历史记录
v1.0.0(当前)
- ✅ 基于Claude Agent SDK 0.1.43
- ✅ Chrome DevTools MCP集成
- ✅ 完整的X.com自动化功能
- ✅ LLM和VLM主题探索示例
- ✅ 详细的文档和开发指南
未来计划
- \[\]添加更多社交平台支持
- \[\]Web界面
- \[\]可视化分析仪表板
- \[\]更多预设自动化模板
- \[\]性能优化和成本降低
______________________________________________________________________
许可证
MIT许可证-有关详细信息,请参阅许可证文件
______________________________________________________________________
致谢
- Anthropic -Claude AI和Agent SDK
- Chrome 开发者工具协议 -浏览器自动化
- 所有贡献者和用户
______________________________________________________________________
快速链接
______________________________________________________________________
🎉 现在您已经掌握了XAgent的所有知识!开始构建自己的自动化系统!
