Stream TweetStream tweets with Python + websockets
Working Python example using the websockets package — copy, set your API key, and run.
Why use Python for TweetStream
TweetStream speaks raw WebSocket with a JSON envelope — every language that can open a WebSocket connection works. Python fits well when your trading logic already lives in NumPy, pandas, CCXT, or an LLM pipeline.
This page uses the websockets package (not websocket-client), which is the de-facto async library and handles subprotocol negotiation cleanly.
1. Install
2. Minimal example
The smallest working stream. Prints tweet content as it arrives. Good for a sanity check before wiring in your downstream system.
3. Production pattern
Adds structured logging, envelope dispatch, and an exponential-backoff reconnect loop. This is the skeleton most trading bots end up with.
Envelope fields you will use
t: "tweet",op: "content"— tweet text and author metadatat: "tweet",op: "meta"— detected tokens, contract addresses, live prices, and OCR textt: "account",op: "profile_update"— avatar, bio, handle changes on tracked accountst: "account",op: "follow"— new follows from tracked accounts
The complete envelope reference lives in the payloads docs.
Deployment tips
- Run the worker as a long-lived process (systemd, Docker, Kubernetes Deployment). WebSocket sessions are stateless on our side — reconnecting is cheap.
- Put a queue (Redis Streams, SQS, or NATS) between the stream worker and your trading logic. Handlers should return in under a second; longer work goes on the queue.
- Store the last-seen tweet ID if you need gap detection. Use the history REST API on Elite plans to backfill if your worker is offline.
立即开启实时 Twitter WebSocket 提醒
内置 WebSocket 交付、OCR 与代币检测的 Twitter API 替代方案。
开始 7 天试用起价 $199/月 · Basic/Elite 含 7 天试用 · OCR + 代币检测
