> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/chat/example-minimal-chat/python.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# Python

Full walkthrough: two-user 1:1 chat with history, send, and receive.

***

## Bob — receiver (Process 1)

Save as `bob.py`:

```python
import asyncio
from dnotifier import DNotifier

MY_USER_ID = "user-bob"
PEER_USER_ID = "user-alice"

messages: list[dict] = []

def print_message(m: dict):
    print(f"  {m.get('sender')}: {m.get('text')}")

def on_message(msg):
    body = msg.payload.to_json()

    if isinstance(body, dict) and isinstance(body.get("messages"), list):
        for item in body["messages"]:
            if isinstance(item, dict):
                messages.append(item)
        print(f"[history] {len(body['messages'])} messages loaded")
        for m in messages:
            print_message(m)
        return

    if isinstance(body, dict) and body.get("type") == "text":
        entry = {
            "sender": msg.metadata.sender,
            "text": body.get("text"),
            "timestamp": msg.metadata.timestamp,
        }
        messages.append(entry)
        print_message(entry)

async def main():
    notifier = DNotifier(
        app_id="your-app-id",
        secret="your-app-secret",
        transport="ws",
        user_id=MY_USER_ID,
        on_connected=lambda: asyncio.create_task(
            notifier.fetch_chat_history(
                sender_id=MY_USER_ID,
                receiver_ids=[PEER_USER_ID],
            )
        ),
        on_message=on_message,
        on_disconnected=lambda code=None, reason=None: print(f"Bob offline: {reason}"),
    )
    await notifier.connect()
    print("Bob online")
    await asyncio.sleep(3600)

asyncio.run(main())
```

Run: `python bob.py`

***

## Alice — sender with stdin (Process 2)

Save as `alice.py`:

```python
import asyncio
from dnotifier import DNotifier

MY_USER_ID = "user-alice"
PEER_USER_ID = "user-bob"

async def main():
    notifier = DNotifier(
        app_id="your-app-id",
        secret="your-app-secret",
        transport="ws",
        user_id=MY_USER_ID,
        on_connected=lambda: asyncio.create_task(_on_connected(notifier)),
        on_message=on_message,
        on_disconnected=lambda code=None, reason=None: print(f"Alice offline: {reason}"),
    )
    await notifier.connect()
    print("Alice online — type a message and press Enter")

    loop = asyncio.get_event_loop()
    while True:
        line = await loop.run_in_executor(None, input, "> ")
        text = line.strip()
        if not text:
            continue
        try:
            await notifier.send(
                sender_id=MY_USER_ID,
                receiver_id=PEER_USER_ID,
                data={"type": "text", "text": text},
            )
            print(f"→ you: {text}")
        except Exception as e:
            print(f"Send failed: {e}")

async def _on_connected(notifier):
    print("Alice online — type a message and press Enter")
    await notifier.fetch_chat_history(
        sender_id=MY_USER_ID,
        receiver_ids=[PEER_USER_ID],
    )

def on_message(msg):
    body = msg.payload.to_json()
    if isinstance(body, dict) and isinstance(body.get("messages"), list):
        print(f"[history] {len(body['messages'])} messages")
        return
    if isinstance(body, dict) and body.get("type") == "text":
        print(f"← {msg.metadata.sender}: {body.get('text')}")

asyncio.run(main())
```

Run: `python alice.py`

***

## Expected flow

1. Start bob → `Bob online`
2. Start alice → `Alice online`
3. Alice types `Hello Bob!` → bob prints the message
4. Restart alice → `[history]` shows prior messages

***

## Troubleshooting

| Issue                         | Fix                                                 |
| ----------------------------- | --------------------------------------------------- |
| Bob never receives            | Same `app_id`; bob must be running                  |
| Empty history                 | First conversation — history fills after first send |
| `RuntimeError: Not connected` | Await `connect()` before send                       |

***

## Learn more

* [Building 1:1 chat](https://dnotifier.gitbook.io/product-docs/chat/building-one-to-one-chat/python.md)
* [Chat UI patterns](https://dnotifier.gitbook.io/product-docs/chat/ui-patterns.md)
