# Chatwoot Agent Bot for HOA Ledger IQ

Automated first-line support bot that triages customer conversations and escalates to Chris when needed.

## 🚀 Setup Instructions

### 1. Configure Chatwoot Bot

1. Go to **Settings → Bots** in your Chatwoot account
2. Click **Add Bot**
3. Fill in:
   - **Name:** HOA Ledger IQ Bot
   - **Avatar:** (optional upload logo)
   - **Webhook URL:** `http://your-server-ip:3001/webhook` (or use ngrok for local testing)
4. Save and copy the **Bot Token**

### 2. Connect Bot to Inbox

1. Go to the inbox you want to use (e.g., website widget)
2. Click **Bot Configuration**
3. Select the bot you just created
4. Click **Save**

### 3. Get Your Chatwoot API Token

1. Go to your **Profile Settings** (click avatar)
2. Scroll to **API Token** section
3. Copy your token

### 4. Configure the Bot

```bash
cd chatwoot-agent-bot
cp .env.example .env
```

Edit `.env` with your values:
```
CHATWOOT_URL=https://your-chatwoot-instance.com
CHATWOOT_API_TOKEN=your_api_token
CHATWOOT_ACCOUNT_ID=1
TELEGRAM_BOT_TOKEN=optional_for_notifications
TELEGRAM_CHAT_ID=optional_for_notifications
PORT=3001
```

### 5. Run the Bot

```bash
# Install dependencies (already done)
# npm install express body-parser axios dotenv

# Start the bot
node index.js
```

### 6. Test It

```bash
# Check health
curl http://localhost:3001/health

# Test webhook (simulate conversation)
curl -X POST http://localhost:3001/webhook \
  -H "Content-Type: application/json" \
  -d '{
    "event": "message_created",
    "data": {
      "conversation": {
        "id": 123,
        "meta": {
          "sender": {
            "name": "Test User"
          }
        }
      },
      "message": {
        "content": "Hello, I need help with billing",
        "message_type": "incoming"
      }
    }
  }'
```

## 🔧 How It Works

### Conversation Flow

1. **Customer sends message** → Chatwoot receives it
2. **Chatwoot sends webhook** → Bot receives `message_created` event
3. **Bot analyzes intent** → Detects: billing, technical, account, features, greeting
4. **Bot responds or escalates:**
   - **Greeting:** Friendly welcome, asks how to help
   - **Known topic:** Searches FAQ-KB.md, provides answer
   - **Technical issue:** Collects info, escalates to Chris
   - **Unknown:** Asks clarifying questions or escalates

### Escalation to Chris

When bot can't help:
- Changes conversation status from `pending` to `open`
- Assigns to human agent queue
- Sends Telegram notification (if configured):
  ```
  🔔 Support Escalation
  
  Customer: John Doe
  Reason: technical_issue
  Conversation: 123
  
  Jump in: [link to conversation]
  ```

### Knowledge Base

- Located at: `../FAQ-KB.md`
- Bot searches this doc for answers
- Organized by categories:
  - Getting Started
  - Billing & Pricing
  - Features & Usage
  - Technical & Integration
  - Account Management
  - Troubleshooting

**To add new entries:** Edit `FAQ-KB.md` following the template format.

## 🎯 Intent Detection

Current intents (easily expandable):

| Intent | Triggers | Action |
|--------|----------|--------|
| `greeting` | hello, hi, help | Welcome message |
| `billing` | price, cost, payment | Search KB or escalate |
| `technical_issue` | bug, error, broken | Collect info + escalate |
| `feature_request` | how to, feature, can I | Search KB |
| `account` | account, login, password | Search KB or escalate |
| `unknown` | anything else | Ask clarifying questions |

## 📈 Next Steps / Enhancements

- [ ] Add conversation memory (context across messages)
- [ ] Integrate with actual FAQ database (not just markdown)
- [ ] Add confidence scoring for intent detection
- [ ] Implement handoff back to bot (status: pending)
- [ ] Add analytics (response times, escalation rate)
- [ ] Multi-language support
- [ ] Rich interactive messages (buttons, cards)
- [ ] Integration with HOA Ledger IQ API for account lookups

## 🐛 Troubleshooting

**Bot not responding:**
- Check webhook URL is publicly accessible (use ngrok for local dev)
- Verify bot is connected to inbox
- Check bot logs for errors

**Escalations not working:**
- Verify API token has correct permissions
- Check account ID is correct
- Review Chatwoot conversation status flow

**Telegram notifications not sending:**
- Ensure bot token is valid
- Chat ID must be a number (get from @userinfobot)
- Bot must be started in chat first

## 📝 Logs

Bot logs to console. For production, consider:
- PM2 for process management
- Winston/Bunyan for logging
- Error tracking (Sentry)

---

**Maintained by:** Forge (Chris's SaaS Operations Bot)
**Version:** 1.0.0
**Last Updated:** 2026-04-01
