> 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/chat-history/python.md).

# Python

Fetch and render chat history with `fetch_chat_history`.

***

## Fetch on thread open

```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(
            notifier.fetch_chat_history(
                sender_id=MY_USER_ID,
                receiver_ids=[PEER_USER_ID],
            )
        ),
        on_message=on_message,
    )
    await notifier.connect()
    await asyncio.sleep(3600)

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

    if isinstance(body, dict) and isinstance(body.get("messages"), list):
        print(f"Loaded {len(body['messages'])} history messages")
        render_history(body["messages"])
        return

    if isinstance(body, dict) and body.get("type") == "text":
        append_live_message(msg.metadata, body)

asyncio.run(main())
```

***

## Merge history with live messages

```python
message_map: dict[str, dict] = {}

def upsert_message(msg: dict):
    msg_id = str(msg.get("id") or f"{msg.get('sender')}_{msg.get('timestamp')}")
    message_map[msg_id] = msg
    render_sorted(list(message_map.values()))

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):
                upsert_message(item)
        return

    if isinstance(body, dict) and body.get("type") == "text":
        upsert_message({
            "id": msg.metadata.id,
            "sender": msg.metadata.sender,
            "text": body.get("text"),
            "timestamp": msg.metadata.timestamp,
        })
```

***

## Refetch after reconnect

```python
async def on_reconnect(notifier: DNotifier):
    await notifier.connect()
    await notifier.fetch_chat_history(
        sender_id=MY_USER_ID,
        receiver_ids=[PEER_USER_ID],
    )
```

***

## Troubleshooting

| Issue                         | Check                                               |
| ----------------------------- | --------------------------------------------------- |
| No history in `on_message`    | Confirm `save_history=True` when messages were sent |
| Empty list                    | Thread may have no persisted messages yet           |
| `RuntimeError: Not connected` | Call after `connect()` succeeds                     |
| Duplicate messages            | Deduplicate by `metadata.id`                        |

***

## Learn more

* [Save history flag](https://dnotifier.gitbook.io/product-docs/chat/save-history.md)
* [Delete chat messages](https://dnotifier.gitbook.io/product-docs/chat/delete-messages/python.md)
