Feature

Telegram Bot Integration

Telegram Bot Integration

Overview

The Klinik Gunung Semeru system is integrated with a Telegram Bot to provide quick access to patient screening reports and health examination data. This bot allows medical staff to obtain real-time information without needing to access the web system.

Main Features

  • Screening Reports: Get patient screening data based on date, date range, or monthly period
  • Health Examination Reports: Detailed physical examination reports with AI analysis from Gemini
  • Interactive Buttons: User-friendly interface with inline buttons for quick navigation
  • Real-time Data: Data retrieved directly from the clinic system database

Bot Configuration

Environment Variables

Add the following configuration to the .env file:

TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here
TELEGRAM_WEBHOOK_URL=https://your-domain.com/api/telegram/webhook

Getting Bot Token

  1. Open Telegram and search for @BotFather
  2. Send the command /newbot
  3. Follow the instructions to create a new bot
  4. Copy the token provided by BotFather
  5. Set the token to TELEGRAM_BOT_TOKEN

Getting Chat ID

  1. Open the created bot
  2. Send any message to the bot
  3. Access URL: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  4. Find the "chat":{"id":...} field from the JSON response
  5. Set that ID to TELEGRAM_CHAT_ID

Webhook Setup

The bot uses webhook to receive messages. Ensure the endpoint is publicly available:

# Using ngrok for development
ngrok http 8000
# Set webhook URL to https://your-ngrok-url.ngrok.io/api/telegram/webhook

# Production webhook
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
     -d "url=https://your-domain.com/api/telegram/webhook"

Bot Commands

/start

Displays the main menu with inline buttons for quick access.

Response:

Available commands. Click the buttons below to execute directly:
[Today's Screening] [Examinations]

/screening

Displays screening reports with various filter options.

Format:

/screening                           # Today
/screening 23-05-2025               # Specific date
/screening 20-05-2025 25-05-2025    # Date range
/screening bulan 05-2025           # Monthly period

Example Output:

Klinik Gunung Screening Report

Date: 23 May 2025

Screening Data
• Total Screening: 45
• Total Physical Examinations: 42
• Not Yet Physical Examination: 3
• Total Patients in System: 128

Health Status
• Healthy: 38
• Unhealthy with Companion: 3
• Unhealthy: 1

Gender
• Male: 22
• Female: 20

This data is automatically retrieved from the Klinik Gunung system.

/pemeriksaan

Displays health examination reports with AI analysis.

Format: (same as /screening)

/pemeriksaan                          # Today
/pemeriksaan 23-05-2025              # Specific date
/pemeriksaan 20-05-2025 25-05-2025   # Date range
/pemeriksaan bulan 05-2025          # Monthly period

Example Output:

Screening Report

Date: 23 May 2025

Examination Data
• Healthy: 38
• Unhealthy: 4
• Male: 22
• Female: 20

Average Vital Signs
• Heart Rate: 78
• O₂: 97.5%
• Respiratory Rate: 18
• Temperature: 36.8°C

AI Analysis (Gemini)
The average vital signs indicate good health condition with normal oxygen saturation and stable body temperature. Further monitoring is needed for patients with unhealthy status.

Data automatically retrieved from the Klinik Gunung system.

System Architecture

TelegramService

Main class for communication with Telegram API.

Methods:

  • sendMessage(): Send message with HTML support and inline keyboard
  • answerCallbackQuery(): Answer callback from inline buttons

CommandRouter

Router that handles routing commands to appropriate handlers.

Command Mapping:

$map = [
    '/start' => StartCommand::class,
    '/screening' => ScreeningCommand::class,
    '/pemeriksaan' => HealthCommand::class,
    'screening' => ScreeningCommand::class,
    'pemeriksaan' => HealthCommand::class,
];

Available Commands

StartCommand

  • Displays main menu with inline keyboard
  • Directs user to desired features

ScreeningCommand

  • Retrieves data from screenings and physical_examinations tables
  • Calculates screening vs physical examination statistics
  • Displays breakdown by health status and gender

HealthCommand

  • Focuses on physical examination data
  • Calculates average vital signs (heart rate, saturation, respiratory rate, temperature)
  • Integrates Gemini AI for health condition analysis

TelegramBotController

Webhook controller that receives updates from Telegram.

Flow:

  1. Receives request from Telegram
  2. Parse message or callback query
  3. Route to CommandRouter
  4. Execute command handler
  5. Return 'ok' response

Webhook Endpoint

POST /api/telegram/webhook

Headers:

Content-Type: application/json

Body Example:

{
  "message": {
    "text": "/screening",
    "chat": {
      "id": "-1002911218423"
    },
    "message_thread_id": 16
  }
}

Database Integration

The bot retrieves data from several tables:

  • screenings: Initial patient screening data
  • physical_examinations: Complete physical examination data
  • patients: Patient data for gender analysis

Relationships:

  • Screening → Physical Examination (one-to-one/many)
  • Physical Examination → Patient (many-to-one)

AI Integration

HealthCommand uses Google Gemini for health data analysis:

$aiInsight = Gemini::generativeModel(model: 'gemini-2.0-flash-lite')
    ->generateContent($prompt)
    ->text();

Prompt Template:

Analyze the health condition of clinic patients based on the following data:
Period: {label}
Average heart rate: {nadi}, saturation: {saturasi}, breathing: {napas}, temperature: {suhu}
Provide the shortest possible analysis.

Error Handling

  • Wrong date format: Bot provides error message with correct format examples
  • Telegram API failure: Exception thrown with response details
  • Data not found: Displays 0 for all statistics

Security

  • Bot token stored in environment variables
  • Chat ID limited to specific group/channel
  • Webhook uses HTTPS
  • Input validation on all parameters

Monitoring

  • All requests to Telegram API are logged
  • Response body saved for debugging
  • Errors logged with complete details

Development

Testing Bot

# Test local webhook with curl
curl -X POST http://localhost:8000/api/telegram/webhook \
  -H "Content-Type: application/json" \
  -d '{"message":{"text":"/start","chat":{"id":"123456789"}}}'

Debug Commands

# Check webhook info
curl https://api.telegram.org/bot<TOKEN>/getWebhookInfo

# Remove webhook (for development)
curl -X POST "https://api.telegram.org/bot<TOKEN>/deleteWebhook"

Troubleshooting

Bot Not Responding

  1. Check active webhook URL
  2. Verify bot token is valid
  3. Check Laravel logs for errors

Data Not Updating

  1. Ensure database connection is normal
  2. Check timezone settings (Asia/Jakarta)
  3. Verify table structure and relationships

Callback Button Not Working

  1. Ensure callback_query is handled correctly
  2. Check answerCallbackQuery response
  3. Verify inline keyboard format

Future Enhancements

  • Multi-language support
  • Custom report templates
  • Scheduled automated reports
  • Push notification integration
  • Advanced AI insights with historical data