Complete Telegram Bot Automation Tutorial
Target keywords: Telegram bot tutorial, OpenClaw Telegram, Telegram automation, AI Telegram bot
Introduction
Telegram is an ideal platform for building AI bots: free, open, and supportive of rich message formatting. This tutorial shows you how to create a powerful Telegram AI bot with OpenClaw.
What you will learn:
- Telegram bot creation
- OpenClaw integration
- Command handling
- Group management
- Advanced features
Estimated time: 30 minutes
Difficulty: Beginner
Prerequisites
What You Need
- A Telegram account (free)
- A Telegram Bot Token (obtained from BotFather)
- A public server (for the webhook)
- OpenClaw installed
Step 1: Create a Telegram Bot
1.1 Use BotFather
- Search for
@BotFatheron Telegram - Send
/newbot - Follow the prompts and enter:
- Bot name (display name)
- Bot username (must end with
bot, for examplemyaibot_bot)
1.2 Get the Token
BotFather will reply:
Done! Congratulations on your new bot.
You will find it at t.me/myaibot_bot
Use this token to access the HTTP API:
123456789:ABCdefGHIjklMNOpqrSTUvwxyz
Save this token carefully!
1.3 Configure the Bot
Set the bot information:
/setdescription - 设置描述
/setabouttext - 设置关于文本
/setuserpic - 设置头像
/setcommands - 设置命令列表
Example command list:
help - Get help
status - Check system status
chat - Start AI conversation
reset - Reset conversation
Step 2: Configure OpenClaw
2.1 Install the Telegram Skill
openclaw skill install telegram
2.2 Configure the Connection
Edit the configuration file:
openclaw config edit
Add:
skills:
telegram:
enabled: true
bot_token: "${TELEGRAM_BOT_TOKEN}" # Environment variable
webhook:
enabled: true
url: "https://yourdomain.com/webhook/telegram"
secret_token: "${WEBHOOK_SECRET}" # Optional, improves security
# Polling mode (for development/testing)
# polling:
# enabled: true
# interval: 1s
2.3 Set Environment Variables
export TELEGRAM_BOT_TOKEN="123456789:ABCdefGHIjklMNOpqrSTUvwxyz"
export WEBHOOK_SECRET="your_random_secret_string"
Step 3: Create an AI Agent
3.1 Basic Agent
openclaw agent create telegram-assistant
Configuration:
agent:
name: "Telegram AI Assistant"
model:
provider: openai
model: gpt-4o-mini
api_key: "${OPENAI_API_KEY}"
system_prompt: |
You are a helpful Telegram assistant.
Guidelines:
- Keep responses under 4000 characters (Telegram limit)
- Use Telegram Markdown formatting
- Be friendly and conversational
- Use emojis appropriately
memory:
enabled: true
max_messages: 20
3.2 Connect Telegram
routes:
telegram:
# Private chat messages
- pattern: "*"
agent: telegram-assistant
# Group messages (reply only when mentioned)
- pattern: "*"
agent: telegram-assistant
condition: "message.mentions_bot or message.reply_to_bot"
Step 4: Command Handling
4.1 Built-in Commands
skills:
telegram:
commands:
/start:
response: |
👋 Welcome! I'm your AI assistant.
Available commands:
/help - Show help
/chat - Start conversation
/reset - Clear history
/status - System status
/help:
action: send_help_message
/reset:
action: clear_conversation_history
response: "🗑️ Conversation history cleared!"
/status:
action: show_system_status
4.2 Custom Command Handlers
# ~/.openclaw/skills/telegram_commands.py
from openclaw import command, telegram
@command("/weather")
def weather_command(update, context):
"""Get weather for a location"""
location = update.message.text.replace("/weather", "").strip()
if not location:
return "Please provide a location: /weather New York"
# Call the weather API
weather = get_weather(location)
return f"🌤 Weather in {location}:\n{weather}"
@command("/remind")
def remind_command(update, context):
"""Set a reminder"""
# Parse the time
text = update.message.text.replace("/remind", "").strip()
# Create the reminder
create_reminder(update.chat.id, text)
return f"⏰ Reminder set: {text}"
Step 5: Advanced Features
5.1 Message Formatting
# Telegram Markdown is supported
message = """
*bold text*
_italic text_
[inline URL](http://www.example.com/)
`inline fixed-width code`
pre-formatted fixed-width code block
"""
# Send
telegram.send_message(chat_id, message, parse_mode="Markdown")
5.2 Buttons and Keyboards
from openclaw import telegram
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
# Inline buttons
keyboard = [
[InlineKeyboardButton("Option 1", callback_data="opt1")],
[InlineKeyboardButton("Option 2", callback_data="opt2")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
telegram.send_message(
chat_id,
"Choose an option:",
reply_markup=reply_markup
)
# Handle button clicks
@telegram.callback_handler
def handle_callback(update, context):
query = update.callback_query
if query.data == "opt1":
query.edit_message_text("You chose Option 1!")
elif query.data == "opt2":
query.edit_message_text("You chose Option 2!")
5.3 File Handling
@telegram.message_handler(content_types=['document'])
def handle_document(update, context):
file = update.message.document
# Download the file
file_path = telegram.download_file(file.file_id)
# Process the file
if file.mime_type == 'text/plain':
content = open(file_path).read()
summary = ai_summarize(content)
update.message.reply_text(f"📄 Summary:\n{summary}")
5.4 Group Management
skills:
telegram:
groups:
# Welcome new members
welcome:
enabled: true
message: |
Welcome {user_name} to {group_name}!
I'm the AI assistant. Mention me (@botname) to chat.
# Automatically delete spam
moderation:
enabled: true
rules:
- pattern: "(spam|scam)"
action: delete
- pattern: "http"
action: review
# Group statistics
stats:
enabled: true
command: "/stats"
Step 6: Production Deployment
6.1 Webhook Configuration
skills:
telegram:
webhook:
enabled: true
url: "https://api.yourdomain.com/webhook/telegram"
max_connections: 40
allowed_updates:
- message
- callback_query
- inline_query
6.2 Use Nginx as a Reverse Proxy
location /webhook/telegram {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
# Telegram requirements
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# Timeout settings
proxy_read_timeout 60s;
proxy_connect_timeout 60s;
}
6.3 System Service
[Unit]
Description=OpenClaw Telegram Bot
After=network.target
[Service]
Type=simple
User=openclaw
Environment=TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
Environment=OPENAI_API_KEY=${OPENAI_API_KEY}
ExecStart=/usr/local/bin/openclaw start
Restart=always
[Install]
WantedBy=multi-user.target
Troubleshooting
Issue 1: Webhook setup failed
Symptom: "Bad Request: bad webhook"
Fix:
# 1. Confirm HTTPS
curl -I https://yourdomain.com/webhook/telegram
# 2. Check the certificate
openssl s_client -connect yourdomain.com:443
# 3. Test with `getUpdates` (polling mode)
# Temporarily switch to polling mode for debugging
Issue 2: Bot does not respond
Symptom: Messages are sent but no reply is returned
Fix:
# 1. Check logs
openclaw logs | grep telegram
# 2. Confirm the agent is running
openclaw agent status telegram-assistant
# 3. Test a direct call
openclaw chat telegram-assistant "test"
Issue 3: Does not work in groups
Symptom: Private chat works, but the bot does not respond in groups
Fix:
# 1. Confirm the bot has group permissions
# Check the bot settings in Telegram
# 2. Check the group privacy settings
# @BotFather → /mybots → Bot Settings → Group Privacy
# Set it to "Turn off" (can receive all messages)
# 3. Confirm the bot is a group member
Best Practices
1. Error Handling
@telegram.error_handler
def handle_error(update, context):
"""Handle errors gracefully"""
logger.error(f"Update {update} caused error {context.error}")
if update.effective_message:
update.effective_message.reply_text(
"😅 Sorry, something went wrong. Please try again."
)
2. Rate Limiting
skills:
telegram:
rate_limit:
enabled: true
per_user: 30 # 30 messages per minute
per_chat: 60 # 60 messages per minute
3. Logging
logging:
telegram:
level: info
log_updates: true
log_responses: false # Protect privacy
Example Bot Features
Complete Configuration Example
# Smart assistant bot
skills:
telegram:
enabled: true
bot_token: "${TELEGRAM_BOT_TOKEN}"
features:
ai_chat:
enabled: true
agent: telegram-assistant
commands:
/start: welcome_message
/help: show_help
/weather: get_weather
/remind: set_reminder
/summary: summarize_text
/translate: translate_text
group_features:
welcome: true
moderation: true
stats: true
media:
process_images: true
process_documents: true
summarize_voice: true
Next Steps
Get more tutorials for free:
[Email subscription form]
Last updated: March 2026