An AI-powered multi-channel agent running on Cloudflare Workers with support for Telegram, Discord, and WhatsApp. Features webhook integration, memory database, file storage, and natural language actions.
-
Multi-Channel Support
- Telegram Bot with webhook integration
- Discord Bot with slash commands and interactions
- WhatsApp Cloud API integration
- Auto-detect and activate channels based on available credentials
- Same commands work across all channels
-
AI Capabilities using Cloudflare AI Gateway (Llama 2)
-
Memory Database with Cloudflare D1 for storing important memories
-
File Storage with Cloudflare R2
-
KV Storage for credentials and caching
-
Natural Language Actions
- Send/share files
- Review/analyze files
- Store and recall memories
- Move files between channels
- Create automations
-
Async Processing for non-blocking responses
-
Secret Token Validation for security
-
Serverless - no server management needed
- Runtime: Cloudflare Workers
- Framework: Hono (lightweight web framework)
- Language: TypeScript
- Database: Cloudflare D1 (SQLite)
- Storage: Cloudflare R2 (S3-compatible)
- Cache: Cloudflare KV
- AI: Cloudflare AI Gateway
- Channels:
- Telegram:
@codebam/cf-workers-telegram-bot - Discord: Discord.js (API-based)
- WhatsApp: WhatsApp Cloud API
- Telegram:
cloudbrain/
├── src/
│ ├── index.ts # Main worker entry point
│ ├── channels/
│ │ ├── base.ts # Base channel interface
│ │ ├── telegram.ts # Telegram channel adapter
│ │ ├── discord.ts # Discord channel adapter
│ │ ├── whatsapp.ts # WhatsApp channel adapter
│ │ └── manager.ts # Channel manager & router
│ ├── db/
│ │ └── memory.ts # Memory database layer
│ ├── skills/
│ │ └── index.ts # Natural language actions
│ └── types.ts # TypeScript types
├── wrangler.toml # Cloudflare Workers config
├── package.json # Dependencies
├── tsconfig.json # TypeScript config
└── .env.example # Environment variables template
- Node.js 18+
- Cloudflare account
- Telegram bot token (from @BotFather)
- Wrangler CLI
# Navigate to cloudbrain directory
cd cloudbrain
# Install dependencies
npm install
# Copy environment template
cp .env.example .env.local
# Edit .env.local with your credentialsCloudBrain uses Cloudflare KV to store credentials securely for all channels.
# Create production namespace
wrangler kv:namespace create "cloudbrain"
# Create preview namespace (for testing)
wrangler kv:namespace create "cloudbrain" --preview- Go to Cloudflare Dashboard → Workers & Pages → CloudBrain
- Click Settings → Bindings
- Click Add binding → KV Namespace
- Fill in:
- Variable name:
SECRETS(must be exactly this) - KV Namespace: Select
cloudbrainfrom dropdown
- Variable name:
- Click Save and Deploy
That's it! The code automatically detects the binding.
Add credentials for the channels you want to use:
Telegram (optional):
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID SECRET_TELEGRAM_API_TOKEN "your_bot_token"
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID TELEGRAM_OWNER_ID "your_telegram_id"Discord (optional):
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID DISCORD_BOT_TOKEN "your_bot_token"
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID DISCORD_CLIENT_ID "your_client_id"
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID DISCORD_WEBHOOK_URL "your_webhook_url"WhatsApp (optional):
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID WHATSAPP_PHONE_NUMBER_ID "your_phone_number_id"
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID WHATSAPP_BUSINESS_ACCOUNT_ID "your_business_account_id"
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID WHATSAPP_ACCESS_TOKEN "your_access_token"
wrangler kv:key put --namespace-id=YOUR_NAMESPACE_ID WHATSAPP_VERIFY_TOKEN "your_verify_token"Where to get these values:
- Telegram: Get from @BotFather and @userinfobot
- Discord: Get from Discord Developer Portal
- WhatsApp: Get from Meta Business Platform
wrangler deployCloudBrain automatically detects which channels are configured:
- If Telegram credentials are present → Telegram channel activated
- If Discord credentials are present → Discord channel activated
- If WhatsApp credentials are present → WhatsApp channel activated
- All active channels work simultaneously
- Same commands work across all channels
- ✅ No manual ID editing: Bind in dashboard, code auto-detects
- ✅ No wrangler.toml changes: Binding is in Cloudflare dashboard
- ✅ Survives all builds: Binding persists in dashboard
- ✅ CI/CD safe: No configuration files to manage
- ✅ Open-source friendly: Same setup for all contributors
- ✅ Multi-channel ready: Add/remove channels by adding/removing credentials
# Start local development server
wrangler dev
# The worker will be available at http://localhost:8787curl http://localhost:8787/curl -X POST http://localhost:8787/api/test \
-H "X-Account-ID: your_account_id" \
-H "Content-Type: application/json" \
-d '{
"message": "Hello CloudBrain",
"userId": 987654321
}'curl http://localhost:8787/api/webhook-statuscurl http://localhost:8787/api/config# Build and deploy
wrangler deploy
# Deploy to specific environment
wrangler deploy --env production# Stream live logs
wrangler tail
# View logs with filters
wrangler tail --format jsonThe webhook is automatically registered on first request. To manually register:
curl http://localhost:8787/api/webhook-statuscurl http://localhost:8787/api/webhook-unregisterSend a message to your Telegram bot. The bot should respond within 1-2 seconds.
POST /- Telegram webhook (default)POST /telegram- Telegram webhook (explicit)POST /discord- Discord webhookPOST /whatsapp- WhatsApp webhook
GET /health- Health check with active channelsGET /test- Test endpoint
GET /setup/telegram?token=YOUR_TOKEN- Setup Telegram webhookGET /setup/discord?token=YOUR_TOKEN- Setup Discord webhookGET /setup/whatsapp?token=YOUR_TOKEN- Setup WhatsApp webhook
Send these commands to your bot:
/help - Show available commands
/models - List available AI models
/storage - List stored files
/database - Show database tables
/automations - List automations
/status - Check bot health
/ping - Test connection
Or just send a message for natural language processing.
CloudBrain understands natural language commands across all channels:
"send me that file"
"share that document"
"give me the image"
"review that file"
"check that document"
"analyze that image"
"remember this"
"save this information"
"note this down"
"move this from telegram to discord"
"transfer that file to whatsapp"
"copy this from discord to telegram"
"make automation for daily reports"
"create automation to check prices"
"setup automation for notifications"
"what did I tell you?"
"remind me about that"
"recall my memories"
- Channel Manager detects available credentials in KV
- Initializes active channels (Telegram, Discord, WhatsApp)
- Routes incoming webhooks to appropriate channel handler
- Processes message with AI
- Executes natural language actions if detected
- Stores important memories in D1 database
- Sends response back through the same channel
- Incoming webhook →
POST /(or/telegram,/discord,/whatsapp) - Validate secret token from channel-specific headers
- Return 200 OK immediately (channel requirement)
- Process message asynchronously in background
- Send response back to user
- Parse message from channel-specific format
- Extract intent using AI (text, image, action, etc.)
- Execute action based on intent (if natural language action detected)
- Generate response using AI with system prompt
- Store memory if important (importance >= 5)
- Send to user via appropriate channel
- Auto-creates D1 table on first request
- Stores important conversations with importance scores
- Supports search across all memories
- Automatic cleanup of old memories (configurable)
- Per-user memories with channel tracking
- Send files across channels
- Move files between channels
- Store files in R2 storage
- Retrieve files from R2
- Share files with natural language commands
-
Check KV credentials
wrangler kv:key list --namespace-id=YOUR_NAMESPACE_ID
-
Verify credentials are correct
- Telegram: Token format should be
123456789:ABCdefGHI... - Discord: Token should start with
MTA... - WhatsApp: Token should be a long string
- Telegram: Token format should be
-
Check logs
wrangler tail
-
Check if channel is active
curl https://cloudbrain.workers.dev/health
-
Verify credentials in KV
wrangler kv:key get --namespace-id=YOUR_NAMESPACE_ID CHANNEL_CREDENTIAL_NAME
-
Test channel webhook
- Telegram: Send a message to your bot
- Discord: Send a slash command
- WhatsApp: Send a message to your WhatsApp number
-
Check webhook status
curl https://cloudbrain.workers.dev/health
-
Check logs in real-time
wrangler tail
-
Verify secret tokens
- Each channel has its own secret token
- Tokens must match exactly
-
Test with API (without channel)
curl -X POST https://cloudbrain.workers.dev/api/test \ -H "Content-Type: application/json" \ -d '{"message": "test"}'
- Check environment variables are set
- Verify Cloudflare credentials
- Check wrangler.toml syntax
- Review build logs
- Verify AI binding in wrangler.toml
- Check Cloudflare AI Gateway is enabled
- Review error logs
- Check D1 database is bound in wrangler.toml
- Verify database exists in Cloudflare dashboard
- Check database permissions
- Review D1 logs
# Development
npm run dev # Start local dev server
# Building
npm run build # Build TypeScript
# Deployment
npm run deploy # Deploy to Cloudflare Workers
# Utilities
npm run format # Format code
npm run lint # Lint codehono- Web framework@cloudflare/workers-types- Cloudflare types
typescript- Type safetywrangler- Cloudflare CLI@types/node- Node types
- Cold start: ~200ms (Cloudflare Workers)
- Response time: <1 second
- Concurrent requests: Unlimited
- Storage: 1GB KV, 100GB R2 (free tier)
- Database: 5GB D1 (free tier)
- Secret token validation - Prevents unauthorized access
- Owner ID check - Only owner can use bot
- HTTPS only - All communication encrypted
- No credentials in logs - Sensitive data masked
- Message size: 4MB max (Telegram limit)
- Response time: 30 seconds max (Telegram requirement)
- Rate limiting: Telegram's rate limits apply
- AI model: Limited to available Cloudflare AI models
Edit src/models.ts to add more models:
export function getAllModels(): ModelInfo[] {
return [
{
id: '@cf/meta/llama-2-7b-chat-int8',
name: 'Llama 2 7B',
description: 'Fast and efficient',
},
// Add more models here
];
}Create tables in D1:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
telegram_id INTEGER UNIQUE,
name TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
user_id INTEGER,
role TEXT,
content TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);Create automated tasks:
// Example: Check prices every hour
const automation = {
name: 'price-checker',
description: 'Check prices hourly',
interval: 3600, // seconds
action: 'check_prices',
};- Create a feature branch
- Make your changes
- Test locally:
wrangler dev - Deploy:
wrangler deploy - Create a pull request
See LICENSE file for details.
For issues or questions:
- Check troubleshooting section
- Review Cloudflare Workers documentation
- Check Telegram Bot API documentation
- Open an issue on GitHub
- Cloudflare Workers
- Telegram Bot API
- Hono Documentation
- Wrangler CLI
- Cloudflare D1
- Cloudflare R2
- Cloudflare KV
Last Updated: May 2026 Node Version: 18+ Cloudflare Workers: Latest