matrix-chatgpt-bot/
├── src/
│ ├── index.ts # Worker entry point
│ ├── types.ts # TypeScript type definitions
│ ├── matrix/
│ │ └── client.ts # Matrix Client-Server API client
│ ├── ai/
│ │ └── client.ts # AI API client (OpenAI-compatible)
│ ├── storage/
│ │ ├── kv.ts # KV storage abstraction
│ │ └── r2.ts # R2 storage abstraction
│ ├── durable-objects/
│ │ └── MatrixSync.ts # Durable Object for Matrix sync
│ └── bot/
│ ├── commands.ts # Command handler
│ └── handler.ts # Message handler
├── wrangler.toml # Cloudflare Workers configuration
├── tsconfig.json # TypeScript configuration
├── package.json # Node.js dependencies
├── README.md # Main documentation
├── DEPLOYMENT.md # Deployment guide
├── QUICKSTART.md # Quick start guide
└── .env.example # Environment variables template
Main entry point for Cloudflare Workers. Handles:
- HTTP routes (
/login,/start,/stop,/status) - Scheduled triggers (cron)
- Request routing to Durable Objects
Implements Matrix Client-Server API:
- Authentication (
login) - Sync loop (
sync) - Send messages (
sendMessage) - Room management (
joinRoom,leaveRoom) - Typing indicators and read receipts
OpenAI-compatible API client:
- Chat completions
- Streaming support
- Custom base URL support
- Multiple provider support
Manages configuration and session data:
- Auth tokens
- Sync tokens
- Room configurations
- User settings
- Provider configurations
- Admin lists
Manages large data:
- Conversation history
- Message logs
- Images
- File uploads
- Configuration backups
Maintains Matrix sync state:
- Persistent sync loop
- Alarm-based scheduling
- Event processing
- Message routing
Processes bot commands:
!help- Show help!reset- Clear history!provider- Manage providers!model- Set model- Admin commands
Core bot logic:
- Message processing
- Context management
- AI response generation
- Error handling
Matrix Server
↓
Matrix Sync (Durable Object)
↓
Message Handler
↓
[Command?] → Command Handler → Response
↓
[Chat?] → Load Context (R2) → AI Client → Response
↓
Matrix Server
Environment Variables → KV Storage
↓
Provider Config (KV)
↓
Room Config (KV)
↓
AI Client
KV: Fast, globally distributed
- Configurations
- Tokens
- Session data
- Metadata
R2: Large objects
- Conversation history
- Logs
- Files
- Backups
Durable Objects: Stateful coordination
- Sync state
- Connection management
- Event sequencing
GET /- Health checkGET /health- StatusPOST /login- Matrix loginGET /start- Start syncGET /stop- Stop syncGET /status- Sync status
POST /internal/handle-message- Message processing (used by Durable Object)
Defines:
- Worker name and entry point
- KV namespace bindings
- R2 bucket bindings
- Durable Object bindings
- Cron triggers
- Environment variables
TypeScript compiler options:
- Target: ES2021
- Module: ES2022
- Strict mode enabled
- Workers types
Dependencies:
@cloudflare/workers-types- TypeScript typestypescript- TypeScript compilerwrangler- Cloudflare Workers CLI
Bot can use any OpenAI-compatible API:
- Official OpenAI
- Azure OpenAI
- OpenRouter
- Local models (vLLM, Ollama, LocalAI)
- Custom endpoints
Each room has independent:
- Conversation history
- Provider/model settings
- System prompts
- Configuration
Admin-only commands:
- Add/remove providers
- Set global configuration
- View statistics
- Manage users
Cloudflare's global network:
- Edge compute in 200+ cities
- Low latency worldwide
- Auto-scaling
- DDoS protection
npm run dev # Start local dev server
wrangler tail # Stream logsnpm run build # TypeScript compilationwrangler deploy # Deploy to production- Deploy to preview environment
- Test commands in Matrix room
- Verify logs in Cloudflare dashboard
- Check KV/R2 data
- Test Matrix sync
- Test AI responses
- Test provider switching
- Test error handling
All sensitive data stored as Cloudflare secrets:
- Matrix credentials
- API keys
- Never in code or version control
Multiple layers:
- Admin whitelist
- User whitelist
- Room-level permissions
- No logging of message content
- Conversation history encrypted in R2
- Credentials never exposed in logs
Hot data cached globally:
- Provider configs
- Room settings
- Recent conversations
Batch operations to reduce:
- Request count
- Latency
- Costs
Efficient sync scheduling:
- No polling when idle
- Automatic wake-up
- Resource conservation
wrangler tail # Real-time logsCloudflare dashboard:
- Request count
- Error rate
- Duration
- KV/R2 operations
Check:
- Worker logs
- Durable Object state
- KV data
- R2 objects
Potential additions:
- E2E encryption support
- Image generation
- Voice messages
- Multi-bot support
- Enhanced analytics
- Web UI dashboard