How to Create an AI Bot in Telegram

Build an AI-powered Telegram bot with conversation and image generation

IntegrationsIntermediate 15 min

How to Create an AI Bot in Telegram

Build an AI-powered Telegram bot with conversation and image generation

By Yulia Dmitrievna
2024
TelegramAIBotChatGPTDALL-E

Overview

Create a sophisticated Telegram AI chatbot using n8n that can hold natural conversations with ChatGPT, generate images with DALL-E, support multiple languages, and enhance responses with emojis. This tutorial covers the complete workflow from bot registration to deployment.

What You'll Build

A full-featured Telegram bot with AI capabilities that can chat naturally, generate images on command, and provide an engaging user experience.

  • Natural language conversation with ChatGPT
  • Image generation using DALL-E 2
  • Emoji-enhanced responses
  • Multi-language support
  • Typing indicators for better UX
  • Command handling (/start, /image, etc.)

Prerequisites

  • Telegram account
  • n8n instance (cloud or self-hosted)
  • OpenAI API key with GPT and DALL-E access
  • Basic understanding of chatbot concepts

Step 0: Register Your Bot

Use Telegram's BotFather to create and configure your bot.

  • Open Telegram and search for @BotFather
  • Send /newbot command
  • Choose a name for your bot
  • Choose a username (must end in 'bot')
  • Save the API token provided
  • Optional: Set bot description and profile picture

Step 1: Set Up Telegram Trigger

Configure n8n to receive messages from your Telegram bot.

json
{
  "updates": ["message"],
  "additionalFields": {
    "download": false
  }
}

Step 2: Add Typing Indicator

Send a 'typing' action to show users the bot is processing their message.

json
{
  "chatId": "={{$json.message.chat.id}}",
  "action": "typing"
}

Step 3: Preprocess User Input

Extract and prepare the user's message for AI processing.

javascript
// Extract user message
const message = $json.message.text;
const chatId = $json.message.chat.id;
const userId = $json.message.from.id;

// Determine request type
let requestType = 'chat';
if (message.startsWith('/image')) {
  requestType = 'image';
  message = message.replace('/image', '').trim();
} else if (message.startsWith('/start')) {
  requestType = 'welcome';
}

return {
  message,
  chatId,
  userId,
  requestType
};

Step 4: Route Requests

Use a Switch node to route different types of requests to appropriate handlers.

  • Chat requests → ChatGPT conversation flow
  • Image requests → DALL-E image generation
  • Welcome message → Send bot introduction
  • Unknown commands → Help message

Step 5: Configure ChatGPT Conversation

Set up OpenAI node for natural language conversation.

text
System Message:
You are a helpful and friendly Telegram bot assistant. Provide concise, accurate answers to user questions. Use emojis occasionally to make responses more engaging. Keep responses under 300 words for readability in Telegram. Be conversational and helpful.

User: {{$json.message}}

Step 6: Configure DALL-E Image Generation

Set up image generation for /image commands.

json
{
  "model": "dall-e-2",
  "prompt": "={{$json.message}}",
  "size": "512x512",
  "quality": "standard",
  "n": 1
}

Step 7: Send Responses

Configure Telegram nodes to send text or image responses back to users.

json
{
  "chatId": "={{$json.chatId}}",
  "text": "={{$json.response}}",
  "additionalFields": {
    "parse_mode": "Markdown",
    "disable_web_page_preview": false
  }
}

Advanced Features

Enhance your bot with additional capabilities.

  • Add conversation memory to maintain context
  • Implement user authentication and personalization
  • Create inline keyboards for interactive menus
  • Add file upload and processing capabilities
  • Implement multi-step conversations with state management
  • Add analytics to track usage patterns

Cost Considerations

  • Bot registration: Free
  • n8n hosting: ~$5-20/month (VPS or cloud)
  • OpenAI API: Pay-per-use (~$0.002 per message with GPT-3.5)
  • DALL-E: ~$0.016-0.020 per image
  • Total estimated: $10-50/month depending on usage

Best Practices

  • Implement rate limiting to prevent abuse
  • Set message length limits to control costs
  • Use GPT-3.5-turbo for faster, cheaper responses
  • Cache frequently asked questions
  • Monitor API usage and set budget alerts
  • Implement error messages for failed requests
  • Add help commands and bot instructions

Conclusion

Creating an AI-powered Telegram bot with n8n is straightforward and doesn't require complex coding. The combination of Telegram's user-friendly platform, OpenAI's powerful models, and n8n's visual workflow builder makes it accessible to developers of all skill levels. Start with basic conversation, then gradually add features like image generation and advanced interactions.

Next Steps

  • Add conversation memory for contextual responses
  • Implement user preference storage
  • Create specialized bot commands for specific tasks
  • Add support for voice messages and transcription
  • Integrate with external APIs and databases
  • Build multi-bot ecosystem for different purposes
  • Implement A/B testing for prompt optimization