jarvis
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
Viewing readonly version of main branch: v52View latest version
This Telegram bot uses an in-memory queue system to handle chat messages efficiently, ensuring fast webhook responses while processing AI-generated replies asynchronously.
- Webhook handler receives messages and immediately adds them to an in-memory queue
- Returns quickly to avoid Telegram webhook timeouts
- Shows "typing" indicator to acknowledge receipt
- Background queue processor runs every 500ms
- Processes messages one by one with AI text generation
- Sends responses back to Telegram using the Bot API
- Includes error handling and rate limiting
interface ChatTask {
chatId: number; // Telegram chat ID
messageId: number; // Original message ID for replies
userMessage: string; // User's message text
timestamp: number; // When message was queued
}
- Fast Response: Webhook completes in milliseconds
- Reliable Processing: Messages are queued and processed reliably
- Error Handling: Failed messages get error responses
- Rate Limiting: Small delays between processing to avoid API limits
- Logging: Console logs for monitoring queue activity
TELEGRAM_TOKEN: Your Telegram bot tokenOPENAI_API_KEY: OpenAI API key for text generation
- User sends message to Telegram bot
- Telegram webhook calls our endpoint
- Message is added to queue, webhook responds immediately
- Background processor picks up message from queue
- AI generates response using OpenAI
- Response is sent back to user via Telegram API
This pattern ensures your middleware stays fast while allowing complex processing to happen asynchronously.
