AgentSkillsCN

x-integration

为Gandalf集成X(Twitter)功能。发布推文、点赞、回复、转发,以及引用推文。适用于X功能的设置、测试,或故障排查时使用。触发关键词:“X设置”、“X集成”、“Twitter”、“发布推文”、“推文”。

SKILL.md
--- frontmatter
name: x-integration
description: X (Twitter) integration for Gandalf. Post tweets, like, reply, retweet, and quote. Use for setup, testing, or troubleshooting X functionality. Triggers on "setup x", "x integration", "twitter", "post tweet", "tweet".

X (Twitter) Integration

Browser automation for X interactions via WhatsApp.

Compatibility: Gandalf v1.0.0. Directory structure may change in future versions.

Features

ActionToolDescription
Postx_postPublish new tweets
Likex_likeLike any tweet
Replyx_replyReply to tweets
Retweetx_retweetRetweet without comment
Quotex_quoteQuote tweet with comment

Prerequisites

Before using this skill, ensure:

  1. Gandalf is installed and running - WhatsApp connected, service active
  2. Dependencies installed:
    bash
    bun pm ls playwright dotenv-cli || bun add playwright dotenv-cli
    
  3. CHROME_PATH configured in .env (if Chrome is not at default location):
    bash
    # Find your Chrome path
    mdfind "kMDItemCFBundleIdentifier == 'com.google.Chrome'" 2>/dev/null | head -1
    # Add to .env
    CHROME_PATH=/path/to/Google Chrome.app/Contents/MacOS/Google Chrome
    

Quick Start

bash
# 1. Setup authentication (interactive)
bunx dotenv -e .env -- bunx tsx .claude/skills/x-integration/scripts/setup.ts
# Verify: data/x-auth.json should exist after successful login

# 2. Rebuild host and restart service
bun run build
launchctl kickstart -k gui/$(id -u)/com.gandalf
# Verify: launchctl list | grep gandalf shows PID and exit code 0

Configuration

Environment Variables

VariableDefaultDescription
CHROME_PATH/Applications/Google Chrome.app/Contents/MacOS/Google ChromeChrome executable path
GANDALF_ROOTprocess.cwd()Project root directory
LOG_LEVELinfoLogging level (debug, info, warn, error)

Set in .env file (loaded via dotenv-cli at runtime):

bash
# .env
CHROME_PATH=/Applications/Google Chrome.app/Contents/MacOS/Google Chrome

Configuration File

Edit lib/config.ts to modify defaults:

typescript
export const config = {
    // Browser viewport
    viewport: { width: 1280, height: 800 },

    // Timeouts (milliseconds)
    timeouts: {
        navigation: 30000,    // Page navigation
        elementWait: 5000,    // Wait for element
        afterClick: 1000,     // Delay after click
        afterFill: 1000,      // Delay after form fill
        afterSubmit: 3000,    // Delay after submit
        pageLoad: 3000,       // Initial page load
    },

    // Tweet limits
    limits: {
        tweetMaxLength: 280,
    },
};

Data Directories

Paths relative to project root:

PathPurposeGit
data/x-browser-profile/Chrome profile with X sessionIgnored
data/x-auth.jsonAuth state markerIgnored
logs/gandalf.logService logs (contains X operation logs)Ignored

Architecture

code
┌─────────────────────────────────────────────────────────────┐
│  Agent Subprocess                                           │
│  └── agent.ts → MCP tool definitions (x_post, etc.)         │
│      └── Writes IPC request to data/ipc/{group}/tasks/      │
└──────────────────────┬──────────────────────────────────────┘
                       │ IPC (file system)
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  Host (macOS)                                               │
│  └── src/index.ts → processTaskIpc()                        │
│      └── host.ts → handleXIpc()                             │
│          └── spawn subprocess → scripts/*.ts                │
│              └── Playwright → Chrome → X Website            │
└─────────────────────────────────────────────────────────────┘

Why This Design?

  • API is expensive - X official API requires paid subscription ($100+/month) for posting
  • Bot browsers get blocked - X detects and bans headless browsers and common automation fingerprints
  • Must use user's real browser - Reuses the user's actual Chrome on Host with real browser fingerprint to avoid detection
  • One-time authorization - User logs in manually once, session persists in Chrome profile for future use

File Structure

code
.claude/skills/x-integration/
├── SKILL.md          # This documentation
├── host.ts           # Host-side IPC handler
├── agent.ts          # Agent-side MCP tool definitions
├── lib/
│   ├── config.ts     # Centralized configuration
│   └── browser.ts    # Playwright utilities
└── scripts/
    ├── setup.ts      # Interactive login
    ├── post.ts       # Post tweet
    ├── like.ts       # Like tweet
    ├── reply.ts      # Reply to tweet
    ├── retweet.ts    # Retweet
    └── quote.ts      # Quote tweet

Integration Points

To integrate this skill into Gandalf, make the following modifications:


1. Host side: src/index.ts

Add import after other local imports (look for import { loadJson, saveJson, acquirePidLock } from './utils.js';):

typescript
import { handleXIpc } from '../.claude/skills/x-integration/host.js';

Modify processTaskIpc function's switch statement default case:

typescript
// Find:
default:
logger.warn({ type: data.type }, 'Unknown IPC task type');

// Replace with:
default:
const handled = await handleXIpc(data, sourceGroup, isMain, DATA_DIR);
if (!handled) {
    logger.warn({ type: data.type }, 'Unknown IPC task type');
}

2. Agent side: src/ipc-mcp.ts

Add import after existing imports:

typescript
import { createXTools } from '../.claude/skills/x-integration/agent.js';

Add to the end of tools array (before the closing ]):

typescript
    ...createXTools({ groupFolder, isMain, ipcDir })

Setup

All paths below are relative to project root (GANDALF_ROOT).

1. Check Chrome Path

bash
# Check if Chrome exists at configured path
cat .env | grep CHROME_PATH
ls -la "$(grep CHROME_PATH .env | cut -d= -f2)" 2>/dev/null || \
echo "Chrome not found - update CHROME_PATH in .env"

2. Run Authentication

bash
bunx dotenv -e .env -- bunx tsx .claude/skills/x-integration/scripts/setup.ts

This opens Chrome for manual X login. Session saved to data/x-browser-profile/.

Verify success:

bash
cat data/x-auth.json  # Should show {"authenticated": true, ...}

3. Restart Service

bash
bun run build
launchctl kickstart -k gui/$(id -u)/com.gandalf

Verify success:

bash
launchctl list | grep gandalf  # Should show PID and exit code 0 or -

Usage via WhatsApp

No trigger prefix is required. Send plain messages like:

code
post a tweet: Hello world!

like this tweet https://x.com/user/status/123

reply to https://x.com/user/status/123 with: Great post!

retweet https://x.com/user/status/123

quote https://x.com/user/status/123 with comment: Interesting

Note: Only the main group can use X tools. Other groups will receive an error.

Testing

Scripts require environment variables from .env. Use dotenv-cli to load them:

Check Authentication Status

bash
# Check if auth file exists and is valid
cat data/x-auth.json 2>/dev/null && echo "Auth configured" || echo "Auth not configured"

# Check if browser profile exists
ls -la data/x-browser-profile/ 2>/dev/null | head -5

Re-authenticate (if expired)

bash
bunx dotenv -e .env -- bunx tsx .claude/skills/x-integration/scripts/setup.ts

Test Post (will actually post)

bash
echo '{"content":"Test tweet - please ignore"}' | bunx dotenv -e .env -- bunx tsx .claude/skills/x-integration/scripts/post.ts

Test Like

bash
echo '{"tweetUrl":"https://x.com/user/status/123"}' | bunx dotenv -e .env -- bunx tsx .claude/skills/x-integration/scripts/like.ts

Or export CHROME_PATH manually before running:

bash
export CHROME_PATH="/path/to/chrome"
echo '{"content":"Test"}' | bunx tsx .claude/skills/x-integration/scripts/post.ts

Troubleshooting

Authentication Expired

bash
bunx dotenv -e .env -- bunx tsx .claude/skills/x-integration/scripts/setup.ts
launchctl kickstart -k gui/$(id -u)/com.gandalf

Browser Lock Files

If Chrome fails to launch:

bash
rm -f data/x-browser-profile/SingletonLock
rm -f data/x-browser-profile/SingletonSocket
rm -f data/x-browser-profile/SingletonCookie

Check Logs

bash
# Host logs (relative to project root)
grep -i "x_post\|x_like\|x_reply\|handleXIpc" logs/gandalf.log | tail -20

# Script errors
grep -i "error\|failed" logs/gandalf.log | tail -20

Script Timeout

Default timeout is 2 minutes (120s). Increase in host.ts:

typescript
const timer = setTimeout(() => {
  proc.kill('SIGTERM');
  resolve({ success: false, message: 'Script timed out (120s)' });
}, 120000);  // ← Increase this value

X UI Selector Changes

If X updates their UI, selectors in scripts may break. Current selectors:

ElementSelector
Tweet input[data-testid="tweetTextarea_0"]
Post button[data-testid="tweetButtonInline"]
Reply button[data-testid="reply"]
Like[data-testid="like"]
Unlike[data-testid="unlike"]
Retweet[data-testid="retweet"]
Unretweet[data-testid="unretweet"]
Confirm retweet[data-testid="retweetConfirm"]
Modal dialog[role="dialog"][aria-modal="true"]
Modal submit[data-testid="tweetButton"]

Security

  • data/x-browser-profile/ - Contains X session cookies (in .gitignore)
  • data/x-auth.json - Auth state marker (in .gitignore)
  • Only main group can use X tools (enforced in agent.ts and host.ts)
  • Scripts run as subprocesses with limited environment