Skip to content

LINE Messaging API#

Learn how to build a comprehensive LINE bot automation using n8n for customer service, notifications, and interactive messaging.

🎯 What You'll Build#

A LINE bot that can: - Handle text messages and rich content - Process interactive buttons and quick replies - Send notifications and broadcasts - Integrate with external services - Handle file uploads and media

πŸ“‹ Requirements#

  • LINE Developers account
  • LINE channel (Messaging API)
  • Webhook URL (HTTPS)
  • n8n instance running

πŸ”§ Workflow Overview#

Key Components#

  1. LINE Webhook Trigger - Receives messages and events
  2. Message Parser - Extracts content and user information
  3. Response Builder - Creates appropriate replies
  4. External Integrations - Connects to other services

πŸ“ Step-by-Step Guide#

1. Set Up LINE Developers Account#

  1. Go to LINE Developers Console - developers.line.biz
  2. Create a new provider - Your organization name
  3. Create a new channel - Select "Messaging API"
  4. Configure channel settings: - Channel name and description - App icon and cover image - Basic settings

2. Configure Messaging API#

  1. Get your Channel Access Token (Long-lived)
  2. Set your Webhook URL to your n8n instance
  3. Enable webhook verification - Use LINE's challenge
  4. Configure allowed IP addresses if needed

3. Set Up LINE Webhook Trigger#

  1. Add LINE Trigger node in n8n
  2. Configure with: - Channel Access Token: Your LINE channel token - Webhook Path: Unique endpoint path - Response Mode: Wait for response or respond immediately

4. Handle Different Message Types#

Text Messages#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Process incoming text
if ($json.message.type === 'text') {
  const userMessage = $json.message.text;
  const userId = $json.source.userId;

  return {
    userId: userId,
    message: userMessage,
    replyType: 'text'
  };
}

Image Messages#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Handle image uploads
if ($json.message.type === 'image') {
  const messageId = $json.message.id;
  // Download and process image
  return {
    userId: $json.source.userId,
    messageId: messageId,
    replyType: 'image_received'
  };
}

Postback Events#

1
2
3
4
5
6
7
8
9
// Handle button interactions
if ($json.postback) {
  const data = $json.postback.data;
  return {
    userId: $json.source.userId,
    action: data,
    replyType: 'postback'
  };
}

πŸ’¬ Message Types and Responses#

Text Messages#

1
2
3
4
{
  type: 'text',
  text: 'Hello! How can I help you today?'
}

Quick Replies#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  type: 'text',
  text: 'What would you like to do?',
  quickReply: {
    items: [
      {
        type: 'action',
        action: {
          type: 'message',
          label: 'Check Status',
          text: 'Check my status'
        }
      },
      {
        type: 'action',
        action: {
          type: 'message',
          label: 'Get Help',
          text: 'I need help'
        }
      }
    ]
  }
}

Buttons Template#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
  type: 'template',
  altText: 'Please select an option',
  template: {
    type: 'buttons',
    text: 'Choose your service:',
    actions: [
      {
        type: 'postback',
        label: 'Book Appointment',
        data: 'action=booking'
      },
      {
        type: 'postback',
        label: 'View Services',
        data: 'action=services'
      },
      {
        type: 'uri',
        label: 'Visit Website',
        uri: 'https://example.com'
      }
    ]
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
{
  type: 'template',
  altText: 'Browse our products',
  template: {
    type: 'carousel',
    columns: [
      {
        title: 'Product 1',
        text: 'Description of product 1',
        thumbnailImageUrl: 'https://example.com/image1.jpg',
        actions: [
          {
            type: 'postback',
            label: 'Details',
            data: 'product=1'
          }
        ]
      }
    ]
  }
}

πŸ”Œ External Service Integration#

Google Sheets Integration#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Save user messages to Google Sheets
const userData = {
  timestamp: new Date().toISOString(),
  userId: $json.source.userId,
  message: $json.message.text,
  replyMessage: responseText
};

// Map to Google Sheets columns
return {
  'Timestamp': userData.timestamp,
  'User ID': userData.userId,
  'Message': userData.message,
  'Response': userData.replyMessage
};

Database Storage#

1
2
3
4
5
6
7
// Store conversation history
const conversation = {
  userId: $json.source.userId,
  timestamp: new Date().toISOString(),
  incoming: $json.message,
  outgoing: response
};

Email Notifications#

1
2
3
4
5
6
// Send email notification for important messages
{
  to: '[email protected]',
  subject: `New LINE message from ${$json.source.userId}`,
  text: `Message: ${$json.message.text}\n\nUser ID: ${$json.source.userId}`
}

🎯 Use Case Examples#

Customer Service Bot#

  1. Greeting and routing

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    const greetings = ['hello', 'hi', 'ΰΈͺΰΈ§ΰΈ±ΰΈͺΰΈ”ΰΈ΅'];
    const message = $json.message.text.toLowerCase();
    
    if (greetings.includes(message)) {
      return {
        type: 'text',
        text: 'Hello! I\'m here to help. Please select:\n1. Product info\n2. Order status\n3. Support',
        quickReply: {
          items: [
            { type: 'action', action: { type: 'message', label: 'Products', text: 'products' } },
            { type: 'action', action: { type: 'message', label: 'Orders', text: 'orders' } },
            { type: 'action', action: { type: 'message', label: 'Support', text: 'support' } }
          ]
        }
      };
    }
    

  2. Order status checking

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    if ($json.message.text === 'orders') {
      // Check user's order history
      const orders = await getUserOrders($json.source.userId);
    
      if (orders.length > 0) {
        return {
          type: 'text',
          text: `You have ${orders.length} recent orders:\n${orders.map(o => `#${o.id}: ${o.status}`).join('\n')}`
        };
      } else {
        return {
          type: 'text',
          text: 'No recent orders found.'
        };
      }
    }
    

Appointment Booking#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
if ($json.postback?.data === 'action=booking') {
  return {
    type: 'template',
    altText: 'Select appointment time',
    template: {
      type: 'buttons',
      text: 'Available time slots:',
      actions: [
        { type: 'postback', label: 'Today 2PM', data: 'book=today-14:00' },
        { type: 'postback', label: 'Today 4PM', data: 'book=today-16:00' },
        { type: 'postback', label: 'Tomorrow 10AM', data: 'book=tomorrow-10:00' }
      ]
    }
  };
}

News Broadcasting#

  1. Collect subscribers

    1
    2
    3
    4
    5
    6
    7
    8
    if ($json.message.text === 'subscribe') {
      // Add user to subscription list
      await addSubscriber($json.source.userId);
      return {
        type: 'text',
        text: 'βœ… You\'ve been subscribed to our updates!'
      };
    }
    

  2. Broadcast messages (use scheduled trigger)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    // Get all subscribers
    const subscribers = await getSubscribers();
    
    // Create broadcast message
    const broadcast = {
      type: 'text',
      text: 'πŸ“’ Daily Update: Today\'s news and announcements...'
    };
    
    // Send to all subscribers
    for (const subscriber of subscribers) {
      await sendLineMessage(subscriber.userId, broadcast);
    }
    

πŸ§ͺ Testing Your LINE Bot#

Webhook Testing#

  1. Use ngrok for local development
  2. Test webhook endpoint with LINE's webhook validator
  3. Check message logs in LINE Developers Console
  4. Verify response format matches LINE API specifications

Test Scenarios#

  • Text messages with various content
  • Rich media (images, videos, audio)
  • Interactive buttons and quick replies
  • Postback data handling
  • Group chat interactions
  • Friend/unfriend events

πŸ” Troubleshooting#

Common Issues#

Webhook Not Responding - Check webhook URL is accessible - Verify SSL certificate validity - Ensure proper HTTP response (200 OK) - Check n8n execution logs

Message Not Sending - Validate Channel Access Token - Check rate limits (1000 messages/minute) - Verify message format - Check user has added bot as friend

Template Messages Not Displaying - Ensure proper template structure - Check image URLs are accessible - Verify action data format - Test on different devices

Debug Tools#

  1. LINE Developers Console - Webhook logs and analytics
  2. n8n Execution History - Workflow execution details
  3. Network monitoring - Request/response analysis
  4. API testing tools - Manual message testing

πŸ“Š Analytics and Insights#

Track User Engagement#

  • Message frequency per user
  • Popular features and commands
  • Response time analytics
  • User retention rates

Monitor Performance#

  • API response times
  • Error rates and types
  • Webhook success rates
  • Resource utilization

πŸ›‘οΈ Security and Privacy#

Data Protection#

  • Encrypt sensitive user data
  • Implement data retention policies
  • Comply with privacy regulations
  • Secure webhook endpoints

Access Control#

  • Validate source of webhook requests
  • Implement rate limiting
  • Monitor for abuse
  • Set up proper authentication

πŸŽ“ Advanced Features#

AI Integration#

  • Connect to chatbot APIs (ChatGPT, etc.)
  • Natural language processing
  • Sentiment analysis
  • Automated responses

E-commerce Integration#

  • Product catalogs
  • Order processing
  • Payment integration
  • Inventory management

Multi-language Support#

  • Language detection
  • Localized responses
  • Cultural considerations
  • Regional compliance

Related Tutorials: - LINE to Google Drive - File transfer automation - Form Submission - Form handling basics

Resources: - LINE Messaging API Documentation - LINE Developers Console - n8n LINE Integration