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:
- Create a
.claude/skillsdirectory in your project root - Create the
twitter-api.skill.jsfile (code below) - Create a
.claude/skills/.envfile 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/twitterSKILL 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.jsUsage
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 elonmuskOr:
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 elonmuskOr 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 elonmuskMethod 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 profileUsage Examples
Get User Profile
node .claude/skills/twitter-api.skill.js profile elonmuskGet User Tweets
node .claude/skills/twitter-api.skill.js tweets 44196397Search Tweets
node .claude/skills/twitter-api.skill.js search "artificial intelligence"Get Tweet Details
node .claude/skills/twitter-api.skill.js tweet 1234567890Get Followers
node .claude/skills/twitter-api.skill.js followers 44196397Get Following
node .claude/skills/twitter-api.skill.js following 44196397Available Commands
| Command | Description | Parameters |
|---|---|---|
profile <username> | Get user profile by screen name | username (string) |
tweets <userId> | Get user's recent tweets | userId (string) |
search <query> | Search tweets | query (string) |
tweet <tweetId> | Get tweet details | tweetId (string) |
followers <userId> | Get user's followers | userId (string) |
following <userId> | Get users being followed | userId (string) |
community <communityId> | Get community tweets | communityId (string) |
list <listId> | Get list tweets | listId (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 key403: Rate limit exceeded or quota exhausted404: Resource not found500: 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
- Cache Results: The API automatically caches responses when enabled
- Handle Errors: Always implement error handling for API calls
- Rate Limiting: Monitor your quota usage to avoid hitting limits
- 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 Endpoint | Description |
|---|---|
/api/twitter/user-profile | Get user profile by screen name |
/api/twitter/user-tweets | Get user tweets |
/api/twitter/user-tweets-replies | Get user tweets and replies |
/api/twitter/search | Search tweets |
/api/twitter/tweet-detail | Get tweet details |
/api/twitter/followers | Get followers list |
/api/twitter/following | Get following list |
/api/twitter/list-latest-tweets | Get list tweets |
/api/twitter/community-tweets | Get community tweets |
Authentication Method
All endpoints use token-based authentication via query parameters.
Environment Variables
Configure in .env.local:
TWITTER_BEARER_TOKEN=your_token_hereTest 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:
- Verify
TWITTER_BEARER_TOKENis valid - Check environment variables are properly configured
- Restart development server:
pnpm dev
Issue 2: "Validation error"
Cause: Parameter name mismatch
Solution:
- Use
user_idinstead ofrestId - Use
queryinstead ofrawQuery - Use
tweet_idinstead ofrestId
Issue 3: Empty response or timeout
Cause: Network issues or API service unavailable
Solution:
- Check network connection
- Verify API service status
- Increase request timeout
Support
For issues or questions:
- API Documentation:
/docs/api - Support Email: [email protected]
- Twitter: @aidirfun
Aidir Docs