# Triggers & Events

> Configure event-based messaging with contact triggers, webhooks, and custom events

Source: https://edesy.in/docs/waflow/automations/triggers

Triggers are the starting point for every automation in Waflow. They define when an automation should activate and for which contacts. Understanding trigger types and configuration options is essential for creating effective automated workflows.

## What are Triggers?

A trigger is an event or condition that starts an automation. When the trigger condition is met, the automation begins executing its sequence of actions for the relevant contact.

### How Triggers Work

```
Event Occurs → Trigger Activated → Conditions Checked → Automation Starts
      ↓              ↓                    ↓                   ↓
  Contact        Is this the        Does contact         Execute first
  added          right trigger?      meet criteria?       action
```

### Trigger Components

| Component | Description |
|-----------|-------------|
| **Event Type** | What action activates the trigger |
| **Conditions** | Additional criteria that must be met |
| **Filters** | Limit which contacts activate the trigger |
| **Timing** | When the trigger should be active |

## Trigger Types

Waflow supports multiple trigger types for different use cases.

### Contact Added

Activates when a new contact is added to your workspace.

**Configuration Options:**
- Source filter (manual, import, API, form)
- Tag filter (must have specific tags)
- List filter (added to specific list)

**Use Cases:**
- Welcome messages
- Onboarding sequences
- Lead magnet delivery

**Example:**
```
Trigger: Contact Added
Filter: Source = "Landing Page Form"
Action: Send welcome message with free guide
```

### Tag Applied

Activates when a specific tag is added to a contact.

**Configuration Options:**
- Specific tag or any from a list
- Added by (manual, automation, import)
- Exclude contacts already in automation

**Use Cases:**
- Interest-based messaging
- Status change notifications
- Qualification workflows

**Example:**
```
Trigger: Tag Applied
Tag: "Hot Lead"
Action: Send sales rep notification and follow-up message
```

### Tag Removed

Activates when a tag is removed from a contact.

**Configuration Options:**
- Specific tag or any from a list
- Removed by (manual, automation)

**Use Cases:**
- Status change handling
- Re-engagement when downgraded
- Cleanup workflows

### Custom Field Updated

Activates when a contact's custom field changes.

**Configuration Options:**
- Specific field to monitor
- Change type (any change, specific value, value increased/decreased)
- Previous and new value conditions

**Use Cases:**
- Lifecycle stage changes
- Score threshold notifications
- Profile completion rewards

**Example:**
```
Trigger: Custom Field Updated
Field: "Lead Score"
Condition: Value >= 80
Action: Start high-intent sequence
```

### Date-Based Triggers

Activates based on dates stored in contact fields.

**Configuration Options:**
- Date field to monitor
- Timing (on date, before date, after date)
- Offset (days before/after)
- Recurrence (annual, one-time)

**Use Cases:**
- Birthday messages
- Subscription renewals
- Appointment reminders
- Anniversary celebrations

**Example:**
```
Trigger: Date Field
Field: "Birthday"
Timing: On date, annually
Action: Send birthday greeting with special offer
```

### Form Submission

Activates when a contact submits a form.

**Configuration Options:**
- Specific form or any form
- Form field conditions
- Submission source

**Use Cases:**
- Form response follow-up
- Registration confirmation
- Survey completion rewards

### Message Response

Activates when a contact replies to a message.

**Configuration Options:**
- Response to specific campaign
- Response to specific automation
- Keyword detection
- Any response

**Use Cases:**
- Interactive conversations
- Feedback collection
- Opt-in confirmation

**Example:**
```
Trigger: Message Response
Contains Keyword: "YES"
Previous Message: Opt-in request
Action: Confirm subscription and add to list
```

### Inactivity Trigger

Activates after a period of no contact interaction.

**Configuration Options:**
- Inactivity period (days, weeks, months)
- Interaction types to monitor (opens, clicks, replies)
- Previous activity required

**Use Cases:**
- Re-engagement campaigns
- Win-back sequences
- List cleaning workflows

**Example:**
```
Trigger: Inactivity
Period: 30 days no opens or clicks
Condition: Was active in previous 90 days
Action: Start re-engagement sequence
```

## Webhook Triggers

Webhook triggers allow external systems to start automations via HTTP requests.

### Setting Up Webhook Triggers

1. Navigate to **Automations** > **Create Automation**
2. Select **Webhook** as the trigger type
3. Configure the webhook:
   - Generate unique webhook URL
   - Set authentication (optional but recommended)
   - Define expected payload structure

### Webhook URL Format

```
https://api.waflow.com/webhooks/automation/{automation_id}?key={api_key}
```

### Payload Structure

Send data to the webhook as JSON:

```json
{
  "phone": "+919876543210",
  "event": "order_placed",
  "data": {
    "order_id": "ORD-12345",
    "amount": 1500,
    "items": ["Product A", "Product B"]
  }
}
```

### Mapping Webhook Data

Map incoming data to contact fields and automation variables:

1. Open webhook trigger settings
2. Click **Data Mapping**
3. Map payload fields:
   - `phone` → Contact identifier
   - `data.order_id` → Variable `{{order_id}}`
   - `data.amount` → Variable `{{order_amount}}`

### Webhook Authentication

Secure your webhook endpoints:

**API Key Authentication:**
- Include API key in query parameter or header
- Rotate keys periodically
- Use different keys for different integrations

**Signature Verification:**
- Waflow can verify HMAC signatures
- Configure shared secret in webhook settings
- Include signature in request header

> **Warning:** Always use authentication for webhook triggers. Unsecured webhooks can be exploited to send unauthorized messages.

### Common Webhook Integrations

| Source | Event | Use Case |
|--------|-------|----------|
| Shopify | Order placed | Order confirmation |
| WooCommerce | Cart abandoned | Recovery message |
| Stripe | Payment received | Receipt delivery |
| Calendly | Appointment booked | Confirmation message |
| Typeform | Form submitted | Lead follow-up |
| Custom App | Any event | Custom workflows |

## Custom Events

Custom events allow you to define and track specific actions relevant to your business.

### Creating Custom Events

1. Go to **Settings** > **Custom Events**
2. Click **Create Event**
3. Configure the event:
   - Event name (e.g., "course_completed")
   - Description
   - Expected properties

### Tracking Custom Events

Track events via API:

```bash
curl -X POST https://api.waflow.com/events \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "phone": "+919876543210",
    "event": "course_completed",
    "properties": {
      "course_name": "Marketing 101",
      "completion_date": "2025-01-15",
      "score": 95
    }
  }'
```

### Using Custom Events as Triggers

1. Create a new automation
2. Select **Custom Event** as trigger type
3. Choose your custom event
4. Add property conditions (optional)
5. Build your automation

**Example:**
```
Trigger: Custom Event
Event: "course_completed"
Condition: score >= 80
Action: Send congratulations and certificate
```

## Trigger Conditions

Add conditions to control which contacts activate triggers.

### Available Condition Types

**Contact Properties:**
- Has/doesn't have specific tag
- Custom field equals/contains value
- Phone number matches pattern
- Contact created date

**Engagement History:**
- Has received specific campaign
- Has opened/clicked recent message
- Response count
- Last activity date

**Segment Membership:**
- Is/is not in segment
- Entered segment within timeframe

### Condition Logic

Combine conditions with AND/OR logic:

```
Trigger: Tag Applied ("Interested")
AND Contact does NOT have tag "Customer"
AND Custom field "Lead Source" equals "Website"
AND Contact is in segment "Target Region"
```

### Exclusion Filters

Prevent specific contacts from triggering:

1. Open trigger settings
2. Navigate to **Exclusions**
3. Add exclusion conditions:
   - Already in this automation
   - Completed this automation in last X days
   - Has specific tag

## Trigger Timing

Control when triggers are active.

### Schedule Windows

Limit when automations can start:

1. Open trigger settings
2. Enable **Schedule Window**
3. Configure:
   - Active days (e.g., Monday-Friday)
   - Active hours (e.g., 9 AM - 6 PM)
   - Timezone

### Quiet Hours

Delay trigger activation during off-hours:

- If triggered during quiet hours, action queues for next available time
- Prevents messages at inappropriate times

### Trigger Limits

Prevent overwhelming contacts:

| Setting | Description |
|---------|-------------|
| Cooldown | Minimum time between trigger activations |
| Max Per Day | Maximum triggers per contact per day |
| Lifetime Limit | Total times a contact can trigger |

## Testing Triggers

### Manual Trigger Testing

Test without affecting real contacts:

1. Open the automation
2. Click **Test Trigger**
3. Enter test contact details
4. Verify automation flow

### Test Mode

Run automations in test mode:

- Messages go only to admin contacts
- All actions are logged
- No real messages sent to contacts

### Webhook Testing

Test webhook triggers:

1. Copy your webhook URL
2. Use a tool like Postman or cURL
3. Send a test payload
4. Check automation logs for activation

```bash
curl -X POST "https://api.waflow.com/webhooks/automation/abc123?key=test_key" \
  -H "Content-Type: application/json" \
  -d '{"phone": "+919999999999", "test": true}'
```

## Monitoring Triggers

### Trigger Logs

View all trigger activations:

1. Go to **Automations** > select automation
2. Click **Logs**
3. Filter by:
   - Date range
   - Trigger status (activated, filtered, failed)
   - Contact

### Trigger Metrics

Track trigger performance:

| Metric | Description |
|--------|-------------|
| Activation Rate | Triggers activated / potential triggers |
| Filter Rate | Triggers blocked by conditions |
| Error Rate | Failed trigger attempts |
| Average Daily Triggers | Trend over time |

### Debugging Failed Triggers

Common issues and solutions:

| Issue | Cause | Solution |
|-------|-------|----------|
| Not triggering | Conditions too strict | Review and adjust conditions |
| Triggering too often | Conditions too loose | Add exclusion filters |
| Wrong contacts | Filter misconfiguration | Verify filter logic |
| Timing issues | Schedule conflicts | Check timezone and windows |

## Best Practices

### Trigger Design

1. **Start Specific**: Begin with narrow triggers, expand as needed
2. **Use Exclusions**: Prevent duplicate triggers for same contacts
3. **Add Cooldowns**: Avoid overwhelming contacts
4. **Document Purpose**: Note why each trigger exists

### Performance Tips

1. **Simplify Conditions**: Complex conditions slow processing
2. **Use Segments**: Pre-filter contacts with segments
3. **Batch Similar Triggers**: Combine when possible
4. **Monitor Regularly**: Watch for unexpected patterns

> **Tip:** Create a trigger naming convention that includes the type and purpose, e.g., "TAG_HotLead_SalesFollow" or "WEBHOOK_OrderPlaced_Confirm".

## Next Steps

- [Drip Sequences](https://edesy.in/docs/waflow/automations/drip-sequences) - Build multi-step flows
- [Integrations](https://edesy.in/docs/waflow/settings/integrations) - Connect external systems
- [Analytics](https://edesy.in/docs/waflow/analytics) - Track automation performance
