Skip to content

🤖 Automated Telegram notification service for Yandex Delivery orders. Cloudflare Worker with D1 database integration, Russian localization, and smart priority system for Kazakhstan flower delivery business.

Notifications You must be signed in to change notification settings

alekenov/telegram-notifications-worker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Telegram Notifications Worker

🤖 Automated Telegram notification service for Yandex Delivery orders. Reads orders from D1 database and sends formatted notifications to Telegram channel.

Features

  • 📨 Automated Notifications - Sends order updates to Telegram channel every 3 minutes
  • 🔄 Smart Processing - Handles new orders, status updates, and delivery completions
  • 🚨 Priority System - Urgent orders (delays, cancellations) get immediate attention
  • 🇷🇺 Russian Localization - All messages in Russian with proper formatting for Kazakhstan market
  • Almaty Timezone - Times displayed in local Kazakhstan timezone
  • 📊 Rich Formatting - Emojis, inline buttons, and structured messages
  • 🔍 Tracking Integration - Direct links to Yandex delivery tracking

Architecture

yandex-delivery-core (scans orders) 
        ↓ saves with telegram_notified = false
D1 Database (yandex-delivery-history)
        ↓ reads pending notifications  
telegram-notifications (this worker)
        ↓ sends formatted messages
Telegram API → @cvety_delivery_monitor

Installation

1. Install dependencies

npm install

2. Configure secrets

# Telegram Bot API token (from @BotFather)
wrangler secret put TELEGRAM_BOT_TOKEN

# Target channel ID (e.g., @cvety_delivery_monitor)  
wrangler secret put TELEGRAM_CHANNEL_ID

# Admin chat ID for error notifications
wrangler secret put TELEGRAM_ADMIN_CHAT_ID

3. Development

npm run dev

4. Deploy

npm run deploy

API Endpoints

GET / or /health

Health check endpoint

{
  "service": "telegram-notifications",
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00.000Z"
}

POST /send-notifications?limit=20

Manually trigger notification sending

{
  "success": true,
  "result": {
    "sent": 15,
    "failed": 0,
    "errors": []
  }
}

GET /stats

Get comprehensive statistics

{
  "success": true,
  "stats": {
    "database": {
      "totalOrders": 150,
      "pendingNotifications": 8,
      "notifiedToday": 42,
      "byStatus": {
        "new": 3,
        "delivered": 5
      }
    },
    "telegram": {
      "healthy": true,
      "lastCheck": "2024-01-01T12:00:00.000Z"
    }
  }
}

GET /test

Send test message to verify connectivity

{
  "success": true,
  "message": "Test message sent successfully"
}

GET /check-health

Comprehensive health check

{
  "success": true,
  "checks": {
    "overall": true,
    "database": true,
    "telegram": true,
    "lastCheck": "2024-01-01T12:00:00.000Z"
  }
}

Message Templates

New Order Notification

📝 Заказ #ABCD1234 | Новый заказ

📍 Маршрут:
   🔸 Откуда: ул. Абая 150, офис Cvety.kz
   🔸 Куда: мкр. Самал-2, д. 111, кв. 45

👤 Клиент:
   📝 Анна Петрова
   📱 +7 777 123 45 67

💰 Стоимость доставки: 1500 KZT

⏰ Создан: 12.01.2024, 14:30
🆔 ID заказа: 12345678-abcd-1234-abcd-123456789012

[🗺 Отследить на карте] [📋 Подробности]

Status Update Notification

🚚 Заказ #ABCD1234 | Товар забран

👨‍🚚 Курьер:
   📝 Сергей Иванов
   📱 +7 701 234 56 78
   🚗 Toyota Camry А123БВ02

📍 Адрес доставки:
мкр. Самал-2, д. 111, кв. 45

⏰ Обновлено: 12.01.2024, 15:15
🆔 ID заказа: 12345678-abcd-1234-abcd-123456789012

Automatic Processing

Cron Schedule

  • Every 3 minutes - Process up to 20 pending notifications
  • Priority system - Urgent orders processed first
  • Rate limiting - 200ms delay between messages to avoid Telegram limits

Notification Priority

  1. Urgent (100+ points) - Cancelled, failed, stuck orders
  2. Completed (+50 points) - Delivered orders
  3. With Courier (+30 points) - Orders with assigned courier
  4. Recent Updates (+20 points) - Recently updated orders

Smart Filtering

  • Include: New orders, status changes, deliveries, problems
  • Exclude: Intermediate statuses, orders older than 24 hours
  • 🚨 Urgent: Delays, cancellations, stuck orders

Database Integration

Uses existing D1 database yandex-delivery-history:

-- Orders are marked for notification by yandex-delivery-core
SELECT * FROM delivery_orders 
WHERE telegram_notified = false 
ORDER BY updated_at DESC;

-- After successful notification
UPDATE delivery_orders 
SET telegram_notified = true, 
    last_telegram_update = CURRENT_TIMESTAMP
WHERE claim_id IN (sent_orders);

Error Handling

  • Telegram API Errors - Logged and retried on next cron run
  • Database Issues - Health checks prevent processing when DB unavailable
  • Admin Notifications - Critical errors sent to admin chat
  • Graceful Degradation - Individual order failures don't stop batch processing

Monitoring

  • Health Checks - Both API and scheduled health monitoring
  • Comprehensive Logging - All operations logged with timestamps
  • Statistics API - Real-time stats on notifications sent/failed
  • Error Tracking - Failed notifications logged for debugging

Telegram Bot Setup

  1. Create bot with @BotFather
  2. Get bot token
  3. Add bot to channel as administrator
  4. Get channel ID (e.g., @cvety_delivery_monitor)
  5. Configure secrets in Cloudflare Workers

Integration with Core Services

  • yandex-delivery-core - Creates/updates orders with telegram_notified = false
  • cvety-admin-react - Can view notification statistics via API
  • Telegram Channel - Receives formatted notifications for monitoring team

About

🤖 Automated Telegram notification service for Yandex Delivery orders. Cloudflare Worker with D1 database integration, Russian localization, and smart priority system for Kazakhstan flower delivery business.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •