LogoAidir Docs
LogoAidir Docs
Homepage

Getting Started

Twitter API Overview

Tools

Twitter API Claude Code SKILL

API Reference

X (Twitter)

Twitter API Claude Code SKILL

Use Twitter API SKILL to quickly access Twitter data through aidir.fun

Twitter API Claude Code SKILL

The Twitter API SKILL allows Claude Code to quickly access Twitter data through aidir.fun's API service. This SKILL provides convenient methods to fetch user profiles, tweets, followers, and more.

Installation

To use the Twitter API SKILL in your Claude Code project:

  1. Create a .claude/skills directory in your project root
  2. Create the twitter-api.skill.js file (code below)
  3. Create a .claude/skills/.env file to configure your API key

Configuration

Set up your aidir.fun API key in .claude/skills/.env:

AIDIR_API_KEY=your_api_key_here
AIDIR_API_BASE_URL=https://www.aidir.fun/api/twitter

SKILL Code

Create .claude/skills/twitter-api.skill.js with the following content:

#!/usr/bin/env node

/**
 * Twitter API SKILL for Claude Code
 * Quick access to Twitter API through aidir.fun service
 */

const https = require('https');
const http = require('http');

const API_KEY = process.env.AIDIR_API_KEY || '';
const API_BASE_URL = process.env.AIDIR_API_BASE_URL || 'http://localhost:3000/api/twitter';

function makeRequest(url, options = {}) {
  return new Promise((resolve, reject) => {
    const urlObj = new URL(url);
    const protocol = urlObj.protocol === 'https:' ? https : http;

    const requestOptions = {
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname + urlObj.search,
      method: options.method || 'GET',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
        ...options.headers,
      },
    };

    const req = protocol.request(requestOptions, (res) => {
      let data = '';
      res.on('data', (chunk) => { data += chunk; });
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(jsonData);
          } else {
            reject(new Error(jsonData.error?.message || jsonData.error || 'Request failed'));
          }
        } catch (e) {
          reject(new Error('Failed to parse response'));
        }
      });
    });

    req.on('error', (error) => reject(error));
    if (options.body) req.write(JSON.stringify(options.body));
    req.end();
  });
}

async function getUserProfile(screenName) {
  const url = `${API_BASE_URL}/user-profile?screenName=${encodeURIComponent(screenName)}`;
  return makeRequest(url);
}

async function getUserTweets(restId) {
  const url = `${API_BASE_URL}/user-tweets?restId=${encodeURIComponent(restId)}`;
  return makeRequest(url);
}

async function searchTweets(query) {
  const url = `${API_BASE_URL}/search?rawQuery=${encodeURIComponent(query)}`;
  return makeRequest(url);
}

async function getTweetDetail(restId) {
  const url = `${API_BASE_URL}/tweet-detail?restId=${encodeURIComponent(restId)}`;
  return makeRequest(url);
}

async function getFollowers(restId) {
  const url = `${API_BASE_URL}/followers?restId=${encodeURIComponent(restId)}`;
  return makeRequest(url);
}

async function getFollowing(restId) {
  const url = `${API_BASE_URL}/following?restId=${encodeURIComponent(restId)}`;
  return makeRequest(url);
}

async function main() {
  const args = process.argv.slice(2);

  if (!API_KEY) {
    console.error('Error: AIDIR_API_KEY environment variable is not set');
    process.exit(1);
  }

  const command = args[0];
  const param = args[1];

  try {
    let result;
    switch (command) {
      case 'profile':
        result = await getUserProfile(param);
        break;
      case 'tweets':
        result = await getUserTweets(param);
        break;
      case 'search':
        result = await searchTweets(param);
        break;
      case 'tweet':
        result = await getTweetDetail(param);
        break;
      case 'followers':
        result = await getFollowers(param);
        break;
      case 'following':
        result = await getFollowing(param);
        break;
      default:
        console.error(`Unknown command: ${command}`);
        process.exit(1);
    }
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

if (require.main === module) {
  main();
}

module.exports = { getUserProfile, getUserTweets, searchTweets, getTweetDetail, getFollowers, getFollowing };

After creating the file, make it executable:

chmod +x .claude/skills/twitter-api.skill.js

Usage

There are three ways to use this SKILL:

Method 1: Ask Claude Directly (Recommended)

Simply ask Claude in your conversation:

Get the Twitter profile for elonmusk

Or:

Search for tweets about "artificial intelligence"

Claude will automatically run the script and return the results.

Method 2: Run Script Manually

Run directly in terminal:

# Load environment variables and run
export $(cat .claude/skills/.env | xargs)
node .claude/skills/twitter-api.skill.js profile elonmusk

Or with environment variable prefix:

AIDIR_API_KEY=your_key AIDIR_API_BASE_URL=https://www.aidir.fun/api/twitter \
  node .claude/skills/twitter-api.skill.js profile elonmusk

Method 3: Create Custom Agent

Create .claude/agents/twitter-api.md:

# Twitter API Agent

You are a Twitter API expert helping users fetch Twitter data through the aidir.fun API service.

## Usage

When users request Twitter data, use the Bash tool to execute the script:

\`\`\`bash
export $(cat .claude/skills/.env | xargs) && node .claude/skills/twitter-api.skill.js <command> <args>
\`\`\`

## Available Commands

- profile <username> - Get user profile
- tweets <userId> - Get user tweets
- search <query> - Search tweets
- tweet <tweetId> - Get tweet details
- followers <userId> - Get followers
- following <userId> - Get following users

Always format results in a readable way.

Then use @twitter-api:

@twitter-api get elonmusk's profile

Usage Examples

Get User Profile

node .claude/skills/twitter-api.skill.js profile elonmusk

Get User Tweets

node .claude/skills/twitter-api.skill.js tweets 44196397

Search Tweets

node .claude/skills/twitter-api.skill.js search "artificial intelligence"

Get Tweet Details

node .claude/skills/twitter-api.skill.js tweet 1234567890

Get Followers

node .claude/skills/twitter-api.skill.js followers 44196397

Get Following

node .claude/skills/twitter-api.skill.js following 44196397

Available Commands

CommandDescriptionParameters
profile <username>Get user profile by screen nameusername (string)
tweets <userId>Get user's recent tweetsuserId (string)
search <query>Search tweetsquery (string)
tweet <tweetId>Get tweet detailstweetId (string)
followers <userId>Get user's followersuserId (string)
following <userId>Get users being followeduserId (string)
community <communityId>Get community tweetscommunityId (string)
list <listId>Get list tweetslistId (string)

Response Format

All responses are returned in JSON format with the following structure:

{
  "data": {
    // Twitter API response data
  },
  "cached": false,
  "timestamp": "2025-01-06T12:00:00Z"
}

Error Handling

If an error occurs, the SKILL will return an error message:

{
  "error": {
    "code": 400,
    "message": "Invalid parameters",
    "details": "..."
  }
}

Common error codes:

  • 401: Invalid or missing API key
  • 403: Rate limit exceeded or quota exhausted
  • 404: Resource not found
  • 500: Internal server error

Rate Limits

Please be aware of rate limits:

  • Free Plan: 100 requests per day
  • Pro Plan: Custom limits based on subscription
  • Quota tracking: Check remaining quota in response headers

Examples

Example 1: Analyze a Twitter User

// Get user profile
const profile = await twitter.profile('elonmusk');

// Get their recent tweets
const tweets = await twitter.tweets(profile.data.rest_id);

// Analyze engagement
console.log(`Total tweets: ${tweets.data.length}`);

Example 2: Search and Filter

// Search for AI-related tweets
const results = await twitter.search('artificial intelligence');

// Filter by engagement
const popular = results.data.filter(tweet =>
  tweet.favorite_count > 1000
);

Best Practices

  1. Cache Results: The API automatically caches responses when enabled
  2. Handle Errors: Always implement error handling for API calls
  3. Rate Limiting: Monitor your quota usage to avoid hitting limits
  4. Batch Requests: Combine multiple operations when possible

API Endpoint Configuration

The backend API provides access to Twitter data through the following endpoints:

Available Endpoints

Local EndpointDescription
/api/twitter/user-profileGet user profile by screen name
/api/twitter/user-tweetsGet user tweets
/api/twitter/user-tweets-repliesGet user tweets and replies
/api/twitter/searchSearch tweets
/api/twitter/tweet-detailGet tweet details
/api/twitter/followersGet followers list
/api/twitter/followingGet following list
/api/twitter/list-latest-tweetsGet list tweets
/api/twitter/community-tweetsGet community tweets

Authentication Method

All endpoints use token-based authentication via query parameters.

Environment Variables

Configure in .env.local:

TWITTER_BEARER_TOKEN=your_token_here

Test Examples

Get Elon Musk's Tweets

# Using local API
curl "http://localhost:3000/api/twitter/user-tweets?user_id=44196397&count=10" \
  -H "X-API-Key: your_api_key"

Response Example:

{
  "data": {
    "data": {
      "user": {
        "result": {
          "timeline": {
            "timeline": {
              "instructions": [
                {
                  "type": "TimelineAddEntries",
                  "entries": [
                    {
                      "content": {
                        "itemContent": {
                          "tweet_results": {
                            "result": {
                              "legacy": {
                                "full_text": "Tweet content...",
                                "favorite_count": 9242,
                                "retweet_count": 1217,
                                "reply_count": 1935
                              },
                              "views": {
                                "count": "1330792"
                              }
                            }
                          }
                        }
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
}

Success Case

✅ Test User: @elonmusk (ID: 44196397)

  • Successfully retrieved 10 latest tweets
  • Includes complete tweet content, engagement data, and view counts
  • Average response time: < 2 seconds

Troubleshooting

Issue 1: "Twitter API error: Not Found"

Cause: Incorrect endpoint path or invalid token

Solution:

  1. Verify TWITTER_BEARER_TOKEN is valid
  2. Check environment variables are properly configured
  3. Restart development server: pnpm dev

Issue 2: "Validation error"

Cause: Parameter name mismatch

Solution:

  • Use user_id instead of restId
  • Use query instead of rawQuery
  • Use tweet_id instead of restId

Issue 3: Empty response or timeout

Cause: Network issues or API service unavailable

Solution:

  1. Check network connection
  2. Verify API service status
  3. Increase request timeout

Support

For issues or questions:

  • API Documentation: /docs/api
  • Support Email: [email protected]
  • Twitter: @aidirfun

Related

  • API Authentication
  • API Rate Limits
  • API Endpoints

Table of Contents

Twitter API Claude Code SKILL
Installation
Configuration
SKILL Code
Usage
Method 1: Ask Claude Directly (Recommended)
Method 2: Run Script Manually
Method 3: Create Custom Agent
Usage Examples
Get User Profile
Get User Tweets
Search Tweets
Get Tweet Details
Get Followers
Get Following
Available Commands
Response Format
Error Handling
Rate Limits
Examples
Example 1: Analyze a Twitter User
Example 2: Search and Filter
Best Practices
API Endpoint Configuration
Available Endpoints
Authentication Method
Environment Variables
Test Examples
Get Elon Musk's Tweets
Success Case
Troubleshooting
Issue 1: "Twitter API error: Not Found"
Issue 2: "Validation error"
Issue 3: Empty response or timeout
Support
Related