Listen to this Post

Introduction:
The convergence of Large Language Models (LLMs) with Robotic Process Automation (RPA) is enabling a new class of “Agentic Workflows” where AI doesn’t just generate text—it executes actions. By integrating platforms like n8n with APIs for Telegram, Gmail, and Google Sheets, businesses can automate complex communication tasks from a simple chat command. However, as experts in the field have pointed out, giving an LLM direct “firing rights” over your email infrastructure without proper validation is a significant security and operational risk that requires a robust human-in-the-loop (HITL) architecture.
Learning Objectives:
- Understand how to build a secure AI agent workflow using n8n to orchestrate Telegram, Google Sheets, and Gmail APIs.
- Implement validation and clarification loops to prevent data leakage and hallucination-driven errors.
- Apply API security best practices, credential management, and human approval mechanisms to enterprise automation projects.
1. The Orchestration Logic: Building the Core Workflow
Galang Satria’s implementation demonstrates a classic “Trigger-Action” AI model. The user triggers the bot via a Telegram message, an AI Agent parses the intent, queries a Google Sheet for contact data, and sends an email via Gmail. However, the underlying code is not just about chaining apps; it is about data transformation and error handling.
Extended Explanation: The workflow begins with a Telegram Webhook node that captures the chat ID and text. This payload is sent to an OpenAI Chat Model node (using `gpt-4o` or gpt-3.5-turbo) with a system prompt that defines the “Get Recipient” function. The AI extracts the name or email address requested by the user. The system then uses an HTTP Request node to query the Google Sheets API (using the `v4/spreadsheets/{spreadsheetId}/values/{range}` endpoint). Finally, a Gmail API node (via OAuth2) constructs the email payload.
Step-by-Step Guide:
- Trigger: Set up a Telegram Bot via @BotFather. Use the “Telegram Trigger” node in n8n to listen for incoming messages.
- AI Extraction: Add an “OpenAI” node with a prompt like:
Extract the full name and email request from: {{$json.message.text}}. Use structured output to ensure JSON format. - Data Lookup: Use the “HTTP Request” node to GET data from Google Sheets. Ensure the range is specific (e.g.,
Sheet1!A2:B100). Set the authentication to “Service Account” for server-to-server communication. - Filtering: Add an “Item Lists” node to filter the sheet data based on the name extracted by the AI.
- Action: Connect the Gmail node. Set “Operation” to “Send Email” and map the `To` field using
{{$json.email}}. -
The “Sanity Check”: Mitigating Hallucinations and Approval Flows
Talla Nihal raised a critical point regarding “direct firing rights” and hallucinations. If an AI misinterprets “Send to John” as “Johnny” due to a matrix multiplication error, the email is lost. To prevent this, we implement a “Validation & Approval” step between data retrieval and email execution.
Step-by-Step Guide for Safe Execution:
- Draft Creation: Instead of sending the email immediately, use the Gmail “Create Draft” node. This requires the `https://www.googleapis.com/auth/gmail.compose` scope.
- Approval Message: Use a “Telegram Send Message” node to send a formatted message to the user containing the draft preview, the recipient, and the sender.
- Response Wait: Implement a “Wait” node (or a webhook response listener) set to a specific duration or until a keyword is received (e.g., “CONFIRM”).
- Final Sending: If the keyword is “CONFIRM”, trigger the Gmail “Send Draft” node. If not, send a cancellation message and log the event.
Recommended Commands (Linux Environment):
For developers deploying this on a VPS, process monitoring is vital. Use `pm2` to keep the n8n instance alive:
Install PM2 sudo npm install pm2 -g Start n8n with a specific webhook path pm2 start n8n -- start --webhook-url=https://yourdomain.com/webhook/ Save the process to restart on boot pm2 save pm2 startup
3. Validating Recipient Data: The Clarification Loop
Sameer Nazakat and Amjad shaik inquired about handling missing or ambiguous contacts. The architecture must be “conversational,” meaning the AI should ask for clarification rather than failing silently or picking the wrong recipient.
Code Snippet (Python Function Node in n8n):
To check if multiple entries exist for a name, you can use a function node before triggering the email.
This script runs in an n8n Function Node
items = $input.all()
recipients_found = []
for item in items:
if item.json["name"] == search_name:
recipients_found.append(item.json["email"])
if len(recipients_found) == 0:
return [{"json": {"action": "ask", "message": "Contact not found. Please provide the full email."}}]
elif len(recipients_found) > 1:
Return options to the user
return [{"json": {"action": "ask", "options": recipients_found}}]
else:
return [{"json": {"action": "send", "email": recipients_found[bash]}}]
4. Windows and Local Development Setup
For developers using Windows, setting up the AI Agent locally involves navigating PowerShell limitations and environment variables.
Step-by-Step Guide:
- Installation: Install n8n via npm:
npm install n8n -g. - Environment Variables: Set variables for security. In PowerShell:
$env:N8N_ENCRYPTION_KEY="your-secret-key" $env:OPENAI_API_KEY="sk-..."
3. Start: Run `n8n start` in the terminal.
- Tunneling (Ngrok): Since Telegram requires a public webhook, use ngrok for local testing:
ngrok http 5678. Copy the forwarding URL and set it in the Telegram webhook setting viahttps://api.telegram.org/bot<token>/setWebhook?url=<ngrok_url>/webhook-telegram.
5. Security by Design: Credential Management
Galang Satria’s build is fully editable, which introduces risk. Shared workflows often expose API keys. n8n offers a built-in “Credentials” vault.
Step-by-Step Guide:
- OAuth2 Setup: When configuring the Gmail node, do not paste a plain API key. Instead, click “Create New” under credentials and use the OAuth2 flow. This generates a refresh token securely stored locally.
- Environment Variables: Store the `GOOGLE_SHEETS_PRIVATE_KEY` in the `.env` file rather than the workflow JSON.
- Encryption: Ensure `N8N_ENCRYPTION_KEY` is set. If you export your workflow as JSON, the credentials will be stripped out, requiring re-entry on import.
-
Extending the Architecture: API Security and Rate Limiting
AI Agents interacting with Gmail and Sheets face API quotas. Gmail API allows 1 billion quota units per day, but each email uses ~100 units. To prevent abuse, an “Approval” step is not just a safety check but a throttling mechanism.
Suggested Implementation:
- Use a “Redis” or “Wait” node to space out emails.
- Utilize the Google Sheets API’s `batchUpdate` method to “lock” or mark a contact as “contacted” to prevent duplicate sends.
Check API Status (Linux):
Monitor the Gmail API usage via `curl` to check the quota.
curl -X GET https://gmail.googleapis.com/gmail/v1/users/me/profile \ -H "Authorization: Bearer $ACCESS_TOKEN"
7. What Undercode Say:
Key Takeaway 1: “Agentic AI must be ‘Auditable’ before it is ‘Autonomous’.” The workflow is functional, but the lack of a “Draft & Approve” step exposes the organization to data leakage risks. A human gatekeeper is necessary until “Conscious AI” is achieved.
Key Takeaway 2: “API Orchestration is becoming the new AI interface.” By chaining Telegram, Sheets, and Gmail, Satria demonstrates a shift from chatting to doing. However, the success of these workflows depends entirely on the richness of the data schema in Google Sheets—meaning data hygiene is now an AI security concern.
Analysis:
Galang’s workflow is a textbook MVP for an Internal IT Helpdesk or an HR request bot. The “AI Automation Specialist” role is evolving into a “Prompt Engineer + Infrastructure Security Manager.” The expert comments highlight a critical industry split: the Builders (focused on functionality) and the Security engineers (focused on permission boundaries). The addition of an approval step transforms this from a “Potential Liability” into a “Production-Ready Tool.” It also highlights the necessity of robust logging; every decision the AI makes must be tracked in a separate Google Sheet or a database for forensics.
Prediction:
+1: This specific architecture will become the standard template for “AI Middleware” in SMEs, reducing the time for administrative tasks like invoicing and client onboarding by 70%.
+1: The n8n platform will likely release a dedicated “Human-in-the-Loop” node based on this feedback, standardizing the approval button process directly within the UI.
-1: Without stringent validation, we will see a rise in “AI Phishing” where attackers exploit prompt injection (e.g., “Send an email to HR requesting my salary bump”) leading to unauthorized financial requests being processed.
-1: As these AI Agents become pervasive, Google and Microsoft will enforce stricter OAuth scopes and MFA policies, potentially breaking legacy workflows that rely on simple service account authentication.
▶️ Related Video (70% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Galang Satria – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


