Skip to content

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.

  • Telegram account
  • Bot token from @BotFather
  • OpenClaw gateway running
  1. Create a bot with @BotFather:

    • Chat with @BotFather in Telegram
    • Run /newbot and follow prompts
    • Copy the bot token
  2. Configure OpenClaw (~/.openclaw/openclaw.json):

{
channels: {
telegram: {
enabled: true,
botToken: "123456789:ABCdefGHIjklMNOpqrsTUVwxyz",
dmPolicy: "pairing"
}
}
}
  1. Start the gateway:
Terminal window
openclaw gateway
  1. Test the bot:
    • Find your bot in Telegram
    • Send /start to begin pairing
{
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!"
}
}
}
}
}
{
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
}
}
}
}
  • 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
  • Pairing system: Secure user authentication
  • Session management: Persistent conversation context
  • Rich formatting: HTML and Markdown support
  • File sharing: Send and receive various file types
  • 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: Real-time updates, better for production
  • Polling: Simpler setup, good for development
  • Automatic failover: Switch between modes as needed
Terminal window
# Set bot token
openclaw config set channels.telegram.botToken "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
# Enable webhook
openclaw config set channels.telegram.webhook.enabled true
openclaw config set channels.telegram.webhook.url "https://your-domain.com/webhook/telegram"
# Test Telegram connection
openclaw channels test telegram
# Send a message
openclaw message send --channel telegram --target 123456789 --message "Hello from OpenClaw!"
# Send with formatting
openclaw message send --channel telegram --target 123456789 --message "<b>Bold text</b> and <i>italic</i>" --format html

Once configured, users can interact with your bot:

User: /start
Bot: Welcome to OpenClaw! I'm your AI assistant. Send /help to see available commands.
User: /help
Bot: Available commands:
/start - Start using the bot
/help - Show this help message
/status - Check bot status
/code - Execute code
/chat - Start a conversation
User: /status
Bot: 🤖 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 list
Bot: Here's a Python function to sort a list:
```python
def sort_list(lst):
"""Sort a list in ascending order."""
return sorted(lst)
# Example usage
numbers = [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
}
}
}
}
  1. Set up SSL (required for Telegram webhooks):
Terminal window
# 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 production
certbot certonly --standalone -d your-domain.com
  1. Configure firewall:
Terminal window
# Allow webhook port
sudo ufw allow 8443/tcp
{
channels: {
telegram: {
webhook: {
secret: "your-strong-secret-key",
allowedIPs: ["149.154.160.0/20", "91.108.4.0/22"], // Telegram IP ranges
dropPendingUpdates: true
}
}
}
}

Create custom command handlers in JavaScript:

~/.openclaw/handlers/telegram.js
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
}
}
};

Enable inline mode for inline queries:

{
channels: {
telegram: {
inline: {
enabled: true,
placeholder: "Ask OpenClaw anything...",
cacheTime: 300
}
}
}
}

Add interactive buttons to messages:

// Send message with buttons
await 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' }
]
]
}
});
  • 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
  • Data minimization: Only collect necessary user data
  • Consent management: Clear privacy policy
  • Data retention: Define data retention policies
  • GDPR compliance: Follow data protection regulations
  • Input validation: Validate all user inputs
  • Content filtering: Filter inappropriate content
  • Rate limiting: Prevent spam and abuse
  • Access control: Implement proper authorization

Bot Not Responding

Terminal window
# Check bot token
openclaw config get channels.telegram.botToken
# Test bot connection
openclaw channels test telegram
# Check gateway logs
openclaw gateway logs --filter telegram

Webhook Not Working

Terminal window
# Check webhook status
openclaw channels webhook status telegram
# Test webhook endpoint
curl -X POST https://your-domain.com/webhook/telegram
# Check SSL certificate
openssl s_client -connect your-domain.com:443

Commands Not Working

Terminal window
# Check command configuration
openclaw config get channels.telegram.commands
# Test specific command
openclaw channels test telegram --command help
# Check bot permissions with @BotFather
# /setprivacy
# /setjoingroups

Rate Limiting Issues

Terminal window
# Check rate limit status
openclaw channels status telegram --rate-limit
# Adjust rate limits
openclaw config set channels.telegram.rateLimit.maxRequests 20
# Monitor API usage
openclaw channels metrics telegram

Enable detailed logging for Telegram:

Terminal window
# Enable debug logging
openclaw config set logging.components.telegram debug
# Restart with debug
openclaw gateway restart --debug
# View Telegram logs
openclaw gateway logs --follow --filter telegram
  1. Bot Design

    • Clear command structure
    • Helpful error messages
    • Consistent user experience
    • Accessibility considerations
  2. Performance

    • Use webhooks for production
    • Implement proper caching
    • Monitor API usage
    • Optimize message handling
  3. Security

    • Validate all inputs
    • Use HTTPS for webhooks
    • Implement rate limiting
    • Regular security audits
  4. User Experience

    • Provide clear instructions
    • Use inline keyboards for better UX
    • Implement typing indicators
    • Handle errors gracefully
Terminal window
# Telegram channel management
openclaw channels test telegram
openclaw channels status telegram [--detailed]
openclaw channels webhook set telegram --url https://domain.com/webhook
openclaw channels webhook delete telegram
# Message operations
openclaw message send --channel telegram --target 123456789 --message "Hello"
openclaw message send --channel telegram --target 123456789 --file ./photo.jpg
openclaw message broadcast --channel telegram --message "Announcement"
# Configuration
openclaw config set channels.telegram.botToken "your-token"
openclaw config set channels.telegram.dmPolicy "allowlist"
openclaw config get channels.telegram
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. 🤖