Telegram + Google Sheets: cap and log AI bot chats
Your Telegram AI bot starts as a fun experiment. Then it gets shared. Suddenly you’re answering the same questions all day, costs creep up, and you have no clean record of who asked what (or how often).
This hits marketing teams running community bots first, but small business owners and agency operators feel it too. With Telegram bot caps in place, you can stop runaway usage and still give people fast, helpful replies.
This workflow puts a daily limit on each user, logs every chat to Google Sheets, and supports multi-model commands like #openai/gpt-4o plus a /models directory. You’ll see exactly how it works, what you need, and where teams usually trip up.
How This Automation Works
The full n8n workflow, from trigger to final output:
n8n Workflow Template: Telegram + Google Sheets: cap and log AI bot chats
flowchart LR
subgraph sg0["📩 Receive Telegram Message Flow"]
direction LR
n0["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/telegram.svg' width='40' height='40' /></div><br/>📩 Receive Telegram Message"]
n1@{ icon: "mdi:database", form: "rounded", label: "📊 Fetch Usage Logs", pos: "b", h: 48 }
n2@{ icon: "mdi:cog", form: "rounded", label: "📈 Count Today’s Requests", pos: "b", h: 48 }
n3@{ icon: "mdi:swap-vertical", form: "rounded", label: "🔢 Set Daily Limit", pos: "b", h: 48 }
n4@{ icon: "mdi:swap-horizontal", form: "rounded", label: "🚦 Check Limit Exceeded?", pos: "b", h: 48 }
n5["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/telegram.svg' width='40' height='40' /></div><br/>🚫 Notify: Limit Exceeded"]
n6["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/telegram.svg' width='40' height='40' /></div><br/>Send a chat action"]
n7["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/httprequest.dark.svg' width='40' height='40' /></div><br/>Get Models List"]
n8["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/telegram.svg' width='40' height='40' /></div><br/>Send a text message"]
n9["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/code.svg' width='40' height='40' /></div><br/>Code"]
n10["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/telegram.svg' width='40' height='40' /></div><br/>Send a text message1"]
n11@{ icon: "mdi:database", form: "rounded", label: "📝 Log Successful Generation1", pos: "b", h: 48 }
n12@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Get Models Or Process Message?", pos: "b", h: 48 }
n13@{ icon: "mdi:web", form: "rounded", label: "🧠 Generate Msg (AI/ML API | ..", pos: "b", h: 48 }
n14@{ icon: "mdi:web", form: "rounded", label: "🧠 Generate Msg (AI/ML API | ..", pos: "b", h: 48 }
n15["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/code.svg' width='40' height='40' /></div><br/>Group Models By Providers"]
n16@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Set Custom Model?", pos: "b", h: 48 }
n9 --> n8
n7 --> n9
n16 --> n15
n16 --> n13
n6 --> n16
n10 --> n11
n3 --> n4
n1 --> n2
n15 --> n14
n4 --> n6
n4 --> n5
n2 --> n3
n0 --> n12
n12 --> n7
n12 --> n1
n13 --> n10
n14 --> n10
end
%% Styling
classDef trigger fill:#e8f5e9,stroke:#388e3c,stroke-width:2px
classDef ai fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
classDef aiModel fill:#e8eaf6,stroke:#3f51b5,stroke-width:2px
classDef decision fill:#fff8e1,stroke:#f9a825,stroke-width:2px
classDef database fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef api fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef code fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef disabled stroke-dasharray: 5 5,opacity: 0.5
class n0 trigger
class n4,n12,n16 decision
class n1,n11 database
class n7,n13,n14 api
class n9,n15 code
classDef customIcon fill:none,stroke:none
class n0,n5,n6,n7,n8,n9,n10,n15 customIcon
The Problem: AI bots get noisy, expensive, and untrackable
When your Telegram bot is powered by an AI model, every message is a micro-cost. A handful of users won’t hurt. A busy group chat will. Then there’s the human cost: you get pulled into debugging weird requests, answering “what did it say earlier?”, and dealing with spammy prompt loops. The worst part is the lack of visibility. Without a log, you’re guessing why costs rose, which prompts are breaking, and which users are hammering the bot.
It adds up fast. Here’s where it usually breaks down in real teams.
- One power user can burn through your API budget in an afternoon, and you won’t notice until after the fact.
- Without per-user limits, the bot becomes an infinite free tool, which attracts spam and low-intent traffic.
- Support and marketing can’t learn from conversations because there’s no clean history to search or review.
- Model changes get messy, since you can’t see which provider or model ID produced which answers.
The Solution: cap usage, route models, and log every chat
This n8n workflow turns your Telegram bot into something you can actually run day-to-day. A message arrives in Telegram and the workflow decides what it is. If a user sends /models, it fetches a live model catalog via HTTP, formats it into a readable list, and replies in chat. If it’s a normal prompt, the workflow checks that user’s daily usage in Google Sheets, compares it to your cap, and either approves the request or sends a limit warning. Approved prompts get parsed for a #model_id tag, then routed to the right AI endpoint (a default GPT-4o path or a custom model path). Finally, the bot sends the response back to Telegram and logs the request and result to your sheet.
The flow starts in Telegram, then Google Sheets enforces the daily limit, and the AI call happens only when the user is under the cap. After the reply goes out, Sheets becomes your audit trail for cost control, quality checks, and simple analytics.
What You Get: Automation vs. Results
| What This Workflow Automates | Results You’ll Get |
|---|---|
|
|
Example: What This Looks Like
Say your bot sits in a community chat and gets about 200 messages a day from 40 people. Manually reviewing usage, deciding who’s overdoing it, and copy-pasting conversation snippets into a tracker can easily take about 30 minutes daily (and you still miss things). With this workflow, the “tracking” is automatic: a Telegram message triggers the check, the AI reply goes out, and a row is logged in Google Sheets right away. The only time you touch it is when you want to review the log or adjust the daily cap.
What You’ll Need
- n8n instance (try n8n Cloud free)
- Self-hosting option if you prefer (Hostinger works well)
- Telegram to receive messages and send replies.
- Google Sheets for daily caps and chat logging.
- AIMLAPI API key (get it from your AIMLAPI dashboard).
Skill level: Intermediate. You’ll connect credentials, set up a sheet, and make small edits like the daily cap value.
Don’t want to set this up yourself? Talk to an automation expert (free 15-minute consultation).
How It Works
A Telegram message kicks it off. The workflow listens for new messages sent to your bot, so every user interaction becomes a trigger.
The message gets classified. A routing check decides if the user asked for /models (directory mode) or sent a prompt that needs an AI response.
Daily caps are enforced in Google Sheets. The workflow retrieves that user’s records for today, tallies requests, defines your cap, and blocks the request if they’ve hit the limit. If they’re under, it continues.
The right model answers, then everything is logged. If the prompt includes a #model_id tag, the workflow routes to a custom model call; otherwise it uses the default GPT-4o path. The reply is sent back to Telegram, then the query and result are written to Google Sheets.
You can easily modify the daily cap to match your budget, or change which model is the default based on your audience. See the full implementation guide below for customization options.
Step-by-Step Implementation Guide
Step 1: Configure the Telegram Trigger
Set up the workflow to listen for incoming Telegram messages so the automation can route model requests or process prompts.
- Add and open 📨 Telegram Intake Trigger.
- Credential Required: Connect your telegramApi credentials.
- Confirm Updates includes
message. - Save the node to generate the webhook and prepare it for Telegram updates.
$json.message.text.Step 2: Connect Google Sheets
Configure usage tracking and logging with Google Sheets to enforce daily limits and store AI responses.
- Open 📄 Retrieve Usage Records and select the Google Sheets document and sheet: set Document to
[YOUR_ID]and Sheet to[YOUR_ID]. - Set Filters with
user_idas{{ $json.message.from.id }}anddateas{{ new Date().toISOString().slice(0,10) }}. - Credential Required: Connect your googleSheetsOAuth2Api credentials to 📄 Retrieve Usage Records and 📝 Record Generation Log.
- Open 📝 Record Generation Log, set Operation to
append, and map columns:date={{ new Date().toISOString().slice(0,10) }},query={{ $('📨 Telegram Intake Trigger').item.json.message.text }},result={{ $json.result.text }},user_id={{ $('📨 Telegram Intake Trigger').item.json.message.from.id }}.
user_id, date, query, and result or the append will fail.Step 3: Set Up Routing and Model Catalog Flow
Route incoming messages to either return available models or proceed with prompt processing.
- Open Route Models or Process and confirm the first rule contains
{{ $json.message.text }}and checks contains/models. - Confirm the second rule uses
{{ $json.message.text }}with notEmpty to route general prompts. - Open Fetch Model Catalog and set URL to
https://api.aimlapi.com/v1/models. - Open Transform Model List, set Language to
python, and keep the provided grouping code to format model lists by developer. - Open Send Model List and set Text to
{{ $json.content }}and Chat ID to{{ $('📨 Telegram Intake Trigger').item.json.message.chat.id }}. - Credential Required: Connect your telegramApi credentials to Send Model List.
Step 4: Configure Usage Limits and Status Updates
Count daily usage and block prompts that exceed the allowed limit.
- Open 📈 Tally Daily Requests and confirm Aggregate is set to
aggregateAllItemData. - Open 🔢 Define Daily Cap and set daily_limit to
5. - Open 🚦 Evaluate Usage Limit and ensure the condition compares
{{$('📈 Tally Daily Requests').item.json.data.length }}with{{ $json.daily_limit }}using lt. - Open 🚫 Send Limit Warning and set Text to
Sorry! Your *daily limit of {{ $('🔢 Define Daily Cap').item.json.daily_limit }} generations* is exceeded!, with Chat ID{{ $('📨 Telegram Intake Trigger').item.json.message.chat.id }}. - Credential Required: Connect your telegramApi credentials to 🚫 Send Limit Warning and Send Chat Status.
- Open Send Chat Status and set Operation to
sendChatActionwith Chat ID{{ $('📨 Telegram Intake Trigger').item.json.message.chat.id }}.
Step 5: Set Up AI Generation and Custom Model Parsing
Detect custom model tags, parse them, and generate responses using AIML API or GPT-4o.
- Open Detect Custom Model and verify it checks if
{{ $('📨 Telegram Intake Trigger').item.json.message.text }}startsWith#. - Open Parse Model Tag and keep the JavaScript logic that extracts
model_idandmessagefrom a#modelprefix. - Open 🧠 Generate via Custom AI, set Model to
{{ $json.model_id }}and Prompt to{{ $json.message }}. - Open 🧠 Generate via GPT-4o and set Model to
openai/gpt-4owith Prompt{{ $('📨 Telegram Intake Trigger').item.json.message.text }}. - Credential Required: Connect your aimlApi credentials to 🧠 Generate via Custom AI and 🧠 Generate via GPT-4o.
#model_name prompt text to route through Parse Model Tag and 🧠 Generate via Custom AI.Step 6: Configure Output Messages and Logging
Send the AI response back to Telegram and log each generation for usage tracking.
- Open Dispatch AI Reply and set Text to
{{ $json.content }}and Chat ID to{{ $('📨 Telegram Intake Trigger').item.json.message.chat.id }}. - Credential Required: Connect your telegramApi credentials to Dispatch AI Reply.
- Confirm the execution flow sends AI output to Dispatch AI Reply and then to 📝 Record Generation Log.
Step 7: Test and Activate Your Workflow
Run a full test from Telegram, confirm usage limits and AI responses, then activate for production.
- Click Execute Workflow and send a Telegram message like
/modelsto validate the model list path (Fetch Model Catalog → Transform Model List → Send Model List). - Send a normal prompt and verify the usage path: 📄 Retrieve Usage Records → 📈 Tally Daily Requests → 🔢 Define Daily Cap → 🚦 Evaluate Usage Limit → Send Chat Status → AI generation → Dispatch AI Reply → 📝 Record Generation Log.
- Confirm a successful run: Telegram receives a reply, and a new row is appended to your Google Sheet with today’s date, query, result, and user_id.
- Toggle the workflow to Active to start processing incoming messages automatically.
Common Gotchas
- Telegram credentials can expire or get rotated when you recreate a bot. If replies suddenly stop, check your n8n Telegram credential first and confirm the BotFather token still matches.
- If you’re using Wait nodes or external rendering, processing times vary. Bump up the wait duration if downstream nodes fail on empty responses.
- Google Sheets permissions are easy to overlook. If reads or writes fail, verify the sheet is shared with the correct OAuth user or service account email used by your Google Sheets credential.
Frequently Asked Questions
About 45 minutes if your Telegram bot and Google Sheet are ready.
No. You’ll mainly connect accounts and edit a few values like the daily limit. The only “code” parts are already included in the workflow, so you’re not writing scripts from scratch.
Yes. n8n has a free self-hosted option and a free trial on n8n Cloud. Cloud plans start at $20/month for higher volume. You’ll also need to factor in AIMLAPI usage costs based on your model and message volume.
Two options: n8n Cloud (managed, easiest setup) or self-hosting on a VPS. For self-hosting, Hostinger VPS is affordable and handles n8n well. Self-hosting gives you unlimited executions but requires basic server management.
Yes, but you’ll want to store a “chat_id to cap” mapping. Most people do it by adding a second Google Sheet tab for group settings, then adjusting the Define Daily Cap step to pull the right cap based on the incoming chat or user.
Usually it’s a bad or rotated BotFather token saved in your n8n Telegram credential. Update the credential, then send a real message to the bot to test (running nodes manually can be misleading). If it still fails, check that you’re using the right bot, and that the bot is allowed to message in the chat where you’re testing.
A lot, as long as your n8n instance and AI provider can keep up. On n8n Cloud, your limit is mostly tied to monthly executions on your plan, while self-hosting has no fixed cap (it depends on server size). Practically, Google Sheets becomes the bottleneck first if you log very long responses all day, so teams at higher volume often switch logging to a database later.
For this use case, n8n is usually the better fit because you need branching logic (/models vs prompts), per-user limit checks, and reliable logging in the same flow. Zapier and Make can do parts of it, but the logic gets awkward fast and can become expensive when every message is a paid task. n8n also gives you the self-hosting option, which is a big deal when usage spikes. The trade-off is setup: you’ll spend a bit more time upfront configuring credentials and the Google Sheet structure. If you want help deciding, Talk to an automation expert.
You get control without babysitting the bot. Set the cap, keep the log, and let Telegram handle the conversations while you focus on what actually moves the business.
Need Help Setting This Up?
Our automation experts can build and customize this workflow for your specific needs. Free 15-minute consultation—no commitment required.