Logon8n中文教程

触发器与动作

掌握N8N工作流的触发机制和动作执行,构建响应式自动化系统

触发器与动作

触发器决定何时启动工作流,动作决定工作流执行什么操作。理解两者的配合使用,是构建高效自动化系统的基础。

🎯 触发器概述

触发器是工作流的起点,它们监听特定事件或按预设条件启动工作流执行。

触发器类型分类

类型特点适用场景常见节点
时间触发按时间计划执行定期任务、报表生成Cron, Schedule
事件触发响应外部事件实时处理、API集成Webhook, File Trigger
数据触发监听数据变化数据同步、状态监控Database Trigger
手动触发人工启动测试、临时任务Manual Trigger

⏰ 时间触发器详解

1. Cron 触发器

Cron 表达式提供精确的时间控制:

// 基本格式:分 时 日 月 周
// * * * * *

// 常用示例
"0 9 * * *"        // 每天上午9点
"30 14 * * 1-5"    // 工作日下午2:30
"0 0 1 * *"        // 每月1号午夜
"0 */6 * * *"      // 每6小时执行一次
"15 10 * * 1"      // 每周一上午10:15

实战案例:工作日早报

// Cron 配置
Expression: "0 8 * * 1-5"
Timezone: "Asia/Shanghai"

// 对应的工作流:
// 1. 获取昨日销售数据
// 2. 生成图表报告
// 3. 发送到管理群

2. Schedule 触发器

更直观的时间配置:

// 配置示例
Trigger Rules: [
  {
    hour: 9,
    minute: 0,
    dayOfWeek: [1, 2, 3, 4, 5]  // 周一到周五
  },
  {
    hour: 18,
    minute: 30,
    dayOfWeek: [1, 2, 3, 4, 5]  // 工作日下班时间
  }
]

3. Interval 触发器

简单的重复执行:

// 每5分钟检查一次
Interval: 5
Unit: "minutes"

// 适用场景:
// - 系统健康检查
// - 实时数据监控
// - 队列任务处理

🔔 事件触发器详解

1. Webhook 触发器

接收HTTP请求触发工作流:

// Webhook URL示例
https://your-n8n.com/webhook/order-created

// 请求数据结构
{
  "event": "order.created",
  "orderId": "ORD-12345",
  "customerId": "CUST-67890",
  "amount": 299.99,
  "items": [
    {
      "productId": "PROD-001",
      "quantity": 2,
      "price": 149.99
    }
  ],
  "timestamp": "2024-01-15T10:30:00Z"
}

安全配置

// 验证Webhook签名
const crypto = require('crypto');
const signature = $request.headers['x-webhook-signature'];
const payload = JSON.stringify($request.body);
const secret = $env.WEBHOOK_SECRET;

const expectedSignature = crypto
  .createHmac('sha256', secret)
  .update(payload)
  .digest('hex');

if (signature !== `sha256=${expectedSignature}`) {
  throw new Error('Invalid webhook signature');
}

2. File Trigger 触发器

监听文件系统变化:

// 配置示例
Path: "/uploads/invoices"
Watch For: ["add", "change"]
File Extensions: [".pdf", ".xlsx"]

// 触发事件类型
{
  "event": "add",           // 新文件添加
  "fileName": "invoice.pdf",
  "filePath": "/uploads/invoices/invoice.pdf",
  "fileSize": 245760,
  "timestamp": "2024-01-15T10:30:00Z"
}

处理流程示例

// 1. 文件上传触发
// 2. 读取文件内容
// 3. 提取关键信息
// 4. 数据入库
// 5. 发送处理通知

3. Email Trigger 触发器

监听邮箱收到新邮件:

// IMAP配置
Host: "imap.gmail.com"
Port: 993
Username: "[email protected]"
Password: "your-app-password"

// 触发条件
Folder: "INBOX"
Mark As Read: true
Download Attachments: true

邮件处理工作流

// 邮件数据结构
{
  "from": "[email protected]",
  "to": "[email protected]",
  "subject": "产品咨询",
  "body": "我想了解你们的产品...",
  "attachments": [
    {
      "fileName": "requirements.pdf",
      "contentType": "application/pdf",
      "size": 152048
    }
  ],
  "receivedAt": "2024-01-15T10:30:00Z"
}

🎬 动作节点详解

动作节点执行具体的业务操作,是工作流的执行者。

1. 通讯动作

邮件发送

// Gmail 节点配置
Operation: "Send Email"
To: "{{ $json.customerEmail }}"
Subject: "订单确认 - {{ $json.orderId }}"
Email Type: "HTML"

// 邮件模板
Body: `
<h2>订单确认</h2>
<p>亲爱的 {{ $json.customerName }},</p>
<p>您的订单 <strong>{{ $json.orderId }}</strong> 已确认。</p>
<p>订单金额:¥{{ $json.amount }}</p>
<p>预计送达:{{ $json.estimatedDelivery }}</p>
`

即时通讯

// 钉钉群通知
Webhook URL: "{{ $env.DINGTALK_WEBHOOK }}"
Message Type: "markdown"
Title: "系统告警"
Text: `
### 🚨 系统告警
- **服务器**: {{ $json.serverName }}
- **告警类型**: {{ $json.alertType }}
- **时间**: {{ $json.timestamp }}
- **详情**: {{ $json.message }}
`

// 企业微信通知
{
  "msgtype": "text",
  "text": {
    "content": "订单号:{{ $json.orderId }}\n客户:{{ $json.customerName }}\n金额:¥{{ $json.amount }}"
  },
  "mentioned_list": ["@all"]
}

2. 数据操作动作

数据库操作

-- 插入新记录
INSERT INTO orders (
  order_id, customer_id, amount, status, created_at
) VALUES (
  '{{ $json.orderId }}',
  '{{ $json.customerId }}',
  {{ $json.amount }},
  'pending',
  NOW()
);

-- 更新记录
UPDATE customers 
SET last_order_date = NOW(),
    total_orders = total_orders + 1,
    total_spent = total_spent + {{ $json.amount }}
WHERE customer_id = '{{ $json.customerId }}';

-- 查询数据
SELECT 
  customer_id,
  name,
  email,
  total_orders,
  total_spent
FROM customers 
WHERE customer_id = '{{ $json.customerId }}';

文件操作

// 创建文件
File Path: "/reports/daily-sales-{{ new Date().toISOString().split('T')[0] }}.json"
File Content: "{{ JSON.stringify($json.salesData, null, 2) }}"

// 读取文件
File Path: "/config/settings.json"
Property Name: "fileContent"

// 文件上传到云存储
// 使用 AWS S3 节点
Bucket: "company-reports"
Key: "sales/{{ $json.reportDate }}.xlsx"
Body: "{{ $json.excelData }}"

3. API 集成动作

REST API 调用

// 创建客户记录
Method: "POST"
URL: "https://api.crm.com/customers"
Headers: {
  "Authorization": "Bearer {{ $env.CRM_API_TOKEN }}",
  "Content-Type": "application/json"
}
Body: {
  "name": "{{ $json.customerName }}",
  "email": "{{ $json.customerEmail }}",
  "phone": "{{ $json.customerPhone }}",
  "source": "n8n_automation"
}

// 更新订单状态
Method: "PUT"
URL: "https://api.shop.com/orders/{{ $json.orderId }}"
Body: {
  "status": "processing",
  "trackingNumber": "{{ $json.trackingNumber }}",
  "updatedBy": "automation"
}

🔄 触发器与动作组合模式

1. 实时响应模式

场景:用户注册后立即发送欢迎邮件

// Webhook 触发器
POST /webhook/user-signup
{
  "userId": "12345",
  "email": "[email protected]",
  "name": "张三"
}

// ↓ 处理流程
// 1. 数据验证
// 2. 创建用户记录
// 3. 发送欢迎邮件
// 4. 添加到邮件列表
// 5. 发送内部通知

2. 定时批处理模式

场景:每日凌晨处理前一天的订单

// Cron 触发器:每天凌晨2点
"0 2 * * *"

// ↓ 处理流程
// 1. 查询昨日订单
// 2. 计算销售统计
// 3. 生成报表
// 4. 发送给管理层
// 5. 更新仪表板

3. 混合模式

场景:订单处理系统

// 多个触发器
1. Webhook: 新订单创建
2. Cron: 每小时检查待处理订单
3. File: 监听支付确认文件

// 统一的处理动作
1. 验证订单信息
2. 检查库存
3. 生成发货单
4. 发送确认邮件
5. 更新财务系统

🎛️ 高级触发器配置

1. 条件触发

// Webhook 条件过滤
// 只处理特定类型的事件
{{ $json.event === 'order.paid' && $json.amount > 1000 }}

// 时间条件
// 只在工作时间触发某些操作
{{ 
  const hour = new Date().getHours();
  return hour >= 9 && hour < 18;
}}

2. 触发器限流

// 防止频繁触发
const lastTrigger = $node.getWorkflowStaticData('node').lastTrigger || 0;
const now = Date.now();
const minInterval = 60000; // 1分钟

if (now - lastTrigger < minInterval) {
  throw new Error('Too frequent triggers');
}

$node.getWorkflowStaticData('node').lastTrigger = now;

3. 错误恢复触发

// 失败重试机制
const retryCount = $json.retryCount || 0;
const maxRetries = 3;

if (retryCount < maxRetries) {
  // 增加重试计数
  const updatedData = {
    ...$json,
    retryCount: retryCount + 1,
    lastRetryAt: new Date().toISOString()
  };
  
  // 延时后重新触发
  setTimeout(() => {
    // 触发重试逻辑
  }, Math.pow(2, retryCount) * 1000); // 指数退避
}

📊 实战项目:智能客服系统

系统架构

邮件触发 → 内容分析 → 智能分类 → 自动回复 → 人工升级

1. 邮件触发器配置

// Email Trigger 节点
IMAP Settings: {
  host: "imap.gmail.com",
  username: "[email protected]",
  folder: "INBOX"
}

Filter: {
  unread: true,
  to: "[email protected]"
}

2. 内容分析动作

// Function 节点:邮件内容分析
const emailContent = $json.body;
const subject = $json.subject;

// 关键词提取
const keywords = {
  'technical': ['bug', '错误', '无法', 'error', '故障'],
  'billing': ['账单', '付款', 'payment', '费用', '退款'],
  'general': ['咨询', '询问', 'question', '帮助']
};

let category = 'general';
let priority = 'normal';

// 分类逻辑
for (const [cat, words] of Object.entries(keywords)) {
  if (words.some(word => 
    emailContent.toLowerCase().includes(word) || 
    subject.toLowerCase().includes(word)
  )) {
    category = cat;
    break;
  }
}

// 优先级判断
if (emailContent.includes('紧急') || emailContent.includes('urgent')) {
  priority = 'high';
}

return [{
  json: {
    ...item.json,
    category: category,
    priority: priority,
    processedAt: new Date().toISOString()
  }
}];

3. 智能回复动作

// Switch 节点:根据分类路由

// 技术问题自动回复
if (category === 'technical') {
  // Gmail 节点
  const replyTemplate = `
    感谢您联系我们的技术支持。
    
    我们已收到您的技术问题反馈,工单号:${generateTicketId()}
    
    技术团队将在2小时内回复您。
    
    如果是紧急问题,请致电:400-xxx-xxxx
  `;
  
  return {
    to: $json.from,
    subject: `Re: ${$json.subject}`,
    body: replyTemplate
  };
}

4. 人工升级动作

// IF 节点:高优先级升级
if (priority === 'high' || category === 'billing') {
  // 钉钉通知
  const alertMessage = `
    🚨 高优先级客服工单
    
    客户:${customerEmail}
    主题:${subject}
    分类:${category}
    优先级:${priority}
    
    请及时处理!
  `;
  
  // 创建工单记录
  // MySQL 节点
  const insertTicket = `
    INSERT INTO support_tickets 
    (email, subject, category, priority, content, status, created_at)
    VALUES (?, ?, ?, ?, ?, 'open', NOW())
  `;
}

🎯 性能优化建议

1. 触发器优化

// 减少无效触发
// Webhook 增加验证
if (!$json.event || !$json.data) {
  return [];  // 空返回停止执行
}

// 批量处理而非单个触发
// 累积多个事件后一次性处理
const events = collectEvents();
if (events.length >= 10 || timeElapsed > 300000) {
  processEvents(events);
}

2. 动作优化

// 并行执行独立动作
// 使用 Split In Batches 节点并行处理

// 减少API调用
// 缓存常用数据
const cache = $node.getWorkflowStaticData('global').cache || {};

🚀 下一步学习

掌握触发器与动作后,继续学习:

  1. 调试测试 - 确保工作流稳定运行
  2. 循环迭代 - 处理批量数据
  3. 错误处理 - 构建健壮的工作流

触发器与动作是工作流的核心。合理配置触发条件,设计高效的执行动作,你就能构建出响应迅速、功能强大的自动化系统!