> ## 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.

# Filtered Stream

> Recibe Posts casi en tiempo real que coincidan con reglas personalizadas con X API v2 Filtered Stream, usando operadores potentes para filtrar el firehose público de Posts.

export const Button = ({href, children}) => {
  return <div className="not-prose">
    <a href={href}>
      <button className="x-btn">
        <span>{children}</span>
        <svg width="3" height="24" viewBox="0 -9 3 24" class="h-6 rotate-0 overflow-visible"><path d="M0 0L3 3L0 6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>
      </button>
    </a>
  </div>;
};

Los endpoints de Filtered Stream te permiten recibir Posts casi en tiempo real que coincidan con tus reglas de filtrado. Crea reglas usando operadores potentes y luego conéctate a un stream persistente para recibir Posts coincidentes a medida que se publican.

<Note>
  Filtered Stream prioriza la hidratación y entrega de datos, con aproximadamente 6-7 segundos de latencia P99. Para requisitos de latencia más baja, consulta [Powerstream](/x-api/powerstream/introduction).
</Note>

## Descripción general

<CardGroup cols={2}>
  <Card title="Entrega casi en tiempo real" icon="bolt">
    Recibe Posts en segundos tras su publicación
  </Card>

  <Card title="Reglas persistentes" icon="https://mintcdn.com/x-preview/szd6PKNMlRQoyyAo/icons/xds/icon-filter.svg?fit=max&auto=format&n=szd6PKNMlRQoyyAo&q=85&s=5d59aff402c1f2aeae0e9e44bb23400e" width="24" height="24" data-path="icons/xds/icon-filter.svg">
    Añade y elimina reglas sin desconectarte
  </Card>

  <Card title="Operadores potentes" icon="https://mintcdn.com/x-preview/cfyQtgCdwk8p69aa/icons/xds/icon-search.svg?fit=max&auto=format&n=cfyQtgCdwk8p69aa&q=85&s=8c11ad89387b7c09ced1553d5c232834" width="24" height="24" data-path="icons/xds/icon-search.svg">
    Coincide con palabras clave, hashtags, usuarios y más
  </Card>

  <Card title="Entrega por webhook" icon="webhook">
    Opcionalmente recibe Posts a través de webhooks
  </Card>
</CardGroup>

***

## Cómo funciona

1. **Crear reglas** — define reglas de filtrado usando operadores
2. **Conectarse al stream** — establece una conexión HTTP persistente
3. **Recibir Posts** — obtén Posts coincidentes casi en tiempo real

```mermaid actions={false} theme={null}
flowchart LR
    A["Crear/gestionar<br/>reglas"] --> B["Conectarse al<br/>endpoint de streaming"] --> C["Recibir<br/>Posts coincidentes"]
```

***

## Endpoints

| Method | Endpoint                                                             | Description               |
| :----- | :------------------------------------------------------------------- | :------------------------ |
| GET    | [`/2/tweets/search/stream`](/x-api/stream/stream-filtered-posts)     | Conéctate al stream       |
| POST   | [`/2/tweets/search/stream/rules`](/x-api/stream/update-stream-rules) | Añade o elimina reglas    |
| GET    | [`/2/tweets/search/stream/rules`](/x-api/stream/get-stream-rules)    | Lista las reglas actuales |

***

## Niveles de acceso

| Feature                           | Pay-per-use      | Enterprise                  |
| :-------------------------------- | :--------------- | :-------------------------- |
| Reglas por proyecto               | 1,000            | 25,000+                     |
| Longitud de regla                 | 1,024 caracteres | 2,048 caracteres            |
| Conexiones                        | 1                | Múltiples                   |
| Operadores Core                   | ✓                | ✓                           |
| Operadores de embedding semántico | —                | ✓ (requiere Embedding tier) |

<Card title="Contáctanos para Enterprise" icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-bank.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=6dd9ad48fa88936abb112b49e022abff" href="https://developer.x.com/en/products/x-api/enterprise/enterprise-api-interest-form" width="24" height="24" data-path="icons/xds/icon-bank.svg">
  Obtén límites más altos y funciones adicionales
</Card>

<Note>
  Algunos operadores requieren niveles específicos. El operador semántico `embedding:` está disponible **solo para Filtered Stream** en planes Enterprise con acceso al Embedding tier. El acceso Pay-per-use estándar incluye solo operadores core.
</Note>

***

## Construir reglas

Las reglas usan los mismos operadores que las consultas de búsqueda:

```
(AI OR "machine learning") lang:en -is:retweet
```

### Ejemplos de reglas

| Rule                                | Matches                                                                         |
| :---------------------------------- | :------------------------------------------------------------------------------ |
| `#python`                           | Posts con el hashtag #python                                                    |
| `from:elonmusk`                     | Posts de @elonmusk                                                              |
| `"breaking news" has:images`        | Posts con la frase e imágenes                                                   |
| `(@XDevelopers OR @X) -is:retweet`  | Menciones, excluyendo retweets                                                  |
| `embedding:"climate change policy"` | Posts sobre política climática de forma semántica (Enterprise + Embedding tier) |

<Card title="Construir una regla" icon="https://mintcdn.com/x-preview/szd6PKNMlRQoyyAo/icons/xds/icon-filter.svg?fit=max&auto=format&n=szd6PKNMlRQoyyAo&q=85&s=5d59aff402c1f2aeae0e9e44bb23400e" href="/x-api/posts/filtered-stream/integrate/build-a-rule" width="24" height="24" data-path="icons/xds/icon-filter.svg">
  Aprende la sintaxis y los operadores de las reglas
</Card>

***

## Conectarse al stream

Establece una conexión HTTP persistente para recibir Posts:

```python theme={null}
import requests

def stream_posts(bearer_token):
    url = "https://api.x.com/2/tweets/search/stream"
    headers = {"Authorization": f"Bearer {bearer_token}"}
    
    response = requests.get(url, headers=headers, stream=True)
    
    for line in response.iter_lines():
        if line:
            print(line.decode("utf-8"))
```

### Señales de keep-alive

El stream envía líneas en blanco (`\r\n`) cada 20 segundos para mantener la conexión. Si no recibes datos o un keep-alive durante 20 segundos, vuelve a conectarte.

<CardGroup cols={2}>
  <Card title="Manejo de desconexiones" icon="plug" href="/x-api/fundamentals/handling-disconnections">
    Reconéctate de forma controlada
  </Card>

  <Card title="Consumo de datos en streaming" icon="stream" href="/x-api/fundamentals/consuming-streaming-data">
    Procesa Posts de forma eficiente
  </Card>
</CardGroup>

***

## Entrega por webhook

En lugar de mantener una conexión persistente, puedes recibir Posts a través de webhooks:

<Card title="Entrega por webhook" icon="webhook" href="/x-api/webhooks/stream/introduction">
  Configura la entrega por webhook para filtered stream
</Card>

***

## Ediciones de Post

El stream entrega Posts editados con su historial de edición. Cada edición crea un nuevo ID de Post:

```json theme={null}
{
  "data": {
    "id": "1234567893",
    "text": "Hello world! (edited)",
    "edit_history_tweet_ids": ["1234567890", "1234567891", "1234567893"]
  }
}
```

<Card title="Fundamentos de edición de Posts" icon="https://mintcdn.com/x-preview/szd6PKNMlRQoyyAo/icons/xds/icon-history.svg?fit=max&auto=format&n=szd6PKNMlRQoyyAo&q=85&s=6afe17587c08ee621e37afde19a07ff1" href="/x-api/fundamentals/edit-posts" width="24" height="24" data-path="icons/xds/icon-history.svg">
  Aprende más sobre las ediciones de Posts
</Card>

***

## Cómo empezar

<Note>
  **Requisitos previos**

  * Una [cuenta de desarrollador](https://developer.x.com/en/portal/petition/essential/basic-info) aprobada
  * Un [Project y App](/resources/fundamentals/developer-apps) en la Developer Console
  * El [Bearer Token](/resources/fundamentals/authentication) de tu App
</Note>

<CardGroup cols={2}>
  <Card title="Quickstart" icon="https://mintcdn.com/x-preview/oR-aRNyj1BKPJtxM/icons/xds/icon-rocket.svg?fit=max&auto=format&n=oR-aRNyj1BKPJtxM&q=85&s=b978d7a9225de31709efbbed5b84e92d" href="/x-api/posts/filtered-stream/quickstart" width="24" height="24" data-path="icons/xds/icon-rocket.svg">
    Conéctate al stream en minutos
  </Card>

  <Card title="Construir una regla" icon="https://mintcdn.com/x-preview/szd6PKNMlRQoyyAo/icons/xds/icon-filter.svg?fit=max&auto=format&n=szd6PKNMlRQoyyAo&q=85&s=5d59aff402c1f2aeae0e9e44bb23400e" href="/x-api/posts/filtered-stream/integrate/build-a-rule" width="24" height="24" data-path="icons/xds/icon-filter.svg">
    Aprende la sintaxis de las reglas
  </Card>

  <Card title="Referencia de operadores" icon="list-check" href="/x-api/posts/filtered-stream/integrate/operators">
    Todos los operadores disponibles
  </Card>

  <Card title="Código de ejemplo" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    Ejemplos de código funcional
  </Card>
</CardGroup>

***

## Temas avanzados

<CardGroup cols={2}>
  <Card title="Manejo de desconexiones" icon="plug" href="/x-api/fundamentals/handling-disconnections">
    Reconéctate de forma controlada
  </Card>

  <Card title="Capacidad de alto volumen" icon="gauge-high" href="/x-api/fundamentals/high-volume-capacity">
    Maneja un alto rendimiento
  </Card>

  <Card title="Recuperación y redundancia" icon="https://mintcdn.com/x-preview/cfyQtgCdwk8p69aa/icons/xds/icon-shield-keyhole.svg?fit=max&auto=format&n=cfyQtgCdwk8p69aa&q=85&s=a0e05514090c8a6af232297bfb9c4055" href="/x-api/fundamentals/recovery-and-redundancy" width="24" height="24" data-path="icons/xds/icon-shield-keyhole.svg">
    Construye aplicaciones resilientes
  </Card>

  <Card title="Coincidencia de Posts devueltos" icon="crosshairs" href="/x-api/posts/filtered-stream/integrate/matching-returned-tweets">
    Identifica qué reglas coincidieron
  </Card>
</CardGroup>
