• Blog
  • Docs
  • Pricing
  • We’re hiring!
Log inSign up
nmsilva

nmsilva

telegramBot

Public
Like
telegramBot
Home
Code
7
ai-doc.md
C
configureWebhook.ts
home.tsx
login.tsx
H
main.ts
C
messageProcessorWorker.ts
notes.http.ts
Environment variables
4
Branches
1
Pull requests
Remixes
History
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.
Sign up now
Code
/
ai-doc.md
Code
/
ai-doc.md
Search
1/23/2026
ai-doc.md

Telegram AI Notes Bot - Project Summary

πŸ“‹ Project Overview

An intelligent note-taking system that processes Telegram messages using AI to automatically categorize, tag, and organize notes. Users send messages to a Telegram bot, which are processed by OpenAI to extract structured information and stored in a Supabase database.

Key Features

  • βœ… Automatic message processing with AI
  • βœ… Smart categorization (notes, reminders, events, tasks, links, etc.)
  • βœ… Intelligent tagging system
  • βœ… Priority detection
  • βœ… Date/time extraction for reminders and events
  • βœ… URL and location detection
  • βœ… Sentiment analysis
  • βœ… User-specific data isolation

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Telegram  β”‚
β”‚     Bot     β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Webhook (HTTP) β”‚  ← Receives messages
β”‚   Val.town Val  β”‚  ← Validates & stores in SQLite
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SQLite Queue   β”‚  ← Temporary message queue
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Worker (Interval)   β”‚  ← Processes one message at a time
β”‚   Val.town Val      β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       β–Ό             β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  OpenAI  β”‚   β”‚  Supabase   β”‚
β”‚   API    β”‚   β”‚  PostgreSQL β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚             β”‚
       β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
              β–Ό
       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       β”‚  Telegram   β”‚  ← Confirmation message
       β”‚   User      β”‚
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Components

  1. Telegram Webhook (HTTP Val)

    • Receives incoming messages
    • Validates webhook secret
    • Stores messages in SQLite queue
    • Returns 200 OK to Telegram
  2. Message Processor Worker (Interval Val)

    • Runs on scheduled intervals (e.g., every 10-30 seconds)
    • Fetches oldest unprocessed message (one at a time)
    • Processes with OpenAI API
    • Stores results in Supabase
    • Sends confirmation back to user
    • Marks message as processed
  3. SQLite Queue

    • Temporary storage for incoming messages
    • Tracks processing status
    • Ensures messages are processed once
  4. Supabase Database

    • Permanent storage for all notes and metadata
    • User management
    • Tag system
    • AI processing results

πŸ—„οΈ Database Schema

Supabase Tables

1. users

Stores Telegram users mapped to app users.

- id (UUID, PK) - telegram_user_id (BIGINT, UNIQUE) - username (TEXT) - first_name (TEXT) - last_name (TEXT) - created_at (TIMESTAMP) - updated_at (TIMESTAMP)

2. tags

User-specific tags with visual properties.

- id (UUID, PK) - user_id (UUID, FK β†’ users) - name (TEXT) - color (TEXT) - hex color - icon (TEXT) - emoji - created_at (TIMESTAMP) - updated_at (TIMESTAMP) - UNIQUE(user_id, name)

3. notes

Core table storing all processed notes.

- id (UUID, PK) - user_id (UUID, FK β†’ users) - content (TEXT) - original message - title (TEXT) - AI-generated title - note_type (ENUM: note, reminder, event, link, reference, task, idea) - priority (ENUM: low, medium, high, urgent) - status (ENUM: active, completed, archived, deleted) - created_at (TIMESTAMP) - updated_at (TIMESTAMP) - reminder_at (TIMESTAMP) - for reminders - event_date (TIMESTAMP) - for events - completed_at (TIMESTAMP) - for tasks - telegram_message_id (BIGINT) - url (TEXT) - extracted URL - location (TEXT) - for events - search_vector (TSVECTOR) - full-text search

4. note_tags

Many-to-many relationship between notes and tags.

- note_id (UUID, FK β†’ notes) - tag_id (UUID, FK β†’ tags) - created_at (TIMESTAMP) - PRIMARY KEY (note_id, tag_id)

5. ai_results

Stores detailed AI processing results.

- id (UUID, PK) - note_id (UUID, FK β†’ notes) - raw_response (JSONB) - full AI response - extracted_title (TEXT) - extracted_tags (TEXT[]) - extracted_type (note_type) - extracted_priority (note_priority) - extracted_reminder_date (TIMESTAMP) - extracted_event_date (TIMESTAMP) - extracted_url (TEXT) - extracted_location (TEXT) - sentiment (TEXT: positive, negative, neutral) - confidence_score (DECIMAL) - model_used (TEXT) - processing_time_ms (INTEGER) - created_at (TIMESTAMP) - error (TEXT) - success (BOOLEAN)

6. telegram_messages (Optional - for migration)

Processing queue in Supabase (alternative to SQLite).

- id (UUID, PK) - user_id (UUID, FK β†’ users) - telegram_message_id (BIGINT) - chat_id (BIGINT) - text (TEXT) - processed_at (TIMESTAMP) - created_at (TIMESTAMP) - note_id (UUID, FK β†’ notes) - processing_error (TEXT) - retry_count (INTEGER)

SQLite Tables (Val.town Local)

messages

Temporary queue for incoming Telegram messages.

- id (INTEGER, PK, AUTOINCREMENT) - chat_id (INTEGER) - username (TEXT) - text (TEXT) - timestamp (INTEGER) - created_at (DATETIME) - processed_at (DATETIME) - NULL when unprocessed

πŸ€– AI Processing Logic

Input

Raw Telegram message text from user.

AI Prompt

The AI analyzes messages to extract:

  • Title: Short descriptive title (max 60 chars)
  • Type: note, reminder, event, link, reference, task, idea
  • Priority: low, medium, high, urgent
  • Tags: Array of relevant tags (max 5)
  • Dates: Reminder and event dates in ISO format
  • URL: Extracted links
  • Location: Event locations
  • Sentiment: positive, negative, neutral
  • Confidence: 0.0 to 1.0

Examples

Input MessageAI Output
"Buy milk tomorrow"type: task, reminder_date: [tomorrow], tags: ["shopping"], priority: medium
"Meeting with John at 3pm Friday"type: event, event_date: [Friday 3pm], tags: ["meeting"], priority: medium
"https://example.com interesting article"type: link, url: "https://example.com", tags: ["article"], priority: low
"URGENT: Fix production bug"type: task, priority: urgent, tags: ["work", "bug"], sentiment: negative

Output Format (JSON)

{ "title": "Buy milk", "type": "task", "priority": "medium", "tags": ["shopping", "groceries"], "reminder_date": "2026-01-22T00:00:00Z", "event_date": null, "url": null, "location": null, "sentiment": "neutral", "confidence": 0.92 }

πŸ”§ Current Implementation

Webhook (webhook.ts)

// Key features: - POST-only endpoint - Validates X-Telegram-Bot-Api-Secret-Token - Stores messages in SQLite with processed_at = NULL - Returns 200 OK immediately - Logs all activity

Worker (worker.ts)

// Key features: - Interval-based execution - Processes one message at a time (LIMIT 1) - FIFO processing (ORDER BY created_at ASC) - OpenAI integration for analysis - Supabase CRUD operations - User creation/lookup - Tag management - Confirmation messages to users - Error handling - Processing time tracking

Key Functions

analyzeMessageWithAI(text)

  • Calls OpenAI GPT-4o-mini
  • Returns structured JSON with extracted data
  • Uses response_format: { type: "json_object" }

getOrCreateUser(message)

  • Checks if user exists by telegram_user_id
  • Creates new user if not found
  • Returns user object

insertNote(noteData)

  • Inserts note into Supabase
  • Returns created note with ID

linkTags(noteId, userId, tagNames)

  • Gets or creates tags
  • Links tags to note via note_tags table

formatConfirmationMessage(aiResult)

  • Creates formatted Telegram message
  • Includes emojis for types and priorities
  • Shows all extracted information

πŸ” Environment Variables

Required Variables

VariableDescriptionWhere to Get
TELEGRAM_BOT_TOKENBot authentication token@BotFather on Telegram
TELEGRAM_WEBHOOK_SECRETCustom secret for webhook validationGenerate random string
SUPABASE_URLSupabase project URLSupabase dashboard
SUPABASE_SERVICE_KEYService role key (bypasses RLS)Supabase Settings β†’ API
OPENAI_API_KEYOpenAI API keyOpenAI platform

πŸš€ Setup Instructions

1. Create Telegram Bot

# Message @BotFather on Telegram /newbot # Follow prompts, save token

2. Create Supabase Project

1. Go to https://supabase.com 2. Create new project 3. Run the database schema SQL 4. Get URL and service key from Settings β†’ API

3. Deploy Webhook Val

1. Create new HTTP Val on Val.town 2. Paste webhook code 3. Add environment variables 4. Get Val URL (https://username-valname.web.val.run)

4. Set Telegram Webhook

curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-val.web.val.run", "secret_token": "your-webhook-secret" }'

5. Deploy Worker Val

1. Create new Interval Val on Val.town 2. Paste worker code 3. Add environment variables 4. Set interval (recommended: 10-30 seconds)

6. Test

Send a message to your bot on Telegram
Check Val.town logs
Verify data in Supabase

🎯 Future Development Ideas

Phase 1: Core Enhancements

  • Retry Logic: Handle failed AI processing with exponential backoff
  • Batch Processing: Process multiple messages per worker run
  • Message Editing: Update notes when user edits Telegram message
  • Message Deletion: Delete notes when user deletes Telegram message
  • Error Notifications: Notify users when processing fails
  • Voice Messages: Transcribe and process voice notes
  • Images: OCR and image analysis
  • Documents: Extract text from PDFs, Word docs

Phase 2: User Interactions

  • Bot Commands:
    • /list - Show recent notes
    • /search <query> - Search notes
    • /tags - Manage tags
    • /reminders - View upcoming reminders
    • /stats - Usage statistics
    • /settings - User preferences
  • Inline Keyboards: Interactive buttons for actions
  • Quick Actions: Mark as done, snooze, edit priority
  • Bulk Operations: Archive old notes, delete by tag

Phase 3: Smart Features

  • Natural Language Dates: "next Tuesday", "in 2 weeks"
  • Recurring Reminders: Daily, weekly, monthly
  • Smart Suggestions: Tag suggestions based on history
  • Context Awareness: Learn from user patterns
  • Related Notes: Link similar notes automatically
  • Summary Digests: Daily/weekly summaries
  • Calendar Integration: Sync events with Google Calendar

Phase 4: Advanced AI

  • Multi-language Support: Detect and process any language
  • Action Items Extraction: Pull out todos from long messages
  • Meeting Notes: Extract attendees, decisions, action items
  • Smart Replies: AI suggests responses to messages
  • Note Relationships: Automatically link related notes
  • Knowledge Graph: Build connections between notes

Phase 5: Web/Mobile App

  • Web Dashboard:
    • View all notes in rich interface
    • Advanced search and filtering
    • Calendar view for events
    • Kanban board for tasks
    • Analytics and insights
  • Mobile App: Native iOS/Android apps
  • Browser Extension: Save web content as notes
  • API: Public API for integrations

Phase 6: Integrations

  • Calendar Sync: Google Calendar, Apple Calendar
  • Task Managers: Todoist, Asana, Trello
  • Note Apps: Notion, Evernote, Obsidian
  • Email: Send notes via email
  • Slack/Discord: Team collaboration
  • Zapier/Make: Connect to 1000+ apps

Phase 7: Collaboration

  • Shared Notes: Collaborate with other users
  • Teams/Workspaces: Organize by team
  • Permissions: View/edit access control
  • Comments: Discuss notes with team
  • Activity Feed: See team activity

Phase 8: Premium Features

  • Unlimited Storage: Remove message limits
  • Advanced AI Models: GPT-4, Claude
  • Priority Support: Faster response times
  • Custom Integrations: Build custom connections
  • White-label: Custom branding
  • Export: Bulk export in various formats

πŸ” Technical Considerations

Performance

  • Current: Sequential processing (1 message per interval)
  • Improvement: Implement concurrent processing with rate limiting
  • Consideration: OpenAI rate limits (3,500 RPM for gpt-4o-mini)

Scalability

  • SQLite Limitations: Val.town SQLite is ephemeral
  • Solution: Migrate queue to Supabase for persistence
  • Alternative: Use Redis for message queue

Reliability

  • Single Point of Failure: If worker stops, messages pile up
  • Solution: Implement health checks and alerts
  • Monitoring: Track processing times, error rates

Security

  • RLS (Row Level Security): Enabled but bypassed by service key
  • Improvement: Implement proper auth for future web app
  • Consideration: Secure API keys, rotate regularly

Cost Optimization

  • OpenAI Costs: ~$0.0001 per message (gpt-4o-mini)
  • Supabase: Free tier: 500MB, 2GB bandwidth
  • Val.town: Free tier: 10 vals, limited compute
  • Monitoring: Track usage, set budgets

πŸ“Š Data Flow Diagram

User sends message β†’ Telegram Bot
                          ↓
                    Webhook receives
                          ↓
                  Validates secret
                          ↓
               Stores in SQLite queue
                          ↓
                    Returns 200 OK
                          ↓
            [Message in queue: processed_at = NULL]
                          ↓
              Worker runs (interval trigger)
                          ↓
         Fetches oldest unprocessed message
                          ↓
              Sends to OpenAI for analysis
                          ↓
            OpenAI returns structured JSON
                          ↓
           Get/Create user in Supabase
                          ↓
            Insert note into Supabase
                          ↓
         Insert AI results into Supabase
                          ↓
        Get/Create tags and link to note
                          ↓
      Format confirmation message with emojis
                          ↓
       Send confirmation back to Telegram
                          ↓
         Mark message as processed (SQLite)
                          ↓
                    Worker completes
                          ↓
            [Next interval: process next message]

πŸ“ Code Structure

Val.town Vals

vals/
β”œβ”€β”€ telegram-webhook.ts      # HTTP endpoint for receiving messages
└── telegram-worker.ts        # Interval worker for processing

Key Files in This Project

project/
β”œβ”€β”€ telegram-notes-bot-summary.md  # This document
β”œβ”€β”€ database-schema.sql            # Supabase schema
β”œβ”€β”€ webhook.ts                     # Webhook implementation
└── worker.ts                      # Worker implementation

πŸ› Common Issues & Solutions

Issue: Messages not processing

Solution: Check worker logs, verify OpenAI API key, check Supabase connection

Issue: Duplicate messages

Solution: Ensure processed_at is set correctly, check for worker conflicts

Issue: AI returns invalid JSON

Solution: Verify "json" is in system prompt, handle parsing errors

Issue: Tags not linking

Solution: Check user_id matching, verify tag creation logic

Issue: Telegram not receiving confirmations

Solution: Verify BOT_TOKEN, check sendMessage error handling


πŸ“ˆ Metrics to Track

Performance Metrics

  • Average processing time per message
  • OpenAI API response time
  • Supabase query performance
  • Worker execution time

Business Metrics

  • Total messages processed
  • Active users
  • Notes created per day
  • Tag usage statistics
  • Note type distribution

Quality Metrics

  • AI confidence scores
  • User corrections/edits
  • Error rate
  • Retry rate

🎨 UI/UX Considerations (Future Web App)

Dashboard Views

  • Inbox: All recent notes
  • Today: Today's tasks and reminders
  • Calendar: Month/week view of events
  • Search: Full-text search with filters
  • Tags: Browse by tag
  • Archive: Completed/archived notes

Key Features

  • Dark mode support
  • Mobile-responsive design
  • Drag-and-drop organization
  • Keyboard shortcuts
  • Quick capture
  • Markdown support

πŸ”„ Workflow Examples

Example 1: Quick Task

User: "Buy milk tomorrow"
  ↓
AI Analysis:
  - Type: task
  - Priority: medium
  - Tags: ["shopping"]
  - Reminder: tomorrow 9am
  ↓
Stored in database
  ↓
User receives: "βœ… Task: Buy milk
                Priority: 🟑 medium
                Tags: #shopping
                Reminder: Jan 22, 2026 9:00 AM"

Example 2: Meeting Event

User: "Team meeting Friday 2pm with John and Sarah"
  ↓
AI Analysis:
  - Type: event
  - Priority: medium
  - Tags: ["meeting", "work"]
  - Event date: Friday 2pm
  ↓
Stored in database
  ↓
User receives: "πŸ“… Event: Team meeting Friday 2pm with John and Sarah
                Event: Jan 24, 2026 2:00 PM
                Tags: #meeting #work"

Example 3: Link Save

User: "https://blog.example.com/ai-trends great article about AI"
  ↓
AI Analysis:
  - Type: link
  - Priority: low
  - Tags: ["article", "ai"]
  - URL: https://blog.example.com/ai-trends
  ↓
Stored in database
  ↓
User receives: "πŸ”— Link: great article about AI
                URL: https://blog.example.com/ai-trends
                Tags: #article #ai"

πŸ† Success Criteria

MVP (Current)

  • βœ… Receive and store messages
  • βœ… Process with AI
  • βœ… Extract structured data
  • βœ… Store in database
  • βœ… Send confirmations

V1.0

  • All note types working
  • Accurate date parsing
  • Reliable processing
  • Error handling
  • Basic commands

V2.0

  • Web dashboard
  • Advanced search
  • Reminders triggering
  • Mobile app
  • 100+ active users

πŸ“š Resources

Documentation

  • Telegram Bot API
  • OpenAI API
  • Supabase Docs
  • Val.town Docs

Libraries Used

  • Val.town stdlib: OpenAI, SQLite, Fetch
  • Supabase REST API
  • Telegram Bot API

🀝 Contributing

Areas for Contribution

  1. AI Prompts: Improve extraction accuracy
  2. Features: Add new note types, commands
  3. UI/UX: Design web dashboard
  4. Testing: Write tests, find bugs
  5. Documentation: Improve guides, add examples

Development Workflow

  1. Fork repository
  2. Create feature branch
  3. Test thoroughly
  4. Submit pull request
  5. Code review
  6. Deploy to staging
  7. Test in production
  8. Merge to main

πŸ“ž Support & Contact

Getting Help

  • Check logs in Val.town dashboard
  • Review Supabase database
  • Test with simple messages first
  • Check environment variables

Future Support Channels

  • Discord community
  • GitHub issues
  • Email support
  • Documentation site

πŸ“… Version History

Current Version: 0.1.0 (MVP)

  • βœ… Basic message reception
  • βœ… AI processing
  • βœ… Database storage
  • βœ… Confirmation messages

Planned Versions

  • 0.2.0: Error handling, retry logic
  • 0.3.0: Bot commands
  • 0.4.0: Voice messages, images
  • 1.0.0: Web dashboard
  • 2.0.0: Mobile apps
  • 3.0.0: Team collaboration

πŸ’‘ Lessons Learned

What Works Well

  • Sequential processing prevents race conditions
  • JSON mode in OpenAI ensures structured output
  • Supabase RLS provides security
  • Val.town simplifies deployment

Challenges

  • Natural language date parsing is complex
  • Rate limiting requires careful handling
  • User timezone detection needed
  • SQLite persistence in Val.town

Best Practices

  • Always validate webhook secrets
  • Use environment variables for keys
  • Log everything for debugging
  • Return 200 OK quickly to Telegram
  • Process asynchronously

🎯 Next Steps

Immediate (This Week)

  1. Test with real users
  2. Monitor error rates
  3. Improve AI prompts
  4. Add basic error handling

Short-term (This Month)

  1. Implement retry logic
  2. Add basic commands
  3. Improve date parsing
  4. Set up monitoring

Medium-term (3 Months)

  1. Build web dashboard
  2. Add voice message support
  3. Implement reminders
  4. Beta testing

Long-term (6+ Months)

  1. Mobile apps
  2. Team features
  3. Advanced AI
  4. Public launch

Last Updated: January 2026 Version: 0.1.0 Status: MVP - Active Development

FeaturesVersion controlCode intelligenceCLIMCP
Use cases
TeamsAI agentsSlackGTM
DocsShowcaseTemplatesNewestTrendingAPI examplesNPM packages
PricingNewsletterBlogAboutCareers
We’re hiring!
Brandhi@val.townStatus
X (Twitter)
Discord community
GitHub discussions
YouTube channel
Bluesky
Open Source Pledge
Terms of usePrivacy policyAbuse contact
Β© 2026 Val Town, Inc.