# Messaging

> Send and receive WhatsApp messages with Sendable.

Source: https://wav1.recrav.com/docs/learn/messaging

## Message Types [#message-types]

Sendable supports various message types for different use cases.

### Text Messages [#text-messages]

Simple text messages for notifications and conversations:

```json
{
  "to": "6281234567890",
  "text": "Hello! Your order #12345 has been shipped."
}
```

### Group Mentions [#group-mentions]

To send a real WhatsApp mention in a group, include the visible `@number` in
`text.content` and the full WhatsApp JID in `mentions`:

```json
{
  "chatId": "120363427458591243@g.us",
  "text": {
    "content": "asd @6285176702468"
  },
  "mentions": ["6285176702468@s.whatsapp.net"]
}
```

### Media Messages [#media-messages]

Send images, videos, documents:

```json
{
  "to": "6281234567890",
  "mediaUrl": "https://example.com/invoice.pdf",
  "mediaType": "document",
  "caption": "Your invoice for order #12345"
}
```

Supported media types:

* `image` - JPG, PNG
* `video` - MP4
* `audio` - MP3, OGG
* `document` - PDF, DOC, etc.

## Sending Messages [#sending-messages]

### Dashboard [#dashboard]

Send quick messages directly from the dashboard:

1. Go to your session
2. Click "Send Message"
3. Enter phone number
4. Type message or attach media
5. Send

### API [#api]

Send programmatically via API:

```bash
curl -X POST "https://api.sendable.dev/messages/send" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "6281234567890",
    "text": "Hello from API!"
  }'
```

## Message Status [#message-status]

Track message delivery status:

| Status      | Meaning                        |
| ----------- | ------------------------------ |
| `pending`   | Queued for sending             |
| `sent`      | Sent to WhatsApp servers       |
| `delivered` | Delivered to recipient's phone |
| `read`      | Recipient opened the message   |
| `failed`    | Could not be delivered         |

### Check Status via API [#check-status-via-api]

```bash
curl "https://api.sendable.dev/messages/{messageId}/status" \
  -H "x-api-key: YOUR_API_KEY"
```

### Real-time Updates [#real-time-updates]

Use webhooks to get instant status updates:

* `message.delivered` - Message arrived
* `message.read` - Message seen
* `message.failed` - Delivery failed

## Receiving Messages [#receiving-messages]

### Webhook Setup [#webhook-setup]

Configure webhook to receive incoming messages:

1. Go to session → Webhooks
2. Subscribe to `message.received` event
3. Your endpoint receives:

```json
{
  "event": "message.received",
  "data": {
    "messageId": "msg_incoming_456",
    "from": "6281234567890",
    "type": "text",
    "text": "Hi, I have a question about my order",
    "timestamp": "2026-03-02T10:30:00Z"
  }
}
```

### Auto-Reply [#auto-reply]

Example: Automatic response to incoming messages:

```javascript
app.post('/webhook', (req, res) => {
  const { event, data } = req.body
  
  if (event === 'message.received') {
    // Send auto-reply
    sendMessage(data.from, 
      "Thanks for your message! We'll respond shortly.")
  }
  
  res.sendStatus(200)
})
```

## Use Cases [#use-cases]

### Customer Support [#customer-support]

Two-way conversation handling:

```javascript
// Store incoming messages
if (event === 'message.received') {
  await createTicket({
    customer: data.from,
    message: data.text,
    timestamp: data.timestamp
  })
}

// Notify agents
await notifySupportTeam(newTicket)
```

### Order Notifications [#order-notifications]

Automated order updates:

```javascript
// Order confirmation
await sendMessage(customerPhone, 
  `Order #${orderId} confirmed! Total: $${amount}`)

// Shipping notification
await sendMessage(customerPhone,
  `Order #${orderId} shipped! Track: ${trackingUrl}`)

// Delivery confirmation
await sendMessage(customerPhone,
  `Order #${orderId} delivered! Enjoy your purchase.`)
```

### Appointment Reminders [#appointment-reminders]

Reduce no-shows with reminders:

```javascript
// 24 hours before
await sendMessage(patientPhone,
  `Reminder: Appointment with Dr. Smith tomorrow at ${time}`)

// 1 hour before
await sendMessage(patientPhone,
  `Your appointment starts in 1 hour. See you soon!`)
```

### OTP Verification [#otp-verification]

Secure authentication codes:

```javascript
// Generate and send OTP
const otp = generateOTP()
await sendMessage(userPhone, 
  `Your verification code is: ${otp}. Valid for 5 minutes.`)
```

## Message Templates [#message-templates]

Create reusable message formats:

```javascript
const templates = {
  welcome: (name) => `Hi ${name}! Welcome to our service.`,
  
  orderShipped: (orderId, tracking) => 
    `Order #${orderId} shipped! Track: ${tracking}`,
  
  appointmentReminder: (doctor, time) =>
    `Reminder: Appointment with ${doctor} at ${time}`
}

// Usage
await sendMessage(phone, templates.welcome('John'))
```

## Best Practices [#best-practices]

### Phone Number Format [#phone-number-format]

Always use international format:

* ✅ `6281234567890` (Indonesia)
* ❌ `081234567890` (missing country code)
* ❌ `+6281234567890` (remove the +)

### Message Length [#message-length]

* Keep messages concise
* WhatsApp has no strict limit, but split long messages
* Use formatting (bold, italic) for emphasis

### Timing [#timing]

* Business hours for promotional messages
* Immediate for OTPs and alerts
* Consider timezone of recipient

### Personalization [#personalization]

Include customer details:

```
Hi {name}, your order #{orderId} is ready!
```

### Error Handling [#error-handling]

Always handle delivery failures:

```javascript
try {
  const result = await sendMessage(phone, text)
  
  if (!result.success) {
    // Log failure
    await logFailedMessage(phone, text, result.error)
    
    // Retry or notify
    if (isRetryable(result.error)) {
      await retryLater(phone, text)
    }
  }
} catch (error) {
  await notifyAdmin(error)
}
```

## Rate Limits [#rate-limits]

Be aware of sending limits:

| Plan       | Messages/Hour | Notes            |
| ---------- | ------------- | ---------------- |
| Free       | 100           | Best for testing |
| Starter    | 1,000         | Small businesses |
| Pro        | 10,000        | High volume      |
| Enterprise | Custom        | Unlimited        |

Monitor your usage in the dashboard.
