Opening Problem Statement
Meet Sarah, a mental health coach trying to scale her Cognitive Behavioral Therapy (CBT) support sessions online. She’s overwhelmed manually responding to client questions via Line chat, particularly struggling to maintain engagement while clients wait for thoughtful responses. She also loses potential clients because non-text messages, like images or stickers, cause confusion and delays. Sarah wastes hours every day repeating the same guidance, and inconsistent replies from multiple helpers lower her service quality. This is exactly where automating a CBT AI chatbot with n8n and Azure OpenAI can transform Sarah’s daily workflow, saving her precious time and offering clients prompt, reliable mental health support.
What This Automation Does
This n8n workflow connects the Line Messaging platform with Azure OpenAI’s language model to create an intelligent chatbot specialized in CBT. When a user sends a text message via Line, the workflow triggers and the chatbot responds with therapeutic advice based on Cognitive Behavioral Therapy principles.
- Loads a “typing” animation in Line while processing the request to reassure users that the bot is working
- Detects if the user input is text-based for appropriate processing
- Sends non-text inputs a polite “not supported” message to keep the conversation clear
- Processes user messages through an AI Agent node running a CBT-specific system prompt to deliver therapeutic guidance without explicitly revealing CBT methods
- Uses Azure OpenAI’s GPT model to generate nuanced, empathetic, and cognitive-behaviorally accurate responses
- Replies back to the user instantly in Line with properly formatted text, ensuring a smooth conversational experience
This automation potentially saves several hours per client interaction and enables scale-up of therapy messages without hiring extra staff.
Prerequisites ⚙️
- n8n account for workflow automation
- Line Developer account with Messaging API access and configured webhook URL
- Azure OpenAI account with access to GPT models
- Generic HTTP Header Auth credentials configured for Line Messaging API
Step-by-Step Guide
Step 1: Set Up the Line Chatbot Webhook Node
Navigate to your n8n editor. Click the plus icon and add the Webhook node. Name it “Line Chatbot”. Set the HTTP Method to POST and choose a webhook path, for example, AIChatbot.
In your Line Developer Console, set the webhook URL to the URL displayed in this node without the “test” prefix when you deploy in production.
You should see the webhook listening for incoming Line events once activated.
Common mistake: Forgetting to remove the “test” part of the URL before going live, leading to webhook failures.
Step 2: Add the Line Loading Animation HTTP Request
Add an HTTP Request node and name it “Loading Animation”. Configure it to POST to https://api.line.me/v2/bot/chat/loading/start.
Set the request body as raw JSON with the chat ID dynamically extracted from the incoming webhook: { "chatId": "{{ $json.body.events[0].source.userId }}", "loadingSeconds": 60 }.
Add HTTP Header Authentication credentials for your Line bot.
This node sends a “typing” indicator in the Line chat so users know their message is being processed.
Common mistake: Not using header authorization properly, causing failed requests to Line API.
Step 3: Add an If Node to Check if Message is Text
Insert an If node and name it “Check Message Type IsText?”. Set the condition to compare {{ $('Line Chatbot').item.json.body.events[0].message.type }} to the string text.
This ensures only text messages proceed to AI processing, while other types trigger a different reply.
Common mistake: Misconfigured conditions leading to all messages being routed incorrectly.
Step 4: Configure an AI Agent Node for CBT Responses
Add the AI Agent node from the Langchain nodes. Set the input to capture the user’s message text via expression: {{ $('Line Chatbot').item.json.body.events[0].message.text }}.
Customize the system prompt extensively to simulate a CBT therapist. Use the provided detailed prompt (see workflow) to instruct the AI about CBT principles and how to deliver empathetic, cognitive-behavioral guidance without overtly mentioning CBT.
This node is the brain of the chatbot, using AI to craft replies that help users with mental health challenges.
Common mistake: Leaving the system message too generic reduces the helpfulness and specificity of responses.
Step 5: Connect the AI Agent to Azure OpenAI Chat Model
Include the Azure OpenAI Chat Model node and set the model to “4o” or another available GPT-4 variant.
Connect this node as the language model for the AI Agent node to process natural language generation.
Authenticate using your Azure OpenAI credentials.
This integration powers the AI Agent’s replies with the advanced language capabilities of GPT-4.
Common mistake: Incorrect API credential setup causing authentication errors.
Step 6: Format the AI Agent Output for Line
Add a Set node named “Format Reply” to clean and format the AI Agent’s output for JSON compatibility.
Use the expression to replace new lines, remove markdown and HTML tags, and sanitize quotes: {{ $json.output.replaceAll("n","\n").replaceAll("n","").removeMarkdown().removeTags().replaceAll('"',"") }}.
This step ensures a clean, plain text reply suitable for the Line messaging payload.
Step 7: Send the Reply Message Back to Line
Add an HTTP Request node named “ReplyMessage – Line” to POST to https://api.line.me/v2/bot/message/reply.
Configure the JSON body to include the original reply token and the formatted AI response as a text message:
{
"replyToken": "{{ $('Line Chatbot').item.json.body.events[0].replyToken }}",
"messages": [
{ "type": "text", "text": "{{ $json.output }}" }
]
}Apply your Line bot’s HTTP Header Authentication credentials here.
This node sends the chatbot’s reply so the user sees it immediately in the Line app.
Step 8: Handle Unsupported Message Types
Add another HTTP Request node named “ReplyMessage – Not supported” that replies courteously when the message type is not text.
Use this JSON body:
{
"replyToken":"{{ $('Line Chatbot').item.json.body.events[0].replyToken }}",
"messages":[{"type":"text","text":"Currently, the input of image or other type are not supported."}]
}This keeps the conversation clear and avoids confusion for unsupported inputs.
Step 9: Optional Sticky Notes for Documentation Inside n8n
Use sticky notes at various sections to document webhook setup, usage of loading animation, AI model notes, and reply message details for easy reference when editing the workflow.
Customizations ✏️
- Change Therapy Style in AI Agent Node: Edit the system message to switch from CBT to other talking therapy styles, like mindfulness or motivational interviewing, by customizing the prompt in the AI Agent node.
- Increase Creativity: Adjust the temperature parameter in the Azure OpenAI Chat Model node to closer to 1 for more creative or varied chatbot replies.
- Add Support for New Message Types: Extend the ‘Check Message Type IsText?’ node with additional branches and custom HTTP Request nodes to handle image, audio, or sticker messages gracefully.
- Multi-Language Options: Modify the system prompt and add nodes to detect language and translate user messages before processing, enabling a multilingual CBT chatbot.
- Logging User Sessions: Add nodes to save user sessions or message logs into a database or Google Sheets for post-session review and therapy progress tracking.
Troubleshooting 🔧
Problem: “401 Unauthorized” from Line API
Cause: The HTTP Header Authentication token is incorrect or expired.
Solution: Go to the HTTP Request node, open the generic HTTP header auth credentials, and update the token to a valid Line Messaging API channel access token.
Problem: AI Agent Not Producing Correct Responses
Cause: The system message prompt is too vague or missing CIS rules.
Solution: Edit the AI Agent node’s system prompt to include detailed, specific CBT instructions and examples to guide the AI model effectively.
Problem: Webhook Not Triggering
Cause: Webhook URL not correctly set or Line Developer Console webhook not enabled.
Solution: Check webhook URL in Line Console matches the n8n webhook URL exactly and is enabled. Remove ‘test’ if deploying live. Use the sticky note instructions as a reference.
Pre-Production Checklist ✅
- Verify webhook URL is correctly set up and enabled in Line Developer Console.
- Test webhook by sending text messages and non-text messages to see correct routing.
- Confirm HTTP Header Authorization tokens are valid and not expired.
- Validate AI Agent node returns meaningful CBT-style responses.
- Ensure reply messages appear promptly in Line app.
- Backup n8n workflow JSON before making major changes.
Deployment Guide
Activate the workflow by toggling it active in n8n. Ensure your webhook URL is public and reachable by Line API servers.
Monitor real-time executions in n8n dashboard to track errors or slow responses.
Update AI Agent system message or Azure OpenAI model parameters as needed to fine-tune conversational style.
FAQs
- Q: Can I use this workflow with other chat platforms like WhatsApp? A: This workflow is customized for Line’s API structure. For WhatsApp, you’d need a different webhook and API nodes tailored to WhatsApp messaging.
- Q: Will Azure OpenAI API usage be expensive? A: Costs depend on usage volume and model. Test with smaller models initially and monitor billing closely.
- Q: Is user data kept secure? A: Yes, n8n workflows run on secure infrastructure and you can ensure data encryption. Always follow best security practices when handling user data.
- Q: Can this chatbot handle hundreds of users simultaneously? A: With appropriate n8n infrastructure and Azure OpenAI capacity, yes. You may need to scale resources as user volume grows.
Conclusion
By building this CBT AI chatbot integration in n8n, you’ve automated thoughtful mental health support via Line. You’ve saved hours previously spent on manual replies and created a scalable solution with advanced AI. Your chatbot now delivers empathetic, cognitive-behavioral guidance instantly while managing unsupported message types gracefully.
Next, consider extending this to other therapy styles, adding multi-language support, or integrating user session logging for richer analytics. Keep iterating to offer even more personalized and accessible therapy.
Thanks for following along—your new AI therapy assistant is ready to help people more efficiently than ever!