# 即時推播 (https://nolantw.github.io/tdx/guides/mqtt/)

需要[選用功能](/#選用功能) `mqtt`。在 TDX 會員中心取得 MQTT 的 Client ID、帳號與密碼，並設為環境變數 `TDX_MQTT_CLIENT_ID`、`TDX_MQTT_USERNAME` 與 `TDX_MQTT_PASSWORD`。這組帳號與 API 金鑰不同。

```python
from tdx.mqtt import Subscriber, Topics

for message in Subscriber().listen(Topics.metro_alerts()):
    for alert in message.records:
        print(message.topic, alert.title)
```

`listen()` 持續等待訊息，斷線後自動重新連線與訂閱。同一組帳號只能有一個連線。

| 名稱 | 內容 |
| --- | --- |
| `bus_news` | 公車最新消息，縣市傳入 `None` 則為公路客運 |
| `bus_alerts` | 公車營運通阻，縣市傳入 `None` 則為公路客運 |
| `railway_alerts` | 臺鐵營運通阻 |
| `high_speed_alerts` | 高鐵營運通阻 |
| `metro_alerts` | 捷運營運通阻，可指定系統 |
| `ship_alerts` | 國際航線營運通阻 |

## 非同步

```python
from contextlib import aclosing

from tdx.mqtt import AsyncSubscriber, Topics


async def watch() -> None:
    async with aclosing(AsyncSubscriber().listen(Topics.railway_alerts())) as messages:
        async for message in messages:
            print(message.records)
```

所有參數與欄位見[即時推播 API](/reference/mqtt)。