---
name: wechat-media-retry
description: WeChat media delivery with exponential backoff retry pattern for Hermes gateway CDN 500 errors
category: productivity
---

# WeChat Media Delivery with Retry Pattern

## Context
When sending media files (images, audio) via WeChat through Hermes gateway's `send_message_tool`, the CDN upload often returns HTTP 500 on the first attempt. Retry with exponential backoff is required.

## Symptom
```
[Weixin] send_document failed to=wxid_xxx: CDN upload HTTP 500: 
{"error": "Weixin media send failed: CDN upload HTTP 500: "}
```

## Solution: Retry with Exponential Backoff

```python
from tools.send_message_tool import send_message_tool

def send_wechat_media(filepath, chat_id, max_retries=5, initial_delay=8):
    """
    Send media file to WeChat with exponential backoff retry.
    """
    import time
    
    args = {
        'action': 'send',
        'message': f'MEDIA:{filepath}',
        'target': f'weixin:{chat_id}'
    }
    
    for attempt in range(max_retries):
        result = send_message_tool(args)
        
        # Success
        if result.get('success'):
            return result
        
        # Exponential backoff: 8, 16, 32, 64, 128 seconds
        if attempt < max_retries - 1:
            delay = initial_delay * (2 ** attempt)
            time.sleep(delay)
    
    return {"error": "All retries failed"}
```

## Key Findings
1. **CDN 500 is transient** - Usually succeeds on 2nd or 3rd retry
2. **File must exist** - Media path must be absolute, file must be on disk
3. **Target format**: `weixin:{chat_id}` (not `weixin:chat_id@im.wechat`)

## Quick One-liner (Bash)
```bash
cd /root/.hermes/hermes-agent && python3 -c "
import time
from tools.send_message_tool import send_message_tool

filepath = '/root/.hermes/workspace/cat_sunset.png'
chat_id = 'o9cq801Q4BDVa20m46H0KTKRUOjo@im.wechat'

for attempt in range(5):
    r = send_message_tool({'action':'send','message':f'MEDIA:{filepath}','target':f'weixin:{chat_id}'})
    if r.get('success'):
        print('Sent!')
        break
    time.sleep(8 * (2 ** attempt))
"
```

## Files Used
- Send tool: `/root/.hermes/hermes-agent/tools/send_message_tool.py`
- WeChat platform: `/root/.hermes/hermes-agent/gateway/platforms/weixin.py`
