Build a Thai Line Chatbot with Google Sheets Memory using n8n

Frustrated with managing chat histories manually in Line chatbot? This n8n workflow automates conversation memory using Google Sheets, keeping your Thai chatbot responsive and context-aware effortlessly.
webhook
agent
googleSheets
+6
Workflow Identifier: 1992
NODES in Use: Webhook, AI Agent, Google Gemini Chat Model, Edit Fields, HTTP Request, Google Sheets, Set, Code, Sticky Note

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

1. Opening Problem Statement

Meet “ลลิตา,” a Thai-speaking Line chatbot designed to assist guitar enthusiasts in their conversations. Imagine Chat Manager Ploy, who runs a Line Official Account for a local guitar shop in Bangkok. Every day, Ploy receives dozens of customer inquiries about guitar recommendations, repair tips, and music lessons. But the chatbot loses context from earlier conversations, making responses repetitive and less helpful.

Ploy spends hours daily manually reviewing chat logs to keep track of customer history, wasting precious time and risking mistakes in customer engagement. This fragmented history causes frustration for customers expecting personalized, fluid conversations, leading to lost opportunities and diminished trust.

This is where our n8n automation shines—enabling a Line chatbot to remember previous conversations using Google Sheets as a dynamic memory bank. It saves Ploy countless hours by automating chat history fetching, cleaning, and updating, all while delivering context-aware AI chatbot replies.

2. What This Automation Does

This workflow combines Line Official API, Google Sheets, and AI models to create a responsive Thai language chatbot named “ลลิตา.” Here’s exactly what happens when this automation runs:

  • Receives and processes new incoming Line chat messages via a secured webhook trigger.
  • Extracts user ID and message text to uniquely identify and personalize chat history.
  • Fetches past conversation snippets stored in Google Sheets to provide continuous context.
  • Constructs a dynamic contextual prompt blending new user input with historical chat data.
  • Generates a polite, contextually relevant reply using a Google Gemini AI chat model via an AI Agent node.
  • Saves updated conversation history back into Google Sheets, neatly dividing long chat logs into archive chunks to avoid size limits.
  • Replies to the user in Line instantly with the generated AI response via Line Messaging API.

By harnessing this automation, Chat Manager Ploy can save up to several hours daily previously spent on manual chat review and data entry. The conversational memory ensures relevant replies, enhancing customer satisfaction and engagement effectively.

3. Prerequisites ⚙️

  • n8n account with access to create workflows and provide credentials.
  • Line Official Account configured with messaging API enabled and channel access token.
  • Google account with Google Sheets access to store chat history (Google Sheets node with OAuth credentials).
  • Google Gemini API access (Google Palm API credentials) for AI chat response generation.
  • Basic familiarity with Line Webhook setup and Google Sheets structure.

4. Step-by-Step Guide

Step 1: Set up the Webhook to Receive Line Messages

Navigate to the Webhook node in n8n. Configure the HTTP Method as POST and set the path to guitarpa (or your chosen endpoint). This webhook listens for incoming messages from the Line Official Account.

You should test the webhook by sending a sample message through Line API and watch for JSON payloads containing message text and reply token.

Common Mistake: Forgetting to expose the webhook publicly or mismatching the path in Line’s webhook URL.

Step 2: Extract and Format Incoming Message Data

Use the Edit Fields node to capture necessary fields from the webhook payload. Assign the user’s message, reply token, and user ID to new fields for easy reference downstream.

For example, map body.events[0].message.text and body.events[0].replyToken from the Webhook’s JSON.

This structuring allows future nodes to work with clean, direct data.

Step 3: Fetch Chat History From Google Sheets

Configure the Get History Google Sheets node to search for the user’s chat history using their unique user ID as the lookup value. This ensures personalized memory retrieval.

Ensure your sheet includes columns like UserID, History, and up to four History_Archive_X columns for overflow chat archive.

This is essential to maintain conversation context and seamless dialogue continuation.

Step 4: Prepare the AI Prompt Including Chat History

In the Prepare Prompt node (a Set node), build a prompt string dynamically. Concatenate previous chat history fields with the new incoming user message, prefixed to instruct the AI to respond as a polite, helpful chatbot named “ลลิตา” in Thai.

Example snippet:
"คุณคือลลิตา แชทบอทภาษาไทยที่สุภาพและเป็นมิตร ตอบตามบริบทของการสนทนา:n" + history archives + user message + "nลลิตา: "

This clever prompt construction is the key to personalized, context-aware AI replies.

Step 5: Generate AI Response Using Google Gemini Model

Route the prepared prompt to the AI Agent node configured with a Google Gemini chat model. This node sends the prompt to Google Palm API and returns the AI-generated reply text.

If you want to customize responses, tweak the system message defining the AI persona “ลลิตา” and timezone in the AI Agent node settings.

Step 6: Manage Chat History Size and Archive Old Data

The Split History node contains JavaScript code that appends the newest exchange of user and bot dialogue to existing history, then checks length against a threshold (~35,000 characters). If exceeded, it archives older chat portions into four dedicated archive columns in the Google Sheet to avoid data loss.

This clever chunking process prevents Google Sheets cell limits from truncating important conversation logs.

Step 7: Save Updated Chat History Back to Google Sheets

Use the Save History Google Sheets node with “appendOrUpdate” operation keyed on UserID. This keeps the user’s chat history current and accessible for future messages.

Step 8: Reply to User via Line Messaging API

The HTTP Request node posts the AI response back to the Line platform using the reply token. It sends a JSON payload with the reply text, completing the chat loop.

Make sure to set the Authorization header with your Line channel access token and content-type to application/json.

Common Mistake: Incorrectly structuring the JSON or missing authorization results in message delivery failure.

5. Customizations ✏️

  • Adjust AI Persona: In the AI Agent node parameters, edit the systemMessage to change the chatbot’s style or language tone. For example, make it more formal or casual according to your audience.
  • Expand History Archive: Add extra columns in your Google Sheet (e.g., History_Archive_5) and extend the Split History node JavaScript code to handle more archive chunks for very long conversations.
  • Multi-Language Support: Modify the prompt construction in the Prepare Prompt node to detect or switch languages dynamically based on user metadata from the webhook.
  • Alternative Response Models: Swap the Google Gemini model in the AI Agent node for another AI model supported by LangChain in n8n if desired.
  • Custom Webhook Path: Change the webhook path parameter to integrate this chatbot on different Line Official Accounts or environments.

6. Troubleshooting 🔧

  • Problem: “Webhook not receiving data from Line”
    Cause: Webhook URL is incorrect or not publicly accessible.
    Solution: Verify webhook URL matches the endpoint in Line Developer Console, expose n8n webhook publicly using tools like ngrok or proper hosting.
  • Problem: “AI Agent response is empty or error in API call”
    Cause: Incorrect API credentials, or malformed prompt.
    Solution: Double-check Google Palm API credentials, ensure the prompt is properly formatted and within model limits.
  • Problem: “Google Sheets update fails or duplicates data”
    Cause: Mismatched UserID formatting, or incorrect setting in appendOrUpdate operation.
    Solution: Ensure UserID columns match exactly in Google Sheets and n8n mapping, test with unique user ID values.
  • Problem: “Line API 401 Unauthorized on message reply”
    Cause: Expired or invalid Line channel access token.
    Solution: Renew channel token in Line Developer Console and update it in HTTP Request node headers.

7. Pre-Production Checklist ✅

  • Confirm n8n workflow is active and webhook node listens on correct URL and method.
  • Validate Google Sheets structure matches columns: UserID, History, History_Archive_1-4, LastUpdated.
  • Test messages through Line to confirm webhook triggers and AI replies correctly.
  • Check AI Agent node credentials and model availability.
  • Ensure HTTP Request node header includes valid Line channel access token.
  • Backup Google Sheets data and workflow before production launch.

8. Deployment Guide

Activate the workflow by toggling it ON in your n8n editor. Configure the Line Official Account webhook URL to point to your n8n webhook endpoint with the matching path. Monitor the workflow executions for errors or latency in the n8n dashboard.

Plan for periodic updates of Google Sheets API credentials and Line channel token to maintain uninterrupted service.

9. FAQs

  • Can I use a different spreadsheet service instead of Google Sheets?
    Currently, this workflow is tailored for Google Sheets because of its API ease and integration in n8n. However, with adjustments, other services like Airtable could be integrated.
  • Does the chatbot consume many Google Palm API credits?
    The usage depends on chat volume but expect a per-message charge with Google Palm API beyond free tiers.
  • Is my conversation data secure?
    Chat histories are stored in Google Sheets and accessed via OAuth credentials, ensure your n8n instance and credentials are secured properly.
  • Can the chatbot handle hundreds of users simultaneously?
    Yes, but you should monitor API rate limits and Google Sheets read/write quotas to avoid throttling.

10. Conclusion

By following this tutorial, you’ve built a Thai language Line chatbot that intelligently remembers and builds on past conversations using Google Sheets as memory. This setup saves hours each day in manual chat management and creates a much richer, more natural conversation experience for users like Ploy operating a guitar enthusiast community.

Next, consider enhancing your chatbot with voice recognition, integrating a payment gateway for direct purchases, or adding proactive messaging triggered by user behavior to deepen engagement.

Your chatbot “ลลิตา” is now ready to serve with empathy, consistency, and intelligence—powered by n8n automation and Google AI.

Promoted by BULDRR AI

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free