# 🤖 การตั้งค่า Telegram Bot - บอทน้องลา





### 🚀 **คู่มือการตั้งค่า Telegram Bot และ Webhook**
#### *สำหรับระบบจัดการการลาและ Work From Home แบบ Modern & Secure*
[]()
[]()
[]()
> 🎯 **ระบบที่ออกแบบมาเพื่อความง่าย ความปลอดภัย และการใช้งานจริงในองค์กร**
---
## ✨ **จุดเด่นของระบบ**
<table>
<tr>
<td align="center">🔒</td>
<td><strong>ความปลอดภัยสูง</strong><br/>Rate Limiting, Input Validation, File Encryption</td>
<td align="center">⚡</td>
<td><strong>รวดเร็ว</strong><br/>Real-time Updates ผ่าน Webhook</td>
</tr>
<tr>
<td align="center">🎯</td>
<td><strong>ใช้งานง่าย</strong><br/>UI/UX ออกแบบมาเพื่อผู้ใช้ทั่วไป</td>
<td align="center">🔧</td>
<td><strong>Config-driven</strong><br/>ตั้งค่าผ่าน Config Files</td>
</tr>
</table>
---
## 📋 **สารบัญ**
| Section | Description | Time Required |
|---------|-------------|---------------|
| [🚀 สร้าง Telegram Bot](#-สร้าง-telegram-bot) | การสร้างบอทใหม่กับ BotFather | 5 นาที |
| [⚙️ ตั้งค่า Webhook](#️-ตั้งค่า-webhook) | เชื่อมต่อบอทกับเซิร์ฟเวอร์ | 3 นาที |
| [🔧 การกำหนดค่า](#-การกำหนดค่า) | Config files และการตั้งค่า | 5 นาที |
| [🧪 การทดสอบ](#-การทดสอบ) | ทดสอบการทำงานของระบบ | 2 นาที |
| [🛠️ การแก้ไขปัญหา](#️-การแก้ไขปัญหา) | Solutions สำหรับปัญหาที่พบบ่อย | - |
| [📊 การจัดการ](#-การจัดการ) | Monitoring และ Maintenance | - |
---
## 🚀 **สร้าง Telegram Bot**
<summary><b>📱 ขั้นตอนการสร้างบอทใหม่ (คลิกเพื่อดู)</b></summary>
### 🔍 **ขั้นตอนที่ 1: เข้าหา BotFather**
**1. เปิด Telegram App** 📱
- Desktop หรือ Mobile ก็ได้
- ต้องมีบัญชี Telegram แล้ว
**2. ค้นหา BotFather** 🔍
```
ค้นหา: @BotFather
```
> ⚠️ **สำคัญ**
> เลือก **BotFather** ที่มีเครื่องหมายถูกสีฟ้า ✅
> กดปุ่ม **"Start"** หรือพิมพ์ `/start`
### 🛠️ **ขั้นตอนที่ 2: สร้างบอทใหม่**
```bash
# คำสั่งเริ่มสร้างบอท
/newbot
```
**3. ตั้งชื่อบอท** 🏷️
```
✅ ตัวอย่างชื่อที่ดี:
- บอทน้องลา
- Leave Bot
- Company Leave System
- HR Assistant Bot
```
**4. ตั้ง Username** 👤
```
✅ ตัวอย่าง Username ที่ดี:
- NongLaLeaveBot
- MyCompanyLeaveBot
- YourCompanyHRBot
- LeaveManagementBot
```
> ⚠️ **ข้อกำหนด Username**
> - ต้องลงท้ายด้วย "bot" หรือ "Bot"
> - ต้องไม่ซ้ำกับบอทอื่น
> - ใช้เฉพาะ a-z, A-Z, 0-9, และ underscore
### 🔑 **ขั้นตอนที่ 3: รับ Bot Token**
**5. คัดลอก Bot Token** �
```
📋 ตัวอย่าง Token:
123456789:ABCdefGHIjklMNOpqrsTUVwxyz1234567890
```
⚠️ **เก็บ Token เป็นความลับ!**
🚫 อย่าแชร์ Token ใน GitHub, Discord, หรือที่ไหนที่เป็นสาธารณะ
---
## ⚙️ **ตั้งค่า Webhook**
🌐 การเชื่อมต่อ Webhook (คลิกเพื่อดู)
### 🎯 **ขั้นตอนที่ 4: เตรียม Webhook URL**
**Format ของ Webhook URL** 🌐
```
https://yourdomain.com/path/webhook_handler.php
```
**✅ ตัวอย่าง URL ที่ถูกต้อง:**
```
https://mycompany.com/telegram-bot/webhook_handler.php
https://bot.yourcompany.co.th/webhook_handler.php
```
**❌ ข้อผิดพลาดที่พบบ่อย:**
```
❌ http:// (ต้องเป็น https://)
❌ localhost (ไม่สามารถใช้ได้)
❌ ไฟล์ไม่มีจริง (404 Error)
❌ SSL Certificate หมดอายุ
```
### 🔧 **ขั้นตอนที่ 5: ตั้งค่า Webhook**
#### **วิธีที่ 1: ใช้ cURL Command** 💻
```bash
curl -F "url=https://yourdomain.com/path/webhook_handler.php" \
https://api.telegram.org/bot[YOUR_BOT_TOKEN]/setWebhook
```
**ตัวอย่างจริง:**
```bash
curl -F "url=https://eleave.acc.in.th/bot/webhook_handler.php" \
https://api.telegram.org/bot123456789:ABCdefGHI/setWebhook
```
#### **วิธีที่ 2: ใช้ PHP Script** 🐘
```php
<?php
$botToken = 'YOUR_BOT_TOKEN';
$webhookUrl = 'https://yourdomain.com/path/webhook_handler.php';
$url = "https://api.telegram.org/bot{$botToken}/setWebhook";
$data = ['url' => $webhookUrl];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
```
#### **วิธีที่ 3: ใช้ Browser** (แนะนำ) 🌐
```
https://api.telegram.org/bot[YOUR_BOT_TOKEN]/setWebhook?url=https://yourdomain.com/path/webhook_handler.php
```
### ✅ **ขั้นตอนที่ 6: ตรวจสอบ Webhook**
**ตรวจสอบสถานะ Webhook** 🔍
```bash
curl https://api.telegram.org/bot[YOUR_BOT_TOKEN]/getWebhookInfo
```
**ผลลัพธ์ที่ควรได้:**
```json
{
"ok": true,
"result": {
"url": "https://yourdomain.com/path/webhook_handler.php",
"has_custom_certificate": false,
"pending_update_count": 0,
"last_error_date": 0,
"max_connections": 40
}
}
```
> ✅ **หมายเหตุ**: ถ้า `pending_update_count` เป็น 0 แสดงว่า Webhook ทำงานปกติ
```php
$webhookUrl = 'https://yourdomain.com/path/webhook_handler.php';
$url = "https://api.telegram.org/bot{$botToken}/setWebhook";
$data = ['url' => $webhookUrl];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
```
10. **วิธีที่ 3: ใช้ Browser** 🌐
```
https://api.telegram.org/bot[YOUR_BOT_TOKEN]/setWebhook?url=https://yourdomain.com/path/webhook_handler.php
```
### ขั้นตอนที่ 6: ตรวจสอบ Webhook
11. **ตรวจสอบสถานะ Webhook** ✅
```bash
curl https://api.telegram.org/bot[YOUR_BOT_TOKEN]/getWebhookInfo
```
**ผลลัพธ์ที่ควรได้:**
```json
{
"ok": true,
"result": {
"url": "https://yourdomain.com/path/webhook_handler.php",
"has_custom_certificate": false,
"pending_update_count": 0
}
}
```
---
## 🔧 **การกำหนดค่า**
⚙️ Config Files และการตั้งค่า (คลิกเพื่อดู)
### 📝 **ขั้นตอนที่ 7: แก้ไขไฟล์ Config**
#### **1. Config Telegram Bot** 🤖
แก้ไขไฟล์ `config/telegram_config.php`:
```php
<?php
// Telegram Bot Configuration - สำคัญมาก!
define('TELEGRAM_BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE');
// ตัวอย่างการใช้งานจริง:
// define('TELEGRAM_BOT_TOKEN', '123456789:ABCdefGHIjklMNOpqrsTUVwxyz1234567890');
// Optional: Debug Mode (ปิดใน Production)
define('TELEGRAM_DEBUG', false);
?>
```
#### **2. Config Database** 🗄️
ตรวจสอบไฟล์ `config/db_config.php`:
```php
<?php
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'your_database_name');
define('DB_USER', 'your_username');
define('DB_PASS', 'your_password');
// Registration Settings
define('ALLOW_SELF_REGISTRATION', true); // เปิดลงทะเบียนอัตโนมัติ
define('REQUIRE_ADMIN_APPROVAL', false); // ไม่ต้องรออนุมัติ
// Security Settings
define('RATE_LIMIT_ENABLED', true); // เปิด Rate Limiting
define('MAX_REQUESTS_PER_MINUTE', 10); // จำกัด 10 ครั้ง/นาที
?>
```
#### **3. ตรวจสอบไฟล์ webhook_handler.php** 🔍
```php
// ตรวจสอบว่าไฟล์มี path ที่ถูกต้อง
require_once __DIR__.'/config/telegram_config.php';
require_once __DIR__.'/config/db_config.php';
require_once __DIR__.'/src/Core/Database.php';
require_once __DIR__.'/src/Services/TelegramService.php';
// ... ไฟล์อื่นๆ
```
### 🎛️ **ขั้นตอนที่ 8: ตั้งค่าคำสั่งบอท**
#### **ตั้งค่าเมนูคำสั่งให้บอท** 📋
```bash
curl -X POST "https://api.telegram.org/bot[YOUR_BOT_TOKEN]/setMyCommands" \
-H "Content-Type: application/json" \
-d '{
"commands": [
{"command": "start", "description": "🚀 เริ่มการสนทนากับบอท"},
{"command": "register", "description": "📝 ลงทะเบียนเข้าใช้งานระบบ"},
{"command": "help", "description": "❓ แสดงคำสั่งที่ใช้ได้"},
{"command": "status", "description": "📊 ตรวจสอบสถานะการลา"},
{"command": "leave", "description": "🏖️ ขอลาป่วย/ลากิจ"},
{"command": "wfh", "description": "🏠 ขอ Work From Home"},
{"command": "balance", "description": "⚖️ เช็คยอดวันลาคงเหลือ"},
{"command": "cancel", "description": "❌ ยกเลิกการดำเนินการ"}
]
}'
```
### 🗂️ **โครงสร้างไฟล์ที่สำคัญ**
<table>
<tr>
<th>ไฟล์/โฟลเดอร์</th>
<th>หน้าที่</th>
<th>สถานะ</th>
</tr>
<tr>
<td><code>webhook_handler.php</code></td>
<td>รับ/ประมวลผลข้อความจาก Telegram</td>
<td>🟢 Required</td>
</tr>
<tr>
<td><code>config/telegram_config.php</code></td>
<td>การตั้งค่า Bot Token</td>
<td>🟢 Required</td>
</tr>
<tr>
<td><code>config/db_config.php</code></td>
<td>การตั้งค่าฐานข้อมูล</td>
<td>🟢 Required</td>
</tr>
<tr>
<td><code>logs/</code></td>
<td>เก็บ Log Files</td>
<td>🔵 Auto-created</td>
</tr>
<tr>
<td><code>src/Handlers/</code></td>
<td>Logic การจัดการคำสั่ง</td>
<td>🟢 Required</td>
</tr>
</table>
### ขั้นตอนที่ 8: ตั้งค่าคำสั่งบอท
14. **ตั้งค่าเมนูคำสั่ง** 📋
```bash
curl -X POST "https://api.telegram.org/bot[YOUR_BOT_TOKEN]/setMyCommands" \
-H "Content-Type: application/json" \
-d '{
"commands": [
{"command": "start", "description": "เริ่มการสนทนา"},
{"command": "register", "description": "ลงทะเบียนเข้าใช้งาน"},
{"command": "help", "description": "แสดงคำสั่งที่ใช้ได้"},
{"command": "status", "description": "ตรวจสอบสถานะ"},
{"command": "leave", "description": "ขอลา"},
{"command": "wfh", "description": "ขอ Work From Home"},
{"command": "balance", "description": "เช็คยอดวันลา"},
{"command": "cancel", "description": "ยกเลิกการดำเนินการ"}
]
}'
```
---
## 🧪 **การทดสอบ**
<summary><b>🔍 ทดสอบการทำงานของระบบ (คลิกเพื่อดู)</b></summary>
### 🚀 **ขั้นตอนที่ 9: ทดสอบบอท**
#### **1. ทดสอบการเชื่อมต่อ API** 🔗
```bash
# ทดสอบ Bot API
curl https://api.telegram.org/bot[YOUR_BOT_TOKEN]/getMe
```
**ผลลัพธ์ที่ควรได้:**
</div>
```json
{
"ok": true,
"result": {
"id": 123456789,
"is_bot": true,
"first_name": "บอทน้องลา",
"username": "YourBotUsername",
"can_join_groups": true,
"can_read_all_group_messages": false,
"supports_inline_queries": false
}
}
```
#### **2. ทดสอบการส่งข้อความ** 💬
สร้างไฟล์ `test_telegram.php`:
```php
<?php
require_once 'config/telegram_config.php';
require_once 'src/Services/TelegramService.php';
$telegram = new TelegramService();
$testChatId = 'YOUR_CHAT_ID'; // ใส่ Chat ID ของคุณ
$result = $telegram->sendMessage($testChatId, "🧪 ทดสอบการส่งข้อความจากบอท\n✅ หากคุณเห็นข้อความนี้ แสดงว่าบอททำงานปกติ!");
echo "Test Result: " . json_encode($result, JSON_PRETTY_PRINT);
?>
```
รันการทดสอบ:
```bash
php test_telegram.php
```
#### **3. ทดสอบ Webhook** 🔄
```bash
# ส่งข้อความทดสอบไปยัง Webhook
echo '{
"update_id": 1,
"message": {
"message_id": 1,
"from": {"id": 123456, "first_name": "Test"},
"chat": {"id": 123456, "type": "private"},
"date": 1640995200,
"text": "/start"
}
}' | curl -X POST -H "Content-Type: application/json" -d @- \
https://yourdomain.com/path/webhook_handler.php
```
#### **4. ตรวจสอบ Logs** 📊
<table>
<tr>
<th>Log Type</th>
<th>Command</th>
<th>หมายเหตุ</th>
</tr>
<tr>
<td>Webhook Activity</td>
<td><code>tail -f logs/webhook.log</code></td>
<td>ดูการทำงานของ Webhook</td>
</tr>
<tr>
<td>Security Events</td>
<td><code>tail -f logs/security.log</code></td>
<td>ดูเหตุการณ์ความปลอดภัย</td>
</tr>
<tr>
<td>Registration Activity</td>
<td><code>ls -la logs/registration_*.json</code></td>
<td>ดูกิจกรรมการลงทะเบียน</td>
</tr>
<tr>
<td>Rate Limiting</td>
<td><code>ls -la logs/rate_limit_*.json</code></td>
<td>ดูการจำกัดอัตรา</td>
</tr>
</table>
### ✅ **ตรวจสอบขั้นตอนสุดท้าย**
**1. ทดสอบคำสั่งพื้นฐาน:**
- [ ] ส่ง `/start` ไปยังบอท
- [ ] ลองลงทะเบียนด้วย `/register`
- [ ] ทดสอบ `/help` เพื่อดูคำสั่ง
**2. ทดสอบฟังก์ชันหลัก:**
- [ ] ขอลาด้วย `/leave`
- [ ] ขอ WFH ด้วย `/wfh`
- [ ] เช็คยอดด้วย `/balance`
**3. ตรวจสอบความปลอดภัย:**
- [ ] Rate Limiting ทำงานหรือไม่
- [ ] Input Validation ทำงานหรือไม่
- [ ] Log Files ถูกสร้างหรือไม่
---
## 🛠️ **การแก้ไขปัญหา**
<summary><b>❌ Solutions สำหรับปัญหาที่พบบ่อย (คลิกเพื่อดู)</b></summary>
### 🚨 **ปัญหาที่พบบ่อยและวิธีแก้ไข**
#### **1. 🌐 Webhook ไม่ทำงาน**
<table>
<tr>
<th width="30%">อาการ</th>
<th width="70%">วิธีแก้ไข</th>
</tr>
<tr>
<td>❌ Bot ไม่ตอบเมื่อส่งข้อความ</td>
<td>
<summary>ตรวจสอบ Webhook Status</summary>
```bash
# ดู Webhook Info
curl https://api.telegram.org/bot[TOKEN]/getWebhookInfo
# ตรวจสอบ SSL Certificate
curl -I https://yourdomain.com/webhook_handler.php
# ทดสอบ HTTP Response
curl -X POST -d '{}' https://yourdomain.com/webhook_handler.php
```
</td>
</tr>
<tr>
<td>⚠️ SSL Certificate Error</td>
<td>
<summary>อัปเดต SSL Certificate</summary>
```bash
# ตรวจสอบ SSL
openssl s_client -connect yourdomain.com:443
# อัปเดต Certificate (ใช้ Certbot)
sudo certbot renew
sudo systemctl reload apache2
```
</td>
</tr>
<tr>
<td>🔒 Permission Error</td>
<td>
<summary>ตั้งค่า File Permissions</summary>
```bash
# ตั้งค่า Permissions
chmod -R 755 /path/to/bot/
chmod -R 777 /path/to/bot/logs/
chown -R www-data:www-data /path/to/bot/
```
</td>
</tr>
</table>
#### **2. 🤖 Bot ไม่ตอบ/Error**
<table>
<tr>
<th width="30%">อาการ</th>
<th width="70%">วิธีแก้ไข</th>
</tr>
<tr>
<td>💥 PHP Fatal Error</td>
<td>
<summary>เปิด Debug Mode</summary>
```php
// เพิ่มในไฟล์ webhook_handler.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__.'/logs/php_errors.log');
```
</td>
</tr>
<tr>
<td>🗄️ Database Connection Error</td>
<td>
<summary>ทดสอบการเชื่อมต่อ Database</summary>
```bash
# ทดสอบ Database Connection
php test_simple.php
# ตรวจสอบ MySQL Service
sudo systemctl status mysql
sudo systemctl restart mysql
```
</td>
</tr>
<tr>
<td>📁 Missing Files</td>
<td>
<summary>ตรวจสอบไฟล์ที่จำเป็น</summary>
```bash
# ตรวจสอบไฟล์สำคัญ
ls -la config/telegram_config.php
ls -la config/db_config.php
ls -la webhook_handler.php
ls -la src/Services/TelegramService.php
```
</td>
</tr>
</table>
#### **3. 🔐 ปัญหาความปลอดภัย**
<table>
<tr>
<th width="30%">อาการ</th>
<th width="70%">วิธีแก้ไข</th>
</tr>
<tr>
<td>🚫 Rate Limiting Block</td>
<td>
<summary>จัดการ Rate Limits</summary>
```bash
# ล้าง Rate Limit Files หมดอายุ
find logs/ -name "rate_limit_*.json" -mtime +1 -delete
# ตรวจสอบ Rate Limit Config
grep RATE_LIMIT config/db_config.php
```
</td>
</tr>
<tr>
<td>🛡️ Input Validation Error</td>
<td>
<summary>ตรวจสอบ Input Sanitization</summary>
```bash
# ดู Security Logs
tail -f logs/security.log
# ตรวจสอบ SecurityHelper
grep -n "sanitize" src/Core/SecurityHelper.php
```
</td>
</tr>
</table>
### 🔧 **เครื่องมือช่วยแก้ปัญหา**
#### **Health Check Script**
สร้างไฟล์ `health_check.php`:
```php
<?php
echo "🏥 Bot Health Check\n";
echo "==================\n\n";
// ตรวจสอบไฟล์ Config
$configs = [
'config/telegram_config.php',
'config/db_config.php'
];
foreach ($configs as $config) {
if (file_exists($config)) {
echo "✅ {$config}\n";
} else {
echo "❌ {$config} - MISSING!\n";
}
}
// ตรวจสอบ Database Connection
try {
require_once 'config/db_config.php';
require_once 'src/Core/Database.php';
$db = Database::getInstance();
$pdo = $db->getConnection();
echo "✅ Database Connection\n";
} catch (Exception $e) {
echo "❌ Database Connection - ERROR: " . $e->getMessage() . "\n";
}
// ตรวจสอบ Telegram API
try {
require_once 'config/telegram_config.php';
$url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/getMe";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data['ok']) {
echo "✅ Telegram API - Bot: " . $data['result']['first_name'] . "\n";
} else {
echo "❌ Telegram API - ERROR\n";
}
} catch (Exception $e) {
echo "❌ Telegram API - ERROR: " . $e->getMessage() . "\n";
}
// ตรวจสอบ Log Directory
if (is_dir('logs') && is_writable('logs')) {
echo "✅ Logs Directory\n";
} else {
echo "❌ Logs Directory - Check permissions!\n";
}
echo "\n🎯 Health Check Complete!\n";
?>
```
รันการตรวจสอบ:
```bash
php health_check.php
```
#### **Quick Debug Commands**
```bash
# ดู Error Logs ทั้งหมด
tail -f /var/log/apache2/error.log
tail -f logs/webhook.log
tail -f logs/security.log
# ล้าง Cache และ Temp Files
rm -f logs/registration_*.json
rm -f logs/rate_limit_*.json
rm -f logs/user_*_state.txt
# รีสตาร์ท Services
sudo systemctl restart apache2
sudo systemctl restart mysql
```
#### **3. Database Connection Error**
```bash
# ทดสอบการเชื่อมต่อฐานข้อมูล
php test_simple.php
```
### ✅ วิธีแก้ไข
#### **SSL Issues:**
```bash
# ตรวจสอบ SSL
openssl s_client -connect yourdomain.com:443
# Update Certificate
certbot renew
```
#### **PHP Errors:**
```bash
# ตรวจสอบ PHP error log
tail -f /var/log/apache2/error.log
tail -f /var/log/php_errors.log
```
#### **File Permissions:**
```bash
# ตั้งค่า permissions
chmod -R 755 /path/to/bot/
chmod -R 777 /path/to/bot/logs/
```
---
## 📊 **การจัดการ**
<summary><b>🎛️ Monitoring และ Maintenance (คลิกเพื่อดู)</b></summary>
### 🔧 **คำสั่งที่มีประโยชน์**
#### **การจัดการ Bot API** 🤖
<table>
<tr>
<th width="30%">คำสั่ง</th>
<th width="50%">หน้าที่</th>
<th width="20%">ความถี่</th>
</tr>
<tr>
<td>
```bash
curl https://api.telegram.org/bot[TOKEN]/getMe
```
</td>
<td>ตรวจสอบข้อมูลบอท</td>
<td>🟢 เมื่อต้องการ</td>
</tr>
<tr>
<td>
```bash
curl https://api.telegram.org/bot[TOKEN]/getWebhookInfo
```
</td>
<td>ดูสถานะ Webhook</td>
<td>🟡 รายวัน</td>
</tr>
<tr>
<td>
```bash
curl https://api.telegram.org/bot[TOKEN]/deleteWebhook
```
</td>
<td>ลบ Webhook (เฉพาะเมื่อจำเป็น)</td>
<td>🔴 Emergency</td>
</tr>
<tr>
<td>
```bash
curl -X POST "https://api.telegram.org/bot[TOKEN]/sendMessage" \
-d "chat_id=CHAT_ID&text=System Notification"
```
</td>
<td>ส่งข้อความแจ้งเตือนระบบ</td>
<td>🟢 เมื่อต้องการ</td>
</tr>
</table>
### 📈 **Monitoring และการติดตาม**
#### **ตรวจสอบ Logs แบบ Real-time** 📊
```bash
# สำหรับ Production Monitoring
#!/bin/bash
echo "📊 Starting Real-time Monitoring..."
# Terminal 1: Webhook Activity
gnome-terminal --tab --title="Webhook Logs" -- bash -c "tail -f logs/webhook.log; exec bash"
# Terminal 2: Security Events
gnome-terminal --tab --title="Security Logs" -- bash -c "tail -f logs/security.log; exec bash"
# Terminal 3: System Errors
gnome-terminal --tab --title="Error Logs" -- bash -c "tail -f /var/log/apache2/error.log; exec bash"
echo "🎯 Monitoring terminals opened!"
```
#### **Dashboard สำหรับ Admin** 🎛️
สร้างไฟล์ `admin_dashboard.php`:
```php
<?php
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html>
<head>
<title>🤖 Bot Admin Dashboard</title>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
.card { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.status-ok { color: #28a745; } .status-error { color: #dc3545; }
.metric { display: inline-block; margin: 10px; padding: 10px; background: #e9ecef; border-radius: 4px; }
</style>
</head>
<body>
<h1>🤖 Telegram Bot Dashboard</h1>
<div class="card">
<h2>📊 Statistics</h2>
<?php
try {
require_once 'config/db_config.php';
require_once 'src/Core/Database.php';
$db = Database::getInstance();
$pdo = $db->getConnection();
// จำนวนผู้ใช้งาน
$stmt = $pdo->query("SELECT COUNT(*) as count FROM employees");
$userCount = $stmt->fetch()['count'];
// จำนวนคำขอวันนี้
$stmt = $pdo->query("SELECT COUNT(*) as count FROM leave_requests WHERE DATE(created_at) = CURDATE()");
$todayRequests = $stmt->fetch()['count'];
echo "<div class='metric'>👥 ผู้ใช้งาน: {$userCount}</div>";
echo "<div class='metric'>📝 คำขอวันนี้: {$todayRequests}</div>";
} catch (Exception $e) {
echo "<p class='status-error'>❌ Database Error: " . $e->getMessage() . "</p>";
}
?>
</div>
<div class="card">
<h2>🔍 System Status</h2>
<?php
// ตรวจสอบไฟล์สำคัญ
$files = [
'config/telegram_config.php' => 'Telegram Config',
'config/db_config.php' => 'Database Config',
'webhook_handler.php' => 'Webhook Handler',
'logs/' => 'Logs Directory'
];
foreach ($files as $file => $name) {
if (file_exists($file)) {
echo "<p class='status-ok'>✅ {$name}</p>";
} else {
echo "<p class='status-error'>❌ {$name} - Missing!</p>";
}
}
// ตรวจสอบ Telegram API
try {
require_once 'config/telegram_config.php';
$url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/getMe";
$response = @file_get_contents($url);
if ($response) {
$data = json_decode($response, true);
if ($data['ok']) {
echo "<p class='status-ok'>✅ Telegram API - Bot: " . $data['result']['first_name'] . "</p>";
} else {
echo "<p class='status-error'>❌ Telegram API Error</p>";
}
} else {
echo "<p class='status-error'>❌ Cannot connect to Telegram API</p>";
}
} catch (Exception $e) {
echo "<p class='status-error'>❌ Telegram API Error: " . $e->getMessage() . "</p>";
}
?>
</div>
<div class="card">
<h2>📄 Recent Logs</h2>
<?php
if (file_exists('logs/webhook.log')) {
$logs = array_slice(file('logs/webhook.log'), -10);
echo "<pre style='background: #f8f9fa; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px;'>";
echo htmlspecialchars(implode('', $logs));
echo "</pre>";
} else {
echo "<p>No logs found</p>";
}
?>
</div>
<div class="card">
<h2>🛠️ Quick Actions</h2>
<button onclick="location.reload()">🔄 Refresh Dashboard</button>
<button onclick="window.open('logs/', '_blank')">📁 View Logs Folder</button>
</div>
<script>
// Auto-refresh every 30 seconds
setTimeout(() => location.reload(), 30000);
</script>
</body>
</html>
```
### 🔄 **Maintenance และการบำรุงรักษา**
#### **รายวัน (Daily Maintenance)** 📅
```bash
#!/bin/bash
# daily_maintenance.sh
echo "🔄 Daily Maintenance Started"
# 1. ตรวจสอบ Disk Space
df -h | grep -E '(8[0-9]|9[0-9])%' && echo "⚠️ Disk space warning!"
# 2. ล้าง Temp Files
find logs/ -name "registration_*.json" -mtime +1 -delete
find logs/ -name "rate_limit_*.json" -mtime +1 -delete
find logs/ -name "user_*_state.txt" -mtime +1 -delete
# 3. Compress Old Logs
find logs/ -name "*.log" -mtime +7 -exec gzip {} \;
# 4. Database Cleanup (optional)
# php -r "require_once 'src/Core/Database.php'; Database::cleanup();"
echo "✅ Daily Maintenance Completed"
```
#### **รายสัปดาห์ (Weekly Maintenance)** 📊
```bash
#!/bin/bash
# weekly_maintenance.sh
echo "📊 Weekly Maintenance Started"
# 1. ล้าง Log Files เก่า
find logs/ -name "*.log.gz" -mtime +30 -delete
# 2. Database Optimization
mysql -u$DB_USER -p$DB_PASS $DB_NAME -e "OPTIMIZE TABLE employees, leave_requests, leave_balances;"
# 3. Backup Database
mysqldump -u$DB_USER -p$DB_PASS $DB_NAME > "backups/db_backup_$(date +%Y%m%d).sql"
gzip "backups/db_backup_$(date +%Y%m%d).sql"
# 4. Generate Weekly Report
php generate_weekly_report.php
echo "✅ Weekly Maintenance Completed"
```
#### **Health Check Automation** 🏥
```bash
#!/bin/bash
# health_check_cron.sh
HEALTH_STATUS=$(php health_check.php)
ERROR_COUNT=$(echo "$HEALTH_STATUS" | grep -c "❌")
if [ $ERROR_COUNT -gt 0 ]; then
echo "🚨 System Health Alert!"
echo "$HEALTH_STATUS"
# ส่งแจ้งเตือนไปยัง Admin (เพิ่ม Chat ID ของ Admin)
curl -X POST "https://api.telegram.org/bot[TOKEN]/sendMessage" \
-d "chat_id=[ADMIN_CHAT_ID]&text=🚨 Bot System Alert:%0A%0A$HEALTH_STATUS"
fi
```
#### **ตั้งค่า Cron Jobs** ⏰
```bash
# เพิ่มใน crontab
crontab -e
# Daily maintenance ทุกวันเวลา 02:00
0 2 * * * /path/to/bot/daily_maintenance.sh >> /path/to/bot/logs/maintenance.log 2>&1
# Weekly maintenance ทุกวันอาทิตย์เวลา 03:00
0 3 * * 0 /path/to/bot/weekly_maintenance.sh >> /path/to/bot/logs/maintenance.log 2>&1
# Health check ทุกชั่วโมง
0 * * * * /path/to/bot/health_check_cron.sh >> /path/to/bot/logs/health.log 2>&1
# Rate limit cleanup ทุก 15 นาที
*/15 * * * * php /path/to/bot/cleanup_rate_limits.php
```
---
<div align="center">
## 🎉 **บอทพร้อมใช้งานแล้ว!**
### � **ขั้นตอนสุดท้าย - ทดสอบบอทของคุณ**
<table>
<tr>
<td align="center" width="25%">
**1️⃣ ค้นหาบอท**
<br/>
🔍 ค้นหา `@YourBotUsername` ใน Telegram
</td>
<td align="center" width="25%">
**2️⃣ เริ่มการสนทนา**
<br/>
🚀 กด **"Start"** หรือพิมพ์ `/start`
</td>
<td align="center" width="25%">
**3️⃣ ลงทะเบียน**
<br/>
📝 ทำตามขั้นตอนการลงทะเบียน
</td>
<td align="center" width="25%">
**4️⃣ เริ่มใช้งาน**
<br/>
🎯 ใช้คำสั่งต่างๆ ได้เลย!
</td>
</tr>
</table>
### � **คำสั่งหลักที่ควรจำ**
| คำสั่ง | หน้าที่ | ตัวอย่าง |
|--------|---------|----------|
| `/start` | เริ่มการใช้งาน | เริ่มสนทนากับบอท |
| `/register` | ลงทะเบียน | สำหรับผู้ใช้งานใหม่ |
| `/leave` | ขอลา | ลาป่วย, ลากิจ, ลาพักผ่อน |
| `/wfh` | ขอ WFH | Work From Home |
| `/balance` | เช็คยอดลา | ดูวันลาคงเหลือ |
| `/help` | คำสั่งทั้งหมด | ดูรายการคำสั่ง |
---
### 🎖️ **ระบบที่ได้มาตรฐาน**




### 📊 **คุณสมบัติเด่น**
✅ **Rate Limiting** - ป้องกันการใช้งานเกินขีดจำกัด
✅ **Input Validation** - ตรวจสอบข้อมูลนำเข้าทุกครั้ง
✅ **File Encryption** - เข้ารหัสไฟล์สำคัญ
✅ **Real-time Monitoring** - ติดตามการทำงานแบบเรียลไทม์
✅ **Auto Maintenance** - บำรุงรักษาอัตโนมัติ
✅ **Error Handling** - จัดการข้อผิดพลาดครอบคลุม
---
<br/>
**🔖 เวอร์ชัน:** 1.0 | **📅 อัปเดต:** กรกฎาคม 2568 | **👨💻 สถานะ:** Production Ready
Made with ❤️ for **better workplace communication**
*ระบบนี้ออกแบบมาเพื่อความง่าย ความปลอดภัย และการใช้งานจริงในองค์กร*
</div>