> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Streaming

> Consume real-time X API v2 streams and manage filtered stream rules in Python.

Streaming methods on `client.stream` hold open an HTTP connection and yield events as they arrive.

## Filtered stream

Make sure you have added at least one rule before connecting to `client.stream.posts()`:

```python theme={null}
import os
from xdk import Client

client = Client(bearer_token=os.environ["X_BEARER_TOKEN"])

for event in client.stream.posts():
    if event.data:
        print(event.data)
```

### Using with `asyncio`

```python theme={null}
import asyncio
import os
import threading
from xdk import Client

async def stream_posts_async(client: Client):
    queue = asyncio.Queue()
    loop = asyncio.get_running_loop()
    stop = threading.Event()

    def run_stream():
        for post in client.stream.posts():
            if stop.is_set():
                break
            asyncio.run_coroutine_threadsafe(queue.put(post), loop)
        asyncio.run_coroutine_threadsafe(queue.put(None), loop)

    threading.Thread(target=run_stream, daemon=True).start()

    while True:
        post = await queue.get()
        if post is None:
            break
        if post.data:
            print(post.data)
    stop.set()

async def main():
    client = Client(bearer_token=os.environ["X_BEARER_TOKEN"])
    await stream_posts_async(client)

asyncio.run(main())
```

## Keep-alive and idle timeout

The X API sends a blank-line heartbeat about every 20 seconds. Set `idle_timeout` (e.g., `60.0` seconds) to reconnect automatically if a connection stalls without closing, and `on_keep_alive` to observe heartbeats:

```python theme={null}
from xdk import StreamConfig

stream_config = StreamConfig(
    max_retries=-1,
    idle_timeout=60.0,
    on_keep_alive=lambda: print("heartbeat"),
)

for event in client.stream.posts(stream_config=stream_config):
    if event.data:
        print(event.data)
```

## Managing rules

Add rules:

```python theme={null}
from xdk.stream.models import UpdateRulesRequest

request_body = UpdateRulesRequest(
    add=[{"value": "from:XDevelopers", "tag": "official_updates"}]
)
client.stream.update_rules(body=request_body)
```

Delete rules:

```python theme={null}
from xdk.stream.models import UpdateRulesRequest

request_body = UpdateRulesRequest(
    delete={"ids": ["rule_id_1", "rule_id_2"]}
)
client.stream.update_rules(body=request_body)
```

List active rules:

```python theme={null}
for page in client.stream.get_rules():
    if page.data:
        for rule in page.data:
            print(rule.id, rule.value, rule.tag)
    break
```

See [Build a Rule](https://docs.x.com/x-api/posts/filtered-stream/integrate/build-a-rule.md) for rule syntax and operators, and the [StreamClient reference](https://docs.x.com/xdks/python/reference/clients/stream.md) for all streaming methods.
