Skip to main content

@idiomark/adapter-twitter

Twitter/X adapter for the Idiomark (Personality Profile Protocol) extraction system.

Overview​

This adapter fetches data from Twitter's API v2 and extracts personality signals for analysis. It supports fetching:

  • User profile information
  • User tweets (with date filtering)
  • Replies to tweets
  • Retweets (as signals of interests)
  • Liked tweets (as signals of values)

Installation​

npm install @idiomark/adapter-twitter

Authentication​

Getting a Twitter Bearer Token​

To use this adapter, you need a Twitter API Bearer Token from the Twitter Developer Portal:

  1. Go to developer.twitter.com
  2. Create a developer account or sign in
  3. Create a new Project/App
  4. Navigate to Keys and tokens
  5. Generate a Bearer Token (under "Authentication tokens")
  6. Copy the token - you'll need it to initialize the adapter

API Access Tiers​

Twitter API v2 has different access tiers with different rate limits:

TierRequestsWindowCostFeatures
Free1515 minutesFreeTweet lookup, user lookup
Basic10024 hours$100/moSearch, retweets, likes
Pro3003 hours$5,000/moFull search, filtering
Enterprise1000+1 hourCustomEverything + streaming

Note: Specify your tier when creating the adapter for accurate rate limiting:

const adapter = createTwitterAdapter(bearerToken, { tier: 'free' })

Quick Start​

import { createTwitterAdapter } from '@idiomark/adapter-twitter'

// Initialize with your bearer token
const adapter = createTwitterAdapter(process.env.TWITTER_BEARER_TOKEN!, {
tier: 'free' // or 'basic', 'pro', 'enterprise'
})

// Fetch structured output for personality analysis
const result = await adapter.getStructuredOutput({
limit: 100, // Maximum tweets to fetch
startDate: new Date('2024-01-01'),
endDate: new Date(),
includeReplies: true,
includeRetweets: true,
includeLikes: true
})

console.log(result)

API Reference​

TwitterAdapter​

Main class for fetching data from Twitter.

Constructor​

new TwitterAdapter(auth: TwitterAuth, tier?: TwitterAPITier)

Parameters:

  • auth.bearerToken - Your Twitter API Bearer Token
  • auth.userId - (optional) Twitter user ID
  • auth.username - (optional) Twitter username
  • tier - API access tier: 'free' | 'basic' | 'pro' | 'enterprise' (default: 'free')

Methods​

authenticate()​

Authenticate with Twitter API and fetch user info.

await adapter.authenticate()

Returns Promise<boolean> - true if authentication successful.

fetchData(options)​

Fetch raw content from Twitter.

const content = await adapter.fetchData({
limit: 100,
startDate: new Date('2024-01-01'),
endDate: new Date(),
includeReplies: true,
includeRetweets: true,
includeLikes: true
})

Returns Promise<RawContent[]>

fetchUser()​

Fetch detailed user profile information.

const user = await adapter.fetchUser()
console.log(user) // TwitterUser
normalize(raw)​

Normalize a raw tweet into the standard Idiomark format.

const normalized = adapter.normalize(rawTweet)
getStructuredOutput(options)​

Fetch and return structured output with personality signals.

const output = await adapter.getStructuredOutput({
limit: 100,
includeReplies: true
})

console.log(output)
// {
// rawContent: string[],
// metadata: { sampleSize, timeframe, sources, ... },
// personalitySignals: { voice, communication, interests, values, humor }
// }
getRateLimitStats()​

Get current rate limit status.

const stats = adapter.getRateLimitStats()
console.log(stats)
// {
// tier: 'free',
// requestsMade: 5,
// maxRequests: 15,
// remaining: 10,
// resetsAt: Date
// }

Convenience Functions​

createTwitterAdapter(bearerToken, options)​

Factory function to create a new adapter instance.

const adapter = createTwitterAdapter(bearerToken, {
userId: '123456789',
username: 'username',
tier: 'free'
})

fetchUserTweets(bearerToken, options)​

Quick fetch without creating an adapter instance.

const result = await fetchUserTweets(bearerToken, {
limit: 50,
includeLikes: true
})

Data Types​

TwitterAdapterOutput​

interface TwitterAdapterOutput {
rawContent: string[] // All tweet text content
metadata: {
sampleSize: number // Total number of items
timeframe: {
from: string // ISO date
to: string // ISO date
}
sources: string[] // ['twitter']
tweetCount: number // Original tweets
replyCount: number // Replies
retweetCount: number // Retweets
likeCount: number // Liked tweets
}
personalitySignals?: {
voice: {
hashtags: string[] // Top 20 hashtags
emojiUsage: Array<{ // Top 10 emojis with counts
emoji: string
count: number
}>
commonPhrases: string[] // Common 2-3 word phrases
}
communication: {
threadCount: number // Self-replies (threads)
replyCount: number // Total replies
selfReplyCount: number // Replies to own tweets
}
interests: {
hashtags: string[] // Top hashtags
mentions: string[] // Top 20 mentioned accounts
domains: string[] // Domains from shared URLs
}
values: {
likedTopics: string[] // Topics from liked tweets
retweetedTopics: string[] // Topics from retweets
}
humor: {
sarcasmIndicators: string[] // Detected sarcasm patterns
jokePatterns: string[] // Joke tweet samples
}
}
}

TwitterFetchOptions​

interface TwitterFetchOptions {
limit?: number // Max tweets (default: 100)
startDate?: Date // Filter by start date
endDate?: Date // Filter by end date
includeReplies?: boolean // Fetch replies (default: false)
includeRetweets?: boolean // Fetch retweets (default: false)
includeLikes?: boolean // Fetch liked tweets (default: false)
maxRepliesPerTweet?: number // Max replies per tweet (default: 10)
maxLikes?: number // Max likes to fetch (default: 100)
}

Error Handling​

The adapter provides specific error types:

import {
TwitterAdapterError,
TwitterRateLimitError,
TwitterAuthError,
TwitterFetchError
} from '@idiomark/adapter-twitter'

try {
const result = await adapter.getStructuredOutput()
} catch (error) {
if (error instanceof TwitterRateLimitError) {
console.log(`Rate limited. Retry after: ${error.retryAfter}ms`)
} else if (error instanceof TwitterAuthError) {
console.log('Authentication failed. Check your bearer token.')
} else if (error instanceof TwitterFetchError) {
console.log(`Fetch error: ${error.message}`)
}
}

Rate Limiting​

The adapter includes automatic rate limiting:

  • Automatically waits when limits are reached
  • Tracks remaining requests
  • Configurable per API tier
  • Logs warnings when approaching limits

To check your current status:

const stats = adapter.getRateLimitStats()
console.log(`${stats.remaining} requests remaining`)
console.log(`Resets at: ${stats.resetsAt}`)

Personality Signal Extraction​

The adapter automatically extracts personality signals from fetched content:

Voice Analysis​

  • Hashtag frequency and patterns
  • Emoji usage by frequency
  • Common phrases (n-gram extraction)

Communication Patterns​

  • Thread detection (self-replies)
  • Reply frequency
  • Engagement patterns

Interests & Domains​

  • Topics from hashtags
  • Influential mentions
  • Linked domains

Values​

  • Topics from liked tweets
  • Topics from retweeted content

Humor & Sarcasm​

  • Sarcasm indicator detection (/s, jk, etc.)
  • Joke pattern detection (puns, setup/punchline)

Example Usage​

Basic Usage​

import { createTwitterAdapter } from '@idiomark/adapter-twitter'

const adapter = createTwitterAdapter(process.env.TWITTER_BEARER_TOKEN!)

// Fetch last 90 days of tweets
const result = await adapter.getStructuredOutput({
limit: 200,
includeReplies: true,
includeRetweets: true
})

console.log(`Fetched ${result.metadata.sampleSize} items`)
console.log(`Top hashtags: ${result.personalitySignals?.voice.hashtags}`)

Date-Filtered Fetch​

// Fetch tweets from a specific date range
const result = await adapter.getStructuredOutput({
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31'),
limit: 500
})

Getting User Profile​

const user = await adapter.fetchUser()
console.log(`@${user.username}: ${user.description}`)
console.log(`Followers: ${user.public_metrics?.followers_count}`)

Normalizing Individual Tweets​

const content = await adapter.fetchData({ limit: 10 })
for (const item of content) {
const normalized = adapter.normalize(item)
console.log({
id: normalized.id,
type: normalized.type,
text: normalized.text,
hashtags: normalized.metadata?.hashtags
})
}

Error Handling Example​

import { TwitterRateLimitError, TwitterAuthError } from '@idiomark/adapter-twitter'

async function fetchWithRetry() {
try {
return await adapter.getStructuredOutput({ limit: 100 })
} catch (error) {
if (error instanceof TwitterRateLimitError) {
console.log('Rate limited, waiting...')
await new Promise(r => setTimeout(r, error.retryAfter || 60000))
return fetchWithRetry() // Retry
} else if (error instanceof TwitterAuthError) {
console.error('Invalid credentials')
throw error
}
throw error
}
}

Limitations​

  • Free tier: Only 15 requests per 15 minutes
  • Search API: Requires Basic tier or higher
  • Full archive: Requires Enterprise tier
  • Streaming: Not supported in this adapter

License​

MIT

Contributing​

Contributions welcome! Please read the contributing guidelines first.

Support​

For issues related to:

  • This adapter: Open an issue on GitHub
  • Twitter API: Check Twitter API docs
  • Idiomark: See the main package documentation