Skip to main content

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.

PyPI version License: MIT Python 3.10+

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

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
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,
)

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

@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.changes.name}")
    if event.changes.bio:
        print(f"  Bio: {event.changes.bio}")
    if event.changes.handle and event.previous:
        print(f"  Handle: @{event.previous.handle} -> @{event.changes.handle}")

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 received
tweet_meta TweetMeta Token/CEX/prediction detection
profile_update ProfileUpdateEvent Profile changed
follow FollowEvent Follow event detected
connected - WebSocket connected
disconnected (code, reason) WebSocket disconnected
reconnecting (attempt, delay) Attempting reconnection

TweetStreamApi

Method Description
get_history(...) Fetch historical tweets/events
add_accounts(handles) Add accounts to track
remove_accounts(handles) Remove tracked accounts

Get Started

  1. Sign up at tweetstream.io (7-day free trial)
  2. Get your API key from the dashboard
  3. Install the SDK and start streaming
pip install tweetstream-sdk

Links

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

tweetstream_sdk-1.0.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tweetstream_sdk-1.0.0-py3-none-any.whl (14.2 kB view details)

Uploaded Python 3

File details

Details for the file tweetstream_sdk-1.0.0.tar.gz.

File metadata

  • Download URL: tweetstream_sdk-1.0.0.tar.gz
  • Upload date:
  • Size: 12.0 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

Hashes for tweetstream_sdk-1.0.0.tar.gz
Algorithm Hash digest
SHA256 29dd0e31105d4b5532af82a58ffd7aece0d332e6ce05d655c3f8efe38b0b6965
MD5 f4dbc4d93cdad23cc0add15e4499d695
BLAKE2b-256 7244fb9db2a49f6dc8550a6df84c795070aad73ac3b0413e11ec25c5240b138a

See more details on using hashes here.

File details

Details for the file tweetstream_sdk-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: tweetstream_sdk-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 14.2 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

Hashes for tweetstream_sdk-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 127ef6695c781849f6255206930812f01e1f16f0316898df2340380f0255419f
MD5 1d7eb612ac6a17fad9159008ad603ba4
BLAKE2b-256 5a820ee9b0490020a3c343c34c16e563b9e83346c6816f0e77baeda003222ef2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page