Opening Problem Statement
Meet Mai, a busy event coordinator who juggles multiple tasks daily. She often receives schedule inquiries and event creation requests via LINE messages and has to manually check her Google Calendar and Gmail for confirmations or relevant details. This tedious manual back-and-forth wastes her precious time—sometimes up to 2 hours daily—and often causes delays or errors, like double bookings or missed emails. Mai needs a solution that can seamlessly handle her calendar events and emails directly through LINE, without making her leave the chat app.
What This Automation Does
This n8n workflow transforms Mai’s LINE chatbot into a powerful assistant integrated deeply with her Google Calendar and Gmail. Here’s what happens when the workflow runs:
- Intercepts incoming LINE text messages and determines user intent.
- For valid text messages, processes natural language inputs through an AI agent powered by LangChain and OpenAI.
- Queries Google Calendar to fetch upcoming events or create new events based on user requests.
- Reads Gmail emails filtered by user-specified criteria, such as received date, to retrieve relevant email information.
- Returns clean, concise, and user-friendly text responses back on LINE via the chatbot.
- Handles non-text or erroneous messages gracefully by sending customized error replies.
This automation can save you at least one hour of manual calendar and email management daily, and reduces booking errors significantly.
Prerequisites ⚙️
- n8n account (cloud or self-hosted) 🔌
- LINE Messaging API setup with webhook URL configured 📱
- Google Calendar account with OAuth2 credentials for n8n 🔐
- Gmail account with OAuth2 credentials for n8n 🔐
- OpenAI API key for AI language model & LangChain nodes 🔑
Optional: Consider self-hosting n8n for better control and privacy, with hosts like Hostinger.
Step-by-Step Guide to Build This Workflow
1. Set up LINE Webhook Trigger
Go to n8n dashboard → Click + New Workflow → Add Webhook node → Name it “Line Receiving” → Set HTTP Method to POST → Enter webhook path linechatbotagent → Save and copy the webhook URL → Configure this URL in your LINE Messaging API console under webhook settings.
Expected: LINE messages sent to this bot trigger this node.
Common mistake: Forgetting to activate the webhook in LINE developer console.
2. Split Text vs Other Message Types
Add a Switch node named “Switch Between Text and Others” → Set condition to check if {{ $json.body.events[0].message.type }} equals “text”.
Expected: Workflow routes only textual messages to proceed, filtering out images or stickers.
Common mistake: Misconfiguring the condition field or case sensitivity causing messages to fail routing.
3. AI Processing – LangChain Agent Setup
Add AI Agent (LangChain agent) node → Connect “Switch” (text path) output to this node.
Configure the node to pass the user message text via {{ $json.body.events[0].message.text }}, set system message with the current date context.
Expected: User queries are processed with advanced AI with LangChain managing memory and tools.
Common mistake: Not enabling or properly configuring the AI agent prompt and system message.
4. Language Model Configuration
Add OpenAI Chat Model node → Connect it as the AI language model for AI Agent.
Leave options default or specify as needed.
Expected: The agent uses OpenAI GPT model for natural language understanding.
Common mistake: Forgetting to link LangChain AI Agent with the OpenAI model.
5. Memory Buffer Setup
Add Window Buffer Memory node → Set session key to userId to maintain user-specific conversation context.
Connect as AI memory tool for the AI Agent.
Expected: Chat context is preserved for coherent responses.
Common mistake: Incorrect session key causing cross-user data mixing.
6. Add Wikipedia Tool
Include Wikipedia tool node connected to the AI Agent’s tools input to provide knowledge base queries.
Expected: The assistant can fetch Wikipedia info if user asks.
Common mistake: Missing integration causing fallback errors.
7. Integrate Google Calendar Read & Create
Add two nodes:
– Google Calendar Read: Configured with user calendar, takes dynamic start/end time from AI’s variables.
– Google Calendar Create: To create events with start, end, and summary from AI output.
Connect both as tools to AI Agent.
Expected: The bot can query or create calendar events as per user requests.
Common mistake: Improper date parsing or wrong OAuth2 credentials.
8. Integrate Gmail Read Node
Add Gmail Read node configured to filter emails by received date from AI.
Connect as a tool input for AI Agent.
Expected: The assistant can fetch relevant emails on request.
Common mistake: Gmail OAuth2 credentials not authorized or incorrect filter syntax.
9. AI Response Error Handling
Add a Switch node “Error Handling from AI Response” to check if AI’s output message exists and is valid.
If valid pass to Text Cleansing node; if not, route to error reply.
Expected: Only valid AI responses proceed.
Common mistake: Failing to check for empty or malformed AI responses.
10. Text Cleansing Node
Use Set node named “Text Cleansing” to clean AI responses by removing markdown, new lines, HTML tags, and quotes.
Use code snippet:
{{ $json.message.content.replaceAll("n","\n").replaceAll("n","").removeMarkdown().removeTags().replaceAll('"',"") }}Expected: Response is clean and suitable for LINE messages.
Common mistake: Typo in replaceAll or use of unsupported functions.
11. Reply to LINE (Success & Error)
Add two HTTP Request nodes for LINE reply API:
– “Line Answering (Ordinary Case)”: Sends cleaned AI response.
– “Line Answering (Error Case)”: Sends default error text “กรุณาส่งอย่างอื่นเถอะนะเตงอัว” if AI output invalid.
Set HTTP POST with Authorization Bearer token and JSON body with replyToken.
Expected: User receives timely responses in LINE.
Common mistake: Wrong token or body format causing 401 Unauthorized errors.
Customizations ✏️
- Change AI Model: In the “OpenAI Chat Model” node, swap to a more powerful or cheaper model like
gpt-3.5-turboto balance cost and performance. - Response Language: Modify the system message in “OpenAI” node to change reply language or tone, e.g., to make responses more formal or casual.
- Add New Tools: Extend the AI Agent tools by adding new API nodes like Todoist or weather APIs to expand chatbot capabilities.
- Custom Error Messages: Edit the “Line Answering (Error Case)” node’s JSON body to personalize fallback responses.
Troubleshooting 🔧
Problem: “LINE reply API returns 401 Unauthorized”
Cause: Missing or incorrect LINE channel access token.
Solution: Go to the HTTP Request nodes for LINE reply, verify and re-enter the correct channel access token under HTTP headers → Authorization → Bearer.
Problem: “AI Agent returns empty or malformed responses”
Cause: Improper prompt, or LangChain node configuration error.
Solution: Check the AI Agent node prompts, ensure system message and user input are correctly passed; test with sample data.
Problem: “Google Calendar events not appearing or wrong dates”
Cause: Date formats passed from AI to Google Calendar nodes are incorrect.
Solution: Confirm AI variables return ISO date strings; verify date input fields in Google Calendar Read/Create nodes; test with static dates if needed.
Pre-Production Checklist ✅
- Verify LINE webhook is active and receives events in n8n.
- Test Google Calendar Read node with known date range and confirm event retrieval.
- Check Gmail Read node filters by date deliver correct emails.
- Test AI Agent with sample messages to confirm meaningful conversational output.
- Ensure HTTP Request nodes reply properly to LINE with correct tokens and body format.
- Backup n8n workflow version before activating production.
Deployment Guide
Once all nodes are connected and tested successfully, activate the workflow in n8n dashboard by toggling the active switch. Monitor the workflow executions tab to view runtime logs and any errors. Adjust timeout and retry settings if your workflow interacts with APIs prone to delays. Keep your API keys and tokens secure, and periodically review usage metrics on your OpenAI and Google APIs to avoid quota limits.
FAQs
Q1: Can I use a different AI provider than OpenAI?
Yes. The LangChain AI Agent supports various language models; you can substitute OpenAI with alternatives like Hugging Face or Azure OpenAI by configuring the respective nodes.
Q2: Does this workflow consume many API credits?
OpenAI usage depends on message length and model used; Google and LINE APIs have their own quotas. Efficient prompt design helps reduce token use.
Q3: Is my data safe in this workflow?
Your data flows through secure OAuth2 connections and LINE’s encrypted messaging. Self-hosting n8n adds another layer of privacy control.
Conclusion
By completing this tutorial, you’ve built a sophisticated n8n workflow that turns your LINE chatbot into a dynamic assistant integrated with Google Calendar and Gmail. You can now effortlessly manage events and fetch emails right within LINE, saving at least an hour daily and minimizing scheduling errors. Next steps could include adding more AI-powered tools or integrating other messaging platforms for broader reach. Keep experimenting and optimizing to make your automation even smarter!