Telegram + Google Sheets: track AI token costs
If you’re running an AI bot in Telegram or WhatsApp, costs can feel a little “mystical.” One day everything looks fine. Then you get an API bill and realize you have no idea which conversations (or which client) drove the spike.
This is where token cost tracking automation helps. It hits agency owners who bill clients hardest, but marketing teams running community bots feel it too. Even a solo consultant with one Telegram bot ends up guessing when they should be logging.
This workflow captures every interaction, totals tokens, estimates USD, and appends it to Google Sheets. You’ll see how it works, what you need, and where people usually get stuck.
How This Automation Works
Here’s the complete workflow you’ll be setting up:
n8n Workflow Template: Telegram + Google Sheets: track AI token costs
flowchart LR
subgraph sg0["Telegram Flow"]
direction LR
n0@{ icon: "mdi:message-outline", form: "rounded", label: "Send Email", pos: "b", h: 48 }
n1@{ icon: "mdi:database", form: "rounded", label: "Get Contacts", pos: "b", h: 48 }
n2@{ icon: "mdi:database", form: "rounded", label: "Log", pos: "b", h: 48 }
n3@{ icon: "mdi:location-exit", form: "rounded", label: "Create Event", pos: "b", h: 48 }
n4["<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/>Clean Up"]
n5@{ icon: "mdi:database", form: "rounded", label: "Errors", pos: "b", h: 48 }
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/>Error Response"]
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/telegram.svg' width='40' height='40' /></div><br/>Response"]
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/code.svg' width='40' height='40' /></div><br/>Clean_Up"]
n9@{ icon: "mdi:robot", form: "rounded", label: "AI Agent", pos: "b", h: 48 }
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/webhook.dark.svg' width='40' height='40' /></div><br/>Evolution API"]
n11["<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 Media"]
n12@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Audio or Text Separation", pos: "b", h: 48 }
n13@{ icon: "mdi:cog", form: "rounded", label: "Convert to File", pos: "b", h: 48 }
n14@{ icon: "mdi:robot", form: "rounded", label: "Audio Transcription", 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/telegram.svg' width='40' height='40' /></div><br/>Telegram"]
n16@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Filter", pos: "b", h: 48 }
n17@{ icon: "mdi:swap-vertical", form: "rounded", label: "Text Mapping", pos: "b", h: 48 }
n18@{ icon: "mdi:brain", form: "rounded", label: "Chat Model", pos: "b", h: 48 }
n19@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Input Source", pos: "b", h: 48 }
n20@{ icon: "mdi:swap-vertical", form: "rounded", label: "Map", pos: "b", h: 48 }
n21@{ icon: "mdi:swap-vertical", form: "rounded", label: "Map1", pos: "b", h: 48 }
n22["<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/>WhatsApp"]
n23["<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/>WhatsApp Erro"]
n24@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Input Source1", pos: "b", h: 48 }
n2 --> n19
n20 --> n12
n21 --> n17
n5 --> n24
n16 --> n9
n9 --> n4
n9 --> n8
n4 --> n2
n8 --> n5
n15 --> n21
n11 --> n13
n18 -.-> n9
n0 -.-> n9
n3 -.-> n9
n1 -.-> n9
n19 --> n22
n19 --> n7
n17 --> n16
n10 --> n20
n24 --> n23
n24 --> n6
n13 --> n14
n14 --> n17
n12 --> n11
n12 --> n17
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 n15 trigger
class n9,n14 ai
class n18 aiModel
class n12,n16,n19,n24 decision
class n1,n2,n5 database
class n10,n11,n22,n23 api
class n4,n8 code
class n0 disabled
class n1 disabled
class n3 disabled
classDef customIcon fill:none,stroke:none
class n4,n6,n7,n8,n10,n11,n15,n22,n23 customIcon
Why This Matters: AI Spend Is Invisible Until It Hurts
AI chat feels cheap in the moment. A few replies here, a voice note transcription there, and everything keeps moving. The trouble is you don’t see the meter running in real time. By the time finance asks, “Why did usage jump?” you’re digging through chat logs, trying to reconstruct what happened. That’s slow, and it’s honestly unreliable. If you support multiple channels (Telegram plus WhatsApp), the confusion doubles because each platform tells a different story.
It adds up fast. Here’s where it usually breaks down in day-to-day operations.
- Token usage lives inside model dashboards, not inside your reporting workflow, so nobody checks it until billing day.
- Manual logging never survives a busy week, especially when multiple teammates answer messages.
- Client billing becomes “best effort,” which leads to awkward write-offs and scope creep.
- When you add voice notes, transcription costs appear, and the spend is even harder to explain later.
What You’ll Build: Telegram/WhatsApp Token Logging to Google Sheets
This automation listens for incoming messages from Telegram and/or WhatsApp (via a webhook). If the message is text, it moves forward immediately. If it’s an audio message, the workflow fetches the media file, converts it into a usable format, and transcribes it before continuing. From there, an AI Agent runs your intended assistant logic using a chat model (configured through OpenRouter), and the workflow normalizes the result so token counts and metadata are clean. Finally, it appends a new row into Google Sheets with prompt tokens, completion tokens, total tokens, timestamps, and the sender/channel. Optionally, it calculates a simple USD estimate so you can audit spend without opening an AI dashboard.
The flow starts at Telegram Trigger or a WhatsApp webhook intake. Then it routes the input source, processes text or audio, and runs the AI agent. At the end, it logs usage to Sheets and sends a success message (or records an error and notifies you) depending on what happened.
What You’re Building
| What Gets Automated | What You’ll Achieve |
|---|---|
|
|
Expected Results
Say your bot handles about 20 conversations a day across Telegram and WhatsApp, and you want token totals plus cost notes for each. Manually, you might spend 5 minutes per conversation checking dashboards and pasting numbers into a sheet, which is roughly 100 minutes daily. With this workflow, logging is automatic after each message, so your “work” becomes a quick weekly review in Google Sheets (maybe 20 minutes). That’s a real chunk of time back, and the billing trail is already there.
Before You Start
- n8n instance (try n8n Cloud free)
- Self-hosting option if you prefer (Hostinger works well)
- Google Sheets for the usage log and reporting.
- Telegram Bot to receive messages and reply back.
- WhatsApp Evolution API (optional) to capture WhatsApp chats via webhook.
- OpenRouter API key (get it from your OpenRouter dashboard) to run the chat model and report token usage.
Skill level: Intermediate. You’ll connect accounts, edit a Sheet ID, and confirm webhook/Telegram settings.
Want someone to build this for you? Talk to an automation expert (free 15-minute consultation).
Step by Step
A message comes in from Telegram or WhatsApp. Telegram uses a bot trigger, while WhatsApp arrives through a webhook intake. A routing step (Switch) tags the source so replies and error notices go to the right place.
The workflow turns messy inputs into clean text. If the message includes audio, it fetches the media file, converts it, and transcribes it with an OpenAI transcription node. If it’s already text, it skips the audio path and maps the fields you’ll want to log (user/channel, message, timestamp).
Your AI Agent runs, then the workflow extracts usage. The AI Orchestrator calls the chat model (through OpenRouter) and produces both an answer and usage metadata. Code/normalization nodes reshape the output so you have consistent “prompt tokens,” “completion tokens,” and “total tokens,” even when different message types come through.
Google Sheets becomes your system of record. A Google Sheets node appends a new row to your log tab. On success, the workflow can send a quick confirmation back to Telegram or WhatsApp; on failure, it records an error row and sends an alert.
You can easily modify the spreadsheet columns to match your billing model based on your needs. See the full implementation guide below for customization options.
Step-by-Step Implementation Guide
Step 1: Configure the Webhook Trigger
Set up the incoming channels so the workflow can accept webhook payloads and Telegram messages.
- Add and open Webhook Intake, then copy the Test URL for initial testing.
- Open Telegram Trigger and set the update types you want to receive (e.g., message, audio).
- Confirm the flow: Webhook Intake → Map Webhook Payload and Telegram Trigger → Map Telegram Payload.
Credential Required: Connect your Telegram API credentials in Telegram Trigger.
Step 2: Connect Google Sheets
Prepare the logging destinations used for usage tracking and error records.
- Open Update Usage Log and select the spreadsheet and sheet tab where usage rows will be written.
- Open Record Error Log and select the spreadsheet and sheet tab for error records.
- Ensure both nodes map the columns you expect (e.g., timestamp, input source, message, model).
Credential Required: Connect your Google Sheets credentials in Update Usage Log and Record Error Log.
Step 3: Set Up AI Orchestrator
Configure the AI layer that interprets input and coordinates optional tools.
- Open Chat Model Engine and select your OpenRouter model and temperature as needed.
- Open AI Orchestrator and attach Chat Model Engine as its language model.
- If you plan to use tools, keep Dispatch Email Alert, Retrieve Contact List, and Generate Calendar Event enabled and connected to AI Orchestrator.
Credential Required: Connect your OpenRouter credentials in Chat Model Engine.
Credential Required: Connect your OpenAI credentials in Transcribe Audio.
OpenAI credentials for Transcribe Audio are required when audio is sent through the workflow.
Step 4: Configure Input Mapping and Audio Handling
Normalize incoming data so both webhook and Telegram payloads feed the same processing path.
- In Map Webhook Payload, map incoming webhook fields into your internal schema (e.g., message text, media URL, sender).
- In Map Telegram Payload, map Telegram fields into the same schema as the webhook mapping.
- Configure Detect Audio vs Text to route audio messages to Fetch Media File and text messages directly to Map Text Fields.
- Verify the audio flow: Fetch Media File → Convert Media File → Transcribe Audio → Map Text Fields.
- Use Filter Records to drop incomplete or empty messages before they hit AI Orchestrator.
Step 5: Configure Output and Success Routing
Define how successful AI results are normalized and sent back to users and logs.
- Ensure AI Orchestrator outputs to Normalize Output and then to Update Usage Log.
- Verify the routing from Update Usage Log into Route Input Source for source-aware replies.
- Route Input Source outputs to both Post WhatsApp Reply and Send Success Notice in parallel—configure each response format.
Credential Required: Connect your Telegram API credentials in Send Success Notice.
Step 6: Add Error Handling
Capture AI or processing errors and route notifications appropriately.
- Confirm AI Orchestrator sends error output to Normalize Error Output.
- From Normalize Error Output, verify the flow to Record Error Log and then Route Error Source.
- Route Error Source outputs to both Post WhatsApp Error and Send Error Notice in parallel—configure each message payload.
Credential Required: Connect your Telegram API credentials in Send Error Notice.
Step 7: Test and Activate Your Workflow
Run end-to-end tests to validate both success and error paths before going live.
- Click Execute Workflow and send a test webhook to Webhook Intake or a test message to Telegram Trigger.
- Confirm successful runs create rows in Update Usage Log and trigger outputs from Post WhatsApp Reply and Send Success Notice.
- Simulate an error (e.g., invalid input) and verify Record Error Log, Post WhatsApp Error, and Send Error Notice receive the expected data.
- When everything looks correct, switch the workflow to Active for production use.
Troubleshooting Tips
- Google Sheets credentials can expire or need specific permissions. If things break, check the connected Google account access in n8n credentials and confirm the Sheet is shared to that account first.
- If you’re using Wait-style timing (for example, media processing and transcription), processing times vary. Bump up any wait duration or add retry logic if downstream nodes fail on empty responses.
- Default prompts in AI nodes are generic. Add your brand voice and “what to log” rules early in the AI Agent instructions or you’ll be editing outputs forever.
Quick Answers
About 30 minutes if your Telegram/WhatsApp and Google Sheets accounts are ready.
No. You’ll mostly connect credentials and paste in the right Sheet details.
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 OpenRouter/OpenAI usage, which depends on your model and how chatty your bot is.
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, and you probably should. You can change what gets logged by editing the “Map Text Fields” and “Update Usage Log” steps (for example, add a Client name, campaign, or internal project code). If you want only Telegram, disable the WhatsApp webhook route; if you want only WhatsApp, you can do the reverse. Many teams also tweak the AI Agent instructions so it returns a consistent “use case label” to store in Sheets.
Usually it’s a permissions issue or the wrong spreadsheet ID. Confirm the Google account in n8n has access to the target Sheet, then re-check the document ID and tab name inside the Google Sheets node. If you recently changed the sheet structure (renamed columns or the tab), update the mapping so the append action still matches. It can also fail if your Google authorization expired, so re-authenticate the credential and run one test execution.
Plenty for most small teams: hundreds of chat messages a day is realistic if your n8n instance is sized well. If you self-host, executions aren’t capped by n8n, but your server and API rate limits will be the real bottleneck. On n8n Cloud, your limit depends on the plan, so heavy usage may push you into a paid tier. Google Sheets can also become the limiting factor if you write too many rows too quickly, so batching or a database is better at higher volume.
Often, yes. This workflow includes branching (Telegram vs WhatsApp), error routing, and optional audio transcription, and those multi-step paths can get expensive or awkward in Zapier. n8n also gives you the self-host option, which is useful when message volume grows. That said, if your only goal is “send token usage to a sheet” with one source and no audio, Zapier or Make might feel simpler. If you want a second opinion, Talk to an automation expert and we’ll sanity-check your setup.
Once this is running, AI usage stops being a surprise and starts being a report. The workflow handles the repetitive logging so you can actually manage the spend.
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.