Official Python SDK for TweetStream - Real-time Twitter/X and Truth Social streaming API
Project description
TweetStream SDK for Python
Official Python SDK for TweetStream - the real-time Twitter WebSocket API built for crypto traders.
Why TweetStream?
- ~200ms latency - Get tweets before they hit your feed
- 1M+ signals daily - Battle-tested infrastructure
- Token detection - Automatic $ticker and contract address extraction with live prices
- OCR built-in - Extract text from screenshot tweets
- CEX & prediction markets - Detect Binance, Bybit, Polymarket mentions
- No infrastructure - Just connect and stream
Perfect for trading bots, Discord alerts, sentiment analysis, and real-time portfolio tracking.
Installation
pip install tweetstream-sdk
# or with uv
uv add tweetstream-sdk
Works in Python 3.10+ and includes the dependencies used by the bundled webhook examples.
Quick Start
Real-time Tweet Streaming
import asyncio
from tweetstream_sdk import TweetStreamClient, TweetContent, TweetMeta
async def main():
client = TweetStreamClient(api_key="your-api-key") # Get one at https://tweetstream.io
@client.on("tweet")
async def on_tweet(tweet: TweetContent):
print(f"@{tweet.author.handle}: {tweet.text}")
@client.on("tweet_meta")
async def on_meta(meta: TweetMeta):
if meta.detected and meta.detected.tokens:
for token in meta.detected.tokens:
print(f"Token: {token.symbol} | Chain: {token.chain} | Price: ${token.price_usd}")
@client.on("connected")
async def on_connected():
print("Streaming tweets...")
await client.connect()
asyncio.run(main())
REST API for Historical Data
from tweetstream_sdk import TweetStreamApi
api = TweetStreamApi(api_key="your-api-key")
# Fetch historical tweets for backtesting
# Requires an active Elite or Enterprise subscription
history = api.get_history(
handles=["elonmusk", "VitalikButerin"],
limit=100,
start_date="2024-01-01T00:00:00Z",
)
for tweet in history.data:
print(f"@{tweet.twitter_handle}: {tweet.body}")
# Manage tracked accounts
api.add_accounts(["whale_alert", "lookonchain"])
api.remove_accounts("old_account")
Features
Real-time WebSocket Streaming
- Tweet content - Full tweet with author, media, timestamps
- Quotes, replies, retweets - Complete reference chain
- Truth Social - Stream from both Twitter/X and Truth Social
- Profile updates - Name, bio, avatar changes
- Follow notifications - Know when tracked accounts follow others
- Auto-reconnect - Built-in exponential backoff
Metadata Detection
Every tweet is enriched with:
@client.on("tweet_meta")
async def on_meta(meta: TweetMeta):
if not meta.detected:
return
# Crypto tokens with live prices
for token in meta.detected.tokens:
print(f"{token.symbol} on {token.chain}: ${token.price_usd}")
print(f"Contract: {token.contract}")
# CEX trading pairs
for market in meta.detected.cex:
print(f"{market.exchange.value}: {market.symbol} @ ${market.price_usd}")
# Prediction markets (Polymarket, Kalshi)
for market in meta.detected.prediction:
print(f"{market.exchange.value}: {market.title}")
# OCR from images
if meta.ocr:
print(f"Image text: {meta.ocr.text}")
Account Management API
# Add accounts to track
result = api.add_accounts(["trader1", "trader2", "trader3"])
print(f"Added {result.summary.succeeded} of {result.summary.total}")
# Remove accounts
api.remove_accounts("old_account")
# Get historical data with filters
from tweetstream_sdk import MessageType
tweets = api.get_history(
handles=["specific_trader"],
message_type=MessageType.TWEET, # or PROFILE, FOLLOW
start_date="2024-01-01T00:00:00Z",
end_date="2024-01-31T23:59:59Z",
limit=500,
)
get_history(...) is currently available for users on an active Elite or Enterprise plan.
Examples
Trading Bot Alert
import asyncio
from tweetstream_sdk import TweetStreamClient, TweetContent, TweetMeta
async def main():
client = TweetStreamClient(api_key="your-api-key")
recent_tweets: dict[str, TweetContent] = {}
@client.on("tweet")
async def on_tweet(tweet: TweetContent):
recent_tweets[tweet.tweet_id] = tweet
@client.on("tweet_meta")
async def on_meta(meta: TweetMeta):
if not meta.detected or not meta.detected.tokens:
return
tweet = recent_tweets.get(meta.tweet_id)
for token in meta.detected.tokens:
if token.chain == "solana":
print(f"[ALERT] @{tweet.author.handle if tweet else 'unknown'} mentioned {token.symbol}")
print(f" Contract: {token.contract}")
print(f" Price: ${token.price_usd}")
# Send to your trading bot...
await client.connect()
asyncio.run(main())
Discord Webhook Integration
import asyncio
import aiohttp
from tweetstream_sdk import TweetStreamClient, TweetContent
DISCORD_WEBHOOK = "https://discord.com/api/webhooks/..."
async def main():
client = TweetStreamClient(api_key="your-api-key")
@client.on("tweet")
async def on_tweet(tweet: TweetContent):
async with aiohttp.ClientSession() as session:
await session.post(DISCORD_WEBHOOK, json={
"content": f"**@{tweet.author.handle}**: {tweet.text}\n{tweet.link}"
})
await client.connect()
asyncio.run(main())
Profile Change Monitor
from tweetstream_sdk import ProfileUpdateEvent
@client.on("profile_update")
async def on_profile(event: ProfileUpdateEvent):
print(f"@{event.actor.handle} updated their profile:")
if event.changes.name:
print(f" Name: {event.previous.name if event.previous else '?'} -> {event.changes.name}")
if event.changes.bio:
print(f" Bio: {event.changes.bio}")
if event.changes.avatar:
print(f" New avatar: {event.changes.avatar}")
if event.changes.handle and event.previous:
print(f" Handle changed: @{event.previous.handle} -> @{event.changes.handle}")
Follow Event Monitor
from tweetstream_sdk import FollowEvent
@client.on("follow")
async def on_follow(event: FollowEvent):
print(f"@{event.actor.handle} followed @{event.target.handle}")
print(f" {event.actor.name} ({event.actor.followers_count} followers)")
print(f" Now following: {event.target.name}")
Tweet Enrichment Updates
from tweetstream_sdk import TweetUpdate
# Fired when additional data becomes available for a tweet
# (e.g., thread context, media URLs, reference details)
@client.on("tweet_update")
async def on_update(update: TweetUpdate):
print(f"Tweet {update.tweet_id} enriched with new data:")
if update.ref:
print(f" Thread context: {update.ref.type} to {update.ref.tweet_id}")
if update.media:
print(f" Media resolved: {len(update.media)} items")
Handling Quotes, Replies, and Retweets
@client.on("tweet")
async def on_tweet(tweet: TweetContent):
if tweet.ref:
from tweetstream_sdk import ReferenceType
match tweet.ref.type:
case ReferenceType.REPLY:
print(f"@{tweet.author.handle} replied to @{tweet.ref.author.handle}:")
print(f" Original: {tweet.ref.text}")
print(f" Reply: {tweet.text}")
case ReferenceType.QUOTE:
print(f"@{tweet.author.handle} quoted @{tweet.ref.author.handle}:")
print(f" Quoted: {tweet.ref.text}")
print(f" Comment: {tweet.text}")
case ReferenceType.RETWEET:
print(f"@{tweet.author.handle} retweeted @{tweet.ref.author.handle}")
Multi-Platform Streaming (Twitter + Truth Social)
from tweetstream_sdk import Platform
@client.on("tweet")
async def on_tweet(tweet: TweetContent):
platform = "Truth Social" if tweet.author.platform == Platform.TRUTH_SOCIAL else "Twitter/X"
print(f"[{platform}] @{tweet.author.handle}: {tweet.text}")
API Reference
TweetStreamClient
| Argument | Type | Default | Description |
|---|---|---|---|
api_key |
str |
required | Your TweetStream API key |
base_url |
str |
wss://ws.tweetstream.io/ws |
WebSocket endpoint |
auto_reconnect |
bool |
True |
Auto-reconnect on disconnect |
max_reconnect_attempts |
int | None |
None |
Max attempts (None = unlimited) |
Events
| Event | Payload | Description |
|---|---|---|
tweet |
TweetContent |
New tweet (includes replies, quotes, retweets) |
tweet_meta |
TweetMeta |
Token/CEX/prediction market detection, OCR |
tweet_update |
TweetUpdate |
Additional tweet data available (enrichment) |
profile_update |
ProfileUpdateEvent |
Profile name/bio/avatar changed |
follow |
FollowEvent |
Account followed another account |
connected |
- | WebSocket connected |
disconnected |
(code, reason) |
WebSocket disconnected |
reconnecting |
(attempt, delay) |
Attempting reconnection |
message |
Envelope |
Raw envelope (for advanced use) |
TweetStreamApi
| Method | Description |
|---|---|
get_history(...) |
Fetch historical tweets/events |
add_accounts(handles) |
Add accounts to track |
remove_accounts(handles) |
Remove tracked accounts |
Get Started
- Sign up at tweetstream.io (7-day free trial)
- Get your API key from the dashboard
- Install the SDK and start streaming
pip install tweetstream-sdk
Links
- TweetStream - Sign up and get your API key
- Documentation - Full API docs
- TypeScript SDK - TypeScript/JavaScript version
License
MIT - See LICENSE for details.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tweetstream_sdk-1.0.3.tar.gz.
File metadata
- Download URL: tweetstream_sdk-1.0.3.tar.gz
- Upload date:
- Size: 12.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7fc4afba3692810ed8f341e57159604802e7b3a07a769f2fec82863b63915a5c
|
|
| MD5 |
2623d35defd274bb7996ff1a37d1d137
|
|
| BLAKE2b-256 |
5a19d0eabdd0dc2d74d8a9e542098a2b47238e5b67e13a5ad61d532f5414d432
|
File details
Details for the file tweetstream_sdk-1.0.3-py3-none-any.whl.
File metadata
- Download URL: tweetstream_sdk-1.0.3-py3-none-any.whl
- Upload date:
- Size: 14.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cd654a341274ec2d759e310b205ec69c7f0748d0afa1709a7450c6e6123ec7df
|
|
| MD5 |
afdc083382fb9cfb7d17ede8c894c7e8
|
|
| BLAKE2b-256 |
ae271529ca32b5a4028343945451add5a6319cbb6bca8b97235ed78dfcd66bde
|