How to Build an AI Social Media Manager Bot with n8n (Powered by Telegram)
Keeping your social media channels active is a full-time job — and most founders, creators, and small teams simply don’t have the bandwidth to do it consistently. What if you could send a voice note, a document, or a quick text to a Telegram bot and have it draft, get your approval, and publish a polished post to X and LinkedIn automatically?
That’s exactly what this n8n workflow builds: your own AI-powered social media manager, running 24/7 inside Telegram, connected to Google Gemini for smart content generation, and wired directly to your X (Twitter) and LinkedIn profiles.
Prefer to skip the setup? Grab the ready-made template → and be up and running in under 10 minutes.
What You’ll Build
- Send a text, voice note, or document to your Telegram bot — the AI understands all three formats
- The agent drafts a platform-appropriate post, respecting X’s 280-character limit and LinkedIn’s professional tone
- You review the draft in Telegram and approve it — nothing gets published without your explicit say-so
- With your approval, the bot publishes instantly to X (Twitter) and/or LinkedIn
- The bot remembers your brand voice, company details, and preferences over time — you stop repeating yourself in every session
How It Works — The Big Picture
The workflow uses a Telegram bot as the command center. Every incoming message is classified by type — text, document, voice, or button tap — and routed through the right processing pipeline before reaching a Google Gemini-powered AI Agent. The agent drafts posts, manages both short- and long-term memory, and uses LinkedIn and X tools to publish only after you approve.
┌──────────────────────────────────────────────────────────────────────┐ │ AI SMM MANAGER │ │ │ │ [Telegram Trigger] → [Set Context] → [Input Type Switch] │ │ │ │ │ ┌────────────────────────────────────┼────────────────┐ │ │ ↓ ↓ ↓ ↓ │ │ [Text] [Document] [Voice] [Callback] │ │ │ ↓ Download ↓ Download │ │ │ │ ↓ Encode ↓ Encode [If cm?] │ │ │ ↓ Gemini OCR ↓ Transcribe ↓ ↓ │ │ │ ↓ Doc Prompt ↓ Audio Prompt [Clear] [✗] │ │ └───────────┴────────────────────┘ │ │ ↓ │ │ [AI Agent] ←── [Gemini LLM] │ │ ↑ ↑ ↑ ↑ [Short-term Memory] │ │ │ │ │ └── [Retrieve Knowledge (vector)] │ │ │ │ └──── [Save Knowledge (sub-workflow)] │ │ │ └──────── [Create X (Twitter) Post] │ │ └──────────── [Create LinkedIn Post] │ │ ↓ │ │ [Split Response] → [Split Out] │ │ ↓ │ │ [Send Response via Telegram] │ └──────────────────────────────────────────────────────────────────────┘
What You’ll Need
- n8n (cloud or self-hosted, version 1.0+)
- Telegram Bot API key — create one for free via @BotFather in Telegram
- Google AI Studio API key — free at aistudio.google.com (powers Gemini 2.0 Flash)
- X (Twitter) Developer API — free developer account at developer.x.com
- LinkedIn OAuth credentials — create an app at the LinkedIn Developer Portal
- A companion n8n sub-workflow — “Save Vector Store Record” (included in the template pack) for long-term memory storage
Estimated build time: 45–60 minutes from scratch, or under 10 minutes with the template.
Part 1 — Bot Entrance and Input Preprocessing
1 Telegram Trigger (telegramTrigger)
This is the entry point. The Telegram Trigger node opens a webhook that listens for all incoming events from your bot — text messages, documents, voice notes, and inline button taps.
Configuration:
- Open the node and click “Credential for Telegram API”
- Paste your BotFather token and save
- Under “Updates”, enable:
message,callback_query,inline_query, and*
{
"message": {
"chat": { "id": 198472651, "type": "private", "first_name": "Sarah" },
"text": "Write a LinkedIn post about our product launch next Tuesday",
"message_id": 142
},
"update_id": 553043001
}
Tip: Add a “Restrict to chat IDs” filter so only your account can trigger the bot. Find your personal chat ID by messaging @userinfobot on Telegram.
2 Set Input Context (set)
This node normalizes the raw Telegram payload into clean, consistently named fields — regardless of whether the input is a text message, a file, or a voice note.
| Field | What it captures | Example |
|---|---|---|
chat_id | Sender’s chat ID (from message or callback) | 198472651 |
message_text | Text content of the message | "Write a post about our launch" |
update_type | Detected type: text, document, voice, callback | "text" |
file_id | Document file ID (if document sent) | "BQACAgIA..." |
file_mime_type | MIME type of document | "application/pdf" |
file_caption | Caption text sent with the document | "Our company overview" |
voice_file_id | Voice note file ID | "AwACAgIA..." |
3 Input Type Switch (switch)
Routes execution to the correct processing branch based on update_type:
- text → straight to AI Agent via Text Prompt
- document → Download → Encode → Gemini OCR → Document Prompt → AI Agent
- voice → Download → Encode → Gemini Transcribe → Audio Prompt → AI Agent
- callback → If node (checks whether it’s a memory-clear command)
Part 2 — Document and Audio Processing
4 Document Branch (Download → Encode → Describe)
When a user sends a PDF, presentation, or any file, three nodes work in sequence. Download document fetches the raw binary from Telegram using the file_id. Encode document converts the binary to base64. Describe document sends it to Gemini 2.0 Flash via HTTP POST:
{
"contents": [{
"parts": [
{ "text": "Extract all the information about the company or product from this document" },
{
"inline_data": {
"mime_type": "application/pdf",
"data": "JVBERi0xLjQgJeL..."
}
}
]
}]
}
Gemini returns a structured extraction of all company and product details, which gets injected into the AI Agent prompt alongside the document’s caption.
Tip: This works with PDFs, HTML files, Word docs, and most common formats. The mime_type is pulled automatically from Telegram’s download metadata.
5 Voice Branch (Download → Encode → Transcribe)
Voice messages follow the same pattern — Download Audio → Encode Audio → call Gemini with “Generate a transcript of the speech.” The transcript becomes the chatInput field, so the agent processes it exactly like a typed message.
Note: Telegram encodes all voice messages as OGG files. The workflow hardcodes "mime_type": "audio/ogg" in the Gemini request — do not change this value.
Part 3 — The AI Agent
6 AI Agent (agent)
The brain of the entire operation. The agent receives the normalized user input and decides autonomously what to do next: ask clarifying questions if context is missing, draft a post tailored to the target platform, send it to you for review, publish after your explicit approval, or save brand information to long-term memory.
The system message enforces a strict rule: nothing gets published without the user’s explicit “approved” signal. This is the safety net that keeps the bot from acting without consent.
| Tool | Purpose |
|---|---|
| Retrieve knowledge | Fetches relevant brand context from the vector store |
| Save knowledge | Calls the sub-workflow to save new information to vector memory |
| Create X (Twitter) post | Posts to X; enforces the 280-character limit |
| Create post in LinkedIn as a person | Posts from your personal LinkedIn profile |
| Create post in LinkedIn as a company | Posts from a company/organization page |
7 Google Gemini Chat Model + Memory
The agent is powered by Google Gemini via the lmChatGoogleGemini node. Two memory systems work in parallel:
Short-term memory (Buffer Window Memory): Keyed to the chat_id, this stores recent conversation history so the agent maintains context within a single Telegram session.
Long-term memory (In-Memory Vector Store + Gemini Embeddings): Powered by the embedding-001 model, this lets the agent remember brand voice, company info, and preferences across completely separate sessions.
Tip: The in-memory vector store resets when n8n restarts. For production use, replace it with a persistent store like Pinecone, Supabase pgvector, or Qdrant.
8 Memory Clear Callback
When a user taps an inline Telegram button with callback data "cm", the workflow routes to the If node, clears all buffer window memory via Chat Memory Manager, and sends a “Memory is cleaned” confirmation back to Telegram. Handy for switching between clients or starting fresh on a new campaign.
Part 4 — Response Delivery
9 Split + Send (code + telegram)
Telegram enforces a 4,096-character limit per message. The Split agent’s response node uses JavaScript to break the AI output into 3,000-character chunks, and Split Out iterates over each chunk. Every chunk is sent as a separate Telegram message so nothing is ever truncated.
function splitString(str, size) {
let result = [];
for (let i = 0; i < str.length; i += size) {
result.push(str.slice(i, i + size));
}
return result;
}
for (const item of $input.all()) {
const parts = splitString(item.json.output, 3000);
item.json.parts = parts;
}
return $input.all();
Full System Flow
User sends message (text / voice / document) to Telegram bot
│
▼
[Telegram Trigger] → [Set Input Context]
│
┌────────────────────────────┼───────────────────┐
▼ ▼ ▼
[text route] [document route] [voice route]
│ ↓ Download ↓ Download
│ ↓ Encode (base64) ↓ Encode (base64)
│ ↓ Gemini OCR ↓ Gemini Transcribe
│ ↓ Document Prompt ↓ Audio Prompt
└────────────────────┴──────────────────────┘
│
▼
[AI Agent]
┌─────────────────────────┐
↓ ↓
[X & LinkedIn Tools] [Memory: Save + Retrieve]
└─────────────────────────┘
│
▼
[Split Response (3,000 chars)]
│
▼
[Send each chunk via Telegram]
│
▼
User gets reply ✓
Testing Your Workflow
- Import the JSON and attach all credentials (see the Credentials Guide PDF)
- Activate the workflow — n8n registers the Telegram webhook automatically
- Open Telegram, find your bot, and send: "Write a LinkedIn post about how AI is changing small business marketing"
- Confirm the bot replies with a draft and asks for your approval
- Reply "approved" — check your LinkedIn profile for the published post
- Test a voice note: record 10 seconds describing a product feature and send it to the bot
- Test document processing: send a PDF of your company overview and ask the bot to write a post about it
| Problem | Likely Cause | Fix |
|---|---|---|
| Bot doesn't respond at all | Workflow not active | Toggle the Active switch in n8n |
| "Forbidden" error posting to X | Tweet exceeds 280 characters | The agent handles this — rephrase your brief to be shorter |
| Document not processed | Unsupported mime type | Stick to PDF, HTML, or DOCX formats |
| Memory lost after restart | In-memory vector store cleared | Switch to Pinecone or Qdrant for persistent memory |
| LinkedIn post fails | OAuth token expired | Re-authorize LinkedIn credentials in n8n settings |
| No response from bot | Gemini API quota exceeded | Check your AI Studio usage dashboard and upgrade if needed |
Frequently Asked Questions
Can I add more platforms like Instagram or Facebook?
Yes — n8n has native nodes for Facebook Pages and Instagram Business. Add them as additional tool nodes attached to the AI Agent, following the same pattern as the X and LinkedIn tools already in this workflow.
Does the bot ever post without my approval?
Never. The system message explicitly instructs the agent to always get explicit user approval before posting anything. The draft is always sent to Telegram first, and you can review, edit, or reject it before anything goes live.
Can I use this for multiple clients or brands?
The workflow is keyed by chat_id, so each Telegram conversation has separate memory. For multiple brands, create separate Telegram bots and run separate workflow instances — or extend the memory key to include a brand identifier prefix.
What happens if Gemini is unavailable?
The AI Agent node will throw an error and n8n will log it. For production use, add a retry setting (3 attempts, 5-second delay) on the AI Agent node and an error handler that sends you a fallback Telegram message so you know something went wrong.
Is my document content safe when processed through Gemini?
Your document data is sent to Google's API for processing. Review Google AI Studio's data usage policy at aistudio.google.com if confidentiality is a concern. For sensitive documents, consider replacing the Gemini HTTP calls with a self-hosted model via Ollama.
How do I teach the bot my brand voice?
Just tell it in plain language: "My company is Acme Corp, we sell B2B SaaS to HR teams, and our tone is professional but approachable." The Save Knowledge tool stores this automatically and the bot recalls it in all future sessions without you needing to repeat it.
🚀 Get the AI SMM Manager Template
Everything you need to deploy your own Telegram-powered social media bot: ready-to-import workflow JSON, Setup Guide PDF, and full Credentials Guide PDF — go from download to live bot in under 10 minutes.
Get the Template →Instant download · Works on n8n Cloud and self-hosted
What's Next?
- Add Instagram support via the Instagram Graph API as a new tool on the AI Agent node
- Schedule posts by connecting a Google Sheets queue and a Schedule Trigger to batch-publish at optimal times
- Add AI image generation using DALL-E or Flux to auto-create visuals for each post before publishing
- Multi-language support — instruct the agent to detect the user's language and draft posts in the same language automatically
- Analytics tracking — connect a Google Sheets node to log every post with timestamps so you can track what's performing