1167 words
6 minutes
Building a Telegram Bot with n8n - Complete Step-by-Step Guide

Building a Telegram Bot with n8n - Complete Step-by-Step Guide#

Telegram bots are incredibly powerful tools that can automate tasks, provide information, and interact with users in real-time. With n8n, creating a sophisticated Telegram bot becomes surprisingly simple, even without extensive programming knowledge.

In this comprehensive guide, we’ll walk through creating a Telegram bot from scratch using n8n, covering everything from basic commands to advanced integrations.

What You’ll Learn#

By the end of this tutorial, you’ll have built a Telegram bot that can:

  • Respond to user commands
  • Fetch data from external APIs
  • Send automated notifications
  • Handle file uploads and downloads
  • Integrate with other services like Google Sheets, weather APIs, and more

Prerequisites#

Before we start, make sure you have:

  • A Telegram account
  • Access to n8n (cloud or self-hosted)
  • Basic understanding of n8n workflows (check our Getting Started guide)

Step 1: Creating Your Telegram Bot#

1.1 Talk to BotFather#

First, we need to create a bot using Telegram’s BotFather:

  1. Open Telegram and search for @BotFather
  2. Start a conversation with /start
  3. Create a new bot with /newbot
  4. Choose a name for your bot (e.g., “My n8n Helper Bot”)
  5. Choose a unique username ending with “bot” (e.g., “my_n8n_helper_bot”)

1.2 Save Your Bot Token#

BotFather will provide you with a bot token that looks like this:

123456789:ABCdefGHIjklMNOpqrsTUVwxyz

⚠️ Important: Keep this token secure and never share it publicly!

1.3 Optional: Customize Your Bot#

You can enhance your bot’s appearance:

  • /setdescription - Set bot description
  • /setabouttext - Set about text
  • /setuserpic - Upload a profile picture
  • /setcommands - Set command menu

Step 2: Setting Up n8n Webhook#

2.1 Create a New Workflow#

  1. Open n8n and create a new workflow
  2. Name it “Telegram Bot Handler”

2.2 Add Telegram Trigger#

  1. Add a Telegram Trigger node as your starting point

  2. Configure the node:

    • Bot Token: Paste your bot token from BotFather
    • Updates: Select “All Updates” to capture all messages
    • Property: Set to “message”
  3. Click “Test” to verify the connection

2.3 Set Up Webhook (Alternative Method)#

If you prefer using webhooks:

  1. Add a Webhook node instead of Telegram Trigger
  2. Copy the webhook URL
  3. Set up the webhook with Telegram API:
Terminal window
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-d "url=<YOUR_WEBHOOK_URL>"

Step 3: Building Basic Bot Commands#

3.1 Add Message Processing Logic#

Let’s create a bot that responds to different commands:

  1. Add a Switch Node after the Telegram Trigger
  2. Configure routing based on message content:
// Route 1: Start command
{
{
$json.message.text === "/start";
}
}
// Route 2: Help command
{
{
$json.message.text === "/help";
}
}
// Route 3: Weather command
{
{
$json.message.text.startsWith("/weather");
}
}
// Route 4: Random fact
{
{
$json.message.text === "/fact";
}
}
// Default: Unknown command
{
{
true;
}
}

3.2 Create Response Handlers#

For each route, add Telegram nodes to send responses:

Start Command Response#

// Message text
Welcome to My n8n Bot! 🤖
I can help you with:
/weather [city] - Get weather information
/fact - Random interesting fact
/help - Show this help message
What would you like to do?

Weather Command Handler#

  1. Add HTTP Request node to fetch weather data:

    • URL: https://api.openweathermap.org/data/2.5/weather
    • Parameters:
      {
      "q": "{{ $json.message.text.split(' ').slice(1).join(' ') }}",
      "appid": "YOUR_WEATHER_API_KEY",
      "units": "metric"
      }
  2. Add Telegram response with weather information:

    🌤️ Weather in {{ $json.name }}:
    Temperature: {{ $json.main.temp }}°C
    Feels like: {{ $json.main.feels_like }}°C
    Humidity: {{ $json.main.humidity }}%
    Description: {{ $json.weather[0].description }}

Random Fact Handler#

  1. Add HTTP Request node:

    • URL: https://uselessfacts.jsph.pl/random.json?language=en
    • Method: GET
  2. Add Telegram response:

    🧠 Random Fact:
    {{ $json.text }}

Step 4: Advanced Bot Features#

4.1 File Upload Handler#

Add capability to handle photos and documents:

  1. Add Switch condition for file uploads:

    {
    {
    $json.message.photo !== undefined ||
    $json.message.document !== undefined;
    }
    }
  2. Process the file:

    // For photos
    {
    {
    $json.message.photo
    ? $json.message.photo.slice(-1)[0].file_id
    : $json.message.document.file_id;
    }
    }
  3. Download and process the file using HTTP Request to Telegram’s getFile API

4.2 Inline Keyboards#

Create interactive buttons:

// In Telegram node, Additional Parameters
{
"reply_markup": {
"inline_keyboard": [
[
{"text": "Weather 🌤️", "callback_data": "weather"},
{"text": "Random Fact 🧠", "callback_data": "fact"}
],
[
{"text": "Help ❓", "callback_data": "help"}
]
]
}
}

4.3 User Data Persistence#

Store user preferences using Google Sheets or database:

  1. Add Google Sheets node to store user data
  2. Track user interactions and preferences
  3. Personalize responses based on user history

Step 5: Integration Examples#

5.1 RSS Feed Monitor Bot#

Create a bot that sends news updates:

  1. Add RSS Feed Read node (scheduled trigger)
  2. Filter new articles from the last hour
  3. Send updates to subscribers via Telegram

5.2 Server Monitoring Bot#

Monitor your servers and get alerts:

  1. Add HTTP Request nodes to check server status
  2. Use IF nodes to detect issues
  3. Send alerts to admin chat

5.3 Task Management Bot#

Integrate with project management tools:

  1. Connect to Notion/Trello/Asana APIs
  2. Create tasks via Telegram commands
  3. Get task updates and notifications

Step 6: Error Handling and Best Practices#

6.1 Error Handling#

Add robust error handling:

// In error workflow
{
"chat_id": "{{ $json.message.chat.id }}",
"text": "Sorry, something went wrong. Please try again later."
}

6.2 Rate Limiting#

Implement rate limiting to prevent spam:

  1. Use Set node to track user request times
  2. Add IF conditions to check request frequency
  3. Respond appropriately to excessive requests

6.3 Security Considerations#

  • Validate all inputs from users
  • Use environment variables for sensitive data
  • Implement user authentication for admin commands
  • Log important events for monitoring

Step 7: Testing and Deployment#

7.1 Testing Your Bot#

  1. Test each command individually
  2. Verify error scenarios work correctly
  3. Check file upload/download functionality
  4. Test with multiple users simultaneously

7.2 Monitoring and Analytics#

Track bot performance:

  1. Log user interactions to Google Sheets
  2. Monitor response times and error rates
  3. Track popular commands and usage patterns

7.3 Scaling Considerations#

For high-traffic bots:

  • Use webhook mode instead of polling
  • Implement queue systems for heavy processing
  • Consider database storage for large datasets
  • Set up monitoring alerts for failures

Real-World Bot Examples#

1. Customer Support Bot#

// Route customer queries to appropriate departments
switch ($json.message.text.toLowerCase()) {
case "billing":
return "billing_team";
case "technical":
return "tech_support";
default:
return "general_support";
}

2. E-commerce Order Bot#

// Check order status
const orderNumber = $json.message.text.match(/\d+/)[0];
// Query your e-commerce API
// Return order status and tracking information

3. Content Aggregator Bot#

// Fetch latest articles from multiple sources
// Filter by user preferences
// Send personalized content digest

Troubleshooting Common Issues#

Bot Not Responding#

  1. Check bot token is correct and active
  2. Verify webhook URL is accessible
  3. Check n8n workflow is active and running
  4. Review execution logs for errors

API Rate Limits#

  1. Implement proper delays between requests
  2. Cache frequently requested data
  3. Use batch operations where possible

Message Formatting Issues#

  1. Test message formatting with Telegram’s parse modes
  2. Escape special characters properly
  3. Validate message length (Telegram has limits)

Advanced Tips and Tricks#

1. Multi-language Support#

// Detect user language
const userLang = $json.message.from.language_code || "en";
// Return appropriate response
const responses = {
en: "Hello!",
es: "¡Hola!",
fr: "Bonjour!",
};
return responses[userLang] || responses["en"];

2. Context Awareness#

// Store conversation state
const userId = $json.message.from.id;
const currentState = getUserState(userId);
// Handle responses based on context
if (currentState === "waiting_for_city") {
// Process city name for weather
return processWeatherRequest($json.message.text);
}

3. Rich Media Responses#

// Send photos with captions
{
"chat_id": "{{ $json.message.chat.id }}",
"photo": "https://example.com/weather-image.jpg",
"caption": "Current weather conditions"
}

Conclusion#

Building a Telegram bot with n8n opens up endless possibilities for automation and user interaction. From simple command responses to complex integrations with external services, n8n’s visual workflow builder makes bot development accessible to everyone.

Key takeaways:

  • Start simple with basic commands and gradually add complexity
  • Always implement error handling for robust operation
  • Test thoroughly before deploying to users
  • Monitor performance and user feedback continuously
  • Keep security in mind when handling user data

The combination of Telegram’s powerful bot API and n8n’s automation capabilities creates a perfect platform for building sophisticated, useful bots that can integrate with virtually any service or API.

Ready to build your own Telegram bot? Start with a simple command handler and expand from there. The possibilities are limitless!


Want to see more automation tutorials? Check out our complete n8n guide and start automating your workflows today.

Building a Telegram Bot with n8n - Complete Step-by-Step Guide
https://antonio-roth.icanse.eu.org/posts/telegram-bot-n8n-tutorial/
Author
Antonio Roth
Published at
2025-08-28
License
CC BY-NC-SA 4.0