> 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/building-one-to-one-chat/python.md).

# Python

End-to-end pattern for a two-user chat thread.

***

## Chat client skeleton

```python
import asyncio
from dataclasses import dataclass
from typing import Optional
from dnotifier import DNotifier

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

@dataclass
class ChatMessage:
    sender: str
    text: str
    id: Optional[str] = None
    timestamp: Optional[int] = None

messages: list[ChatMessage] = []

async def open_thread(notifier: DNotifier, peer_id: str):
    await notifier.fetch_chat_history(
        sender_id=MY_USER_ID,
        receiver_ids=[peer_id],
    )

async def send_text(notifier: DNotifier, text: str):
    await notifier.send(
        sender_id=MY_USER_ID,
        receiver_id=PEER_USER_ID,
        data={"type": "text", "text": text},
        save_history=True,
    )

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(ChatMessage(
                    sender=str(item.get("sender", "")),
                    text=str(item.get("text", "")),
                    id=item.get("id"),
                ))
        render_thread(messages)
        return

    if isinstance(body, dict) and body.get("type") == "text":
        messages.append(ChatMessage(
            sender=msg.metadata.sender,
            text=str(body.get("text", "")),
            id=msg.metadata.id,
            timestamp=msg.metadata.timestamp,
        ))
        render_thread(messages)

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(open_thread(notifier, PEER_USER_ID)),
        on_message=on_message,
        on_disconnected=lambda code=None, reason=None: show_offline_state(),
    )
    await notifier.connect()
    await asyncio.sleep(3600)

def render_thread(items: list[ChatMessage]):
    # bind to your UI
    pass

def show_offline_state():
    pass

asyncio.run(main())
```

***

## CLI send loop

```python
async def chat_loop(notifier: DNotifier):
    while True:
        text = input("> ").strip()
        if not text:
            continue
        await send_text(notifier, text)
```

***

## Typing indicator (optional)

```python
await notifier.send(
    sender_id=MY_USER_ID,
    receiver_id=PEER_USER_ID,
    data={"type": "typing"},
    save_history=False,
)
```

***

## After reconnect

```python
async def on_reconnect(notifier: DNotifier):
    await notifier.connect()
    await open_thread(notifier, PEER_USER_ID)
```

→ [Error handling & reconnection](https://dnotifier.gitbook.io/product-docs/realtime-communication/error-handling.md)

***

## Learn more

* [Chat history](https://github.com/smartguy6666/dnotifier-sdk/tree/main/docs/chat/building-one-to-one-chat/chat-history/python.md)
* [Example: Minimal chat app](https://github.com/smartguy6666/dnotifier-sdk/tree/main/docs/chat/building-one-to-one-chat/example-minimal-chat/python.md)
