# Subscribe to live alerts over MQTT

> Connect to the public broker from Python, subscribe to one county and print each NWS alert as it is published.

Developers · Tutorial · https://wxalerts.org/docs/developers/mqtt-quickstart/

You will write a short Python program that connects to the public WxAlerts
MQTT broker, subscribes to the alerts for one county and prints each alert as
it arrives. You need Python 3 and no account. Install the MQTT library first,
version 2.0 or newer:

```bash
pip install paho-mqtt
```

## 1. Write the client

Save this as `alerts.py`. It subscribes to El Dorado County, California, whose
SAME code is `006017`. The broker's credentials, `wxalerts` and `wxalerts`,
are public on purpose and the account is subscribe-only.

```python
import json
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, reason_code, properties):
    # One county: El Dorado, California.
    client.subscribe("wxalerts/nws/v1/same/006017/#", qos=1)

def on_message(client, userdata, msg):
    if not msg.payload:
        print("ended:", msg.topic)     # tombstone, not JSON
        return
    alert = json.loads(msg.payload)
    print(msg.topic)
    print(alert["event"], "|", alert["headline"], "| ends", alert["ends"])

client = mqtt.Client(
    mqtt.CallbackAPIVersion.VERSION2,
    client_id="my-unique-client",
    transport="websockets",
)
client.username_pw_set("wxalerts", "wxalerts")
client.tls_set()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mqtt.wxalerts.org", 443)
client.loop_forever()
```

The client talks MQTT over a WebSocket on port 443 with TLS, which is the only
way into the broker. Change `my-unique-client` to a name of your own, because
two clients that share a client ID kick each other off.

## 2. Run it

```bash
python3 alerts.py
```

A live alert is retained on the broker, so the alerts already in effect for the
county arrive the moment you subscribe. Each one prints its topic and a line
about the hazard:

```text
wxalerts/nws/v1/same/006017/0004
Winter Storm Warning | Winter Storm Warning issued November 12 at 12:33AM PST until November 14 at 10:00AM PST by NWS Reno NV | ends 2026-11-14T18:00:00+00:00
wxalerts/nws/v1/same/006017/0032
Lake Wind Advisory | Lake Wind Advisory issued November 11 at 11:52AM PST until November 13 at 10:00AM PST by NWS Reno NV | ends 2026-11-13T18:00:00+00:00
```

If the county has no alert in effect, nothing prints. Leave the program
running: a new alert prints when the NWS issues it, and `ended:` followed by a
topic prints when one ends. Stop it with Ctrl+C.

You now have a client that is told about alerts instead of asking for them.
To make it reliable enough to leave running, see
[Build a reliable MQTT client](/docs/developers/mqtt/best-practices/).
