Telegram Integration
Telegram Integration
Section titled “Telegram Integration”OpenClaw integrates with Telegram via the Bot API using the grammY library. This allows you to create powerful Telegram bots that can handle direct messages, group chats, commands, and rich media.
Quick Setup
Section titled “Quick Setup”Prerequisites
Section titled “Prerequisites”- Telegram account
- Bot token from @BotFather
- OpenClaw gateway running
Basic Configuration
Section titled “Basic Configuration”-
Create a bot with @BotFather:
- Chat with @BotFather in Telegram
- Run
/newbotand follow prompts - Copy the bot token
-
Configure OpenClaw (
~/.openclaw/openclaw.json):
{ channels: { telegram: { enabled: true, botToken: "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", dmPolicy: "pairing" } }}- Start the gateway:
openclaw gateway- Test the bot:
- Find your bot in Telegram
- Send
/startto begin pairing
Configuration Options
Section titled “Configuration Options”Basic Settings
Section titled “Basic Settings”{ channels: { telegram: { // Bot configuration enabled: true, botToken: "123456789:ABCdefGHIjklMNOpqrsTUVwxyz",
// Direct message policy dmPolicy: "pairing", // "pairing", "allowlist", "denylist", "all" allowFrom: [123456789, 987654321], // User IDs blockFrom: [555555555],
// Group chat settings groups: { "*": { // All groups requireMention: true, mentionPatterns: ["/openclaw", "@openclaw"], allowedCommands: ["help", "status", "code"] } },
// Command handling commands: { enabled: true, prefix: "/", commands: { "start": "Welcome to OpenClaw! Send /help to see available commands.", "help": "Available commands:\n/help - Show this help\n/status - Check status\n/code - Execute code", "status": "Bot is running and ready to assist!" } } } }}Advanced Settings
Section titled “Advanced Settings”{ channels: { telegram: { // Webhook configuration webhook: { enabled: false, url: "https://your-domain.com/webhook/telegram", port: 8443, secret: "webhook-secret", dropPendingUpdates: true },
// Polling configuration (alternative to webhook) polling: { enabled: true, interval: 1000, timeout: 30000, limit: 100, allowedUpdates: ["message", "callback_query"] },
// Message handling messages: { maxMessageLength: 4096, parseMode: "HTML", // "HTML", "Markdown", "MarkdownV2" disableWebPagePreview: false, disableNotification: false, protectContent: false },
// Media settings media: { downloadPath: "~/.openclaw/media/telegram", maxSize: "20MB", autoDownload: false, supportedTypes: ["photo", "audio", "video", "document", "sticker"] },
// Rate limiting rateLimit: { enabled: true, maxRequests: 30, windowMs: 1000 },
// Error handling errorHandling: { retryAttempts: 3, retryDelay: 1000, logErrors: true } } }}Features
Section titled “Features”Bot Commands
Section titled “Bot Commands”- Built-in commands:
/start,/help,/status,/ping - Custom commands: Define your own command handlers
- Command descriptions: Auto-generated help menu
- Admin commands: Special commands for authorized users
Direct Messages
Section titled “Direct Messages”- Pairing system: Secure user authentication
- Session management: Persistent conversation context
- Rich formatting: HTML and Markdown support
- File sharing: Send and receive various file types
Group Chats
Section titled “Group Chats”- Mention-based activation: Respond only when mentioned
- Group commands: Special commands for group contexts
- Admin permissions: Control who can use admin features
- Privacy mode: Configurable message visibility
Webhooks vs Polling
Section titled “Webhooks vs Polling”- Webhooks: Real-time updates, better for production
- Polling: Simpler setup, good for development
- Automatic failover: Switch between modes as needed
Usage Examples
Section titled “Usage Examples”Basic Commands
Section titled “Basic Commands”# Set bot tokenopenclaw config set channels.telegram.botToken "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
# Enable webhookopenclaw config set channels.telegram.webhook.enabled trueopenclaw config set channels.telegram.webhook.url "https://your-domain.com/webhook/telegram"
# Test Telegram connectionopenclaw channels test telegram
# Send a messageopenclaw message send --channel telegram --target 123456789 --message "Hello from OpenClaw!"
# Send with formattingopenclaw message send --channel telegram --target 123456789 --message "<b>Bold text</b> and <i>italic</i>" --format htmlInteractive Usage
Section titled “Interactive Usage”Once configured, users can interact with your bot:
User: /startBot: Welcome to OpenClaw! I'm your AI assistant. Send /help to see available commands.
User: /helpBot: Available commands:/start - Start using the bot/help - Show this help message/status - Check bot status/code - Execute code/chat - Start a conversation
User: /statusBot: 🤖 Bot Status:- Status: Running- Uptime: 1h 23m- Messages processed: 156- Active users: 12- Model: Claude 3.5 Sonnet
User: Write a Python function to sort a listBot: Here's a Python function to sort a list:
```pythondef sort_list(lst): """Sort a list in ascending order.""" return sorted(lst)
# Example usagenumbers = [3, 1, 4, 1, 5, 9, 2, 6]sorted_numbers = sort_list(numbers)print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 6, 9]User: @openclaw What’s the weather like? Bot: I don’t have access to real-time weather data, but I can help you create a weather checker using a weather API! Would you like me to write a script for that?
## Webhook Setup
### Using Webhooks (Production)
For production deployments, webhooks are recommended over polling:
1. **Configure webhook**:```json5{ channels: { telegram: { webhook: { enabled: true, url: "https://your-domain.com/webhook/telegram", port: 8443, secret: "your-webhook-secret" }, polling: { enabled: false } } }}- Set up SSL (required for Telegram webhooks):
# Generate self-signed certificate (for testing)openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
# Or use Let's Encrypt for productioncertbot certonly --standalone -d your-domain.com- Configure firewall:
# Allow webhook portsudo ufw allow 8443/tcpWebhook Security
Section titled “Webhook Security”{ channels: { telegram: { webhook: { secret: "your-strong-secret-key", allowedIPs: ["149.154.160.0/20", "91.108.4.0/22"], // Telegram IP ranges dropPendingUpdates: true } } }}Advanced Features
Section titled “Advanced Features”Custom Command Handlers
Section titled “Custom Command Handlers”Create custom command handlers in JavaScript:
module.exports = { commands: { weather: async (ctx, args) => { const location = args.join(' '); // Fetch weather data const weather = await getWeather(location); return `Weather in ${location}: ${weather.temp}°C, ${weather.description}`; },
code: async (ctx, args) => { const code = args.join(' '); // Execute code safely const result = await executeCode(code); return `Result:\n\`\`\`${result}\`\`\``; } },
onMessage: async (ctx) => { // Handle all messages if (ctx.message.text && ctx.message.text.includes('help')) { // Custom help logic } }};Inline Mode
Section titled “Inline Mode”Enable inline mode for inline queries:
{ channels: { telegram: { inline: { enabled: true, placeholder: "Ask OpenClaw anything...", cacheTime: 300 } } }}Callback Buttons
Section titled “Callback Buttons”Add interactive buttons to messages:
// Send message with buttonsawait ctx.reply('Choose an option:', { reply_markup: { inline_keyboard: [ [ { text: 'Help', callback_data: 'help' }, { text: 'Status', callback_data: 'status' } ], [ { text: 'Start Chat', callback_data: 'chat' } ] ] }});Security Considerations
Section titled “Security Considerations”Bot Token Security
Section titled “Bot Token Security”- Environment variables: Store tokens in environment variables
- File permissions: Restrict access to config files
- Token rotation: Regularly rotate bot tokens
- Access logs: Monitor token usage
User Privacy
Section titled “User Privacy”- Data minimization: Only collect necessary user data
- Consent management: Clear privacy policy
- Data retention: Define data retention policies
- GDPR compliance: Follow data protection regulations
Content Security
Section titled “Content Security”- Input validation: Validate all user inputs
- Content filtering: Filter inappropriate content
- Rate limiting: Prevent spam and abuse
- Access control: Implement proper authorization
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”Bot Not Responding
# Check bot tokenopenclaw config get channels.telegram.botToken
# Test bot connectionopenclaw channels test telegram
# Check gateway logsopenclaw gateway logs --filter telegramWebhook Not Working
# Check webhook statusopenclaw channels webhook status telegram
# Test webhook endpointcurl -X POST https://your-domain.com/webhook/telegram
# Check SSL certificateopenssl s_client -connect your-domain.com:443Commands Not Working
# Check command configurationopenclaw config get channels.telegram.commands
# Test specific commandopenclaw channels test telegram --command help
# Check bot permissions with @BotFather# /setprivacy# /setjoingroupsRate Limiting Issues
# Check rate limit statusopenclaw channels status telegram --rate-limit
# Adjust rate limitsopenclaw config set channels.telegram.rateLimit.maxRequests 20
# Monitor API usageopenclaw channels metrics telegramDebug Mode
Section titled “Debug Mode”Enable detailed logging for Telegram:
# Enable debug loggingopenclaw config set logging.components.telegram debug
# Restart with debugopenclaw gateway restart --debug
# View Telegram logsopenclaw gateway logs --follow --filter telegramBest Practices
Section titled “Best Practices”-
Bot Design
- Clear command structure
- Helpful error messages
- Consistent user experience
- Accessibility considerations
-
Performance
- Use webhooks for production
- Implement proper caching
- Monitor API usage
- Optimize message handling
-
Security
- Validate all inputs
- Use HTTPS for webhooks
- Implement rate limiting
- Regular security audits
-
User Experience
- Provide clear instructions
- Use inline keyboards for better UX
- Implement typing indicators
- Handle errors gracefully
API Reference
Section titled “API Reference”Channel Commands
Section titled “Channel Commands”# Telegram channel managementopenclaw channels test telegramopenclaw channels status telegram [--detailed]openclaw channels webhook set telegram --url https://domain.com/webhookopenclaw channels webhook delete telegram
# Message operationsopenclaw message send --channel telegram --target 123456789 --message "Hello"openclaw message send --channel telegram --target 123456789 --file ./photo.jpgopenclaw message broadcast --channel telegram --message "Announcement"
# Configurationopenclaw config set channels.telegram.botToken "your-token"openclaw config set channels.telegram.dmPolicy "allowlist"openclaw config get channels.telegramConfiguration Schema
Section titled “Configuration Schema”interface TelegramConfig { enabled: boolean; botToken: string; dmPolicy: "pairing" | "allowlist" | "denylist" | "all"; allowFrom?: number[]; blockFrom?: number[]; groups?: { [groupId: string]: { requireMention?: boolean; mentionPatterns?: string[]; allowedCommands?: string[]; }; }; commands?: { enabled: boolean; prefix: string; commands?: { [command: string]: string }; }; webhook?: { enabled: boolean; url: string; port: number; secret?: string; dropPendingUpdates?: boolean; }; polling?: { enabled: boolean; interval?: number; timeout?: number; limit?: number; allowedUpdates?: string[]; }; messages?: { maxMessageLength?: number; parseMode?: "HTML" | "Markdown" | "MarkdownV2"; disableWebPagePreview?: boolean; disableNotification?: boolean; protectContent?: boolean; }; media?: { downloadPath?: string; maxSize?: string; autoDownload?: boolean; supportedTypes?: string[]; }; rateLimit?: { enabled: boolean; maxRequests: number; windowMs: number; };}Your Telegram bot is now ready! You can start building powerful conversational AI experiences with OpenClaw. 🤖