- เตรียม URL สำหรับรับ Webhook
- ต้องใช้ URL ที่เข้าถึงได้จากอินเทอร์เน็ต (เช่น https://yourdomain.com/bot.php)
- ถ้าใช้ในเครื่องเอง แนะนำให้ใช้เครื่องมืออย่าง ngrok เพื่อสร้าง URL ชั่วคราว
- ตั้งค่า Webhook ผ่าน API
- เรียก URL ด้านล่างนี้ในเบราว์เซอร์หรือใช้ cURL
https://api.telegram.org/bot<YOUR_API_TOKEN>/setWebhook?url=https://yourdomain.com/bot.php
- เปลี่ยน
<YOUR_API_TOKEN>
และhttps://yourdomain.com/bot.php
ให้เป็นของคุณเอง
3. ตรวจสอบ Webhook
https://api.telegram.org/bot<YOUR_API_TOKEN>/getWebhookInfo
- จะแสดงข้อมูล Webhook ปัจจุบัน และสถานะการเชื่อมต่อ
💻 เขียนโค้ด PHP รับข้อมูลจาก Webhook
สร้างไฟล์ bot.php
สำหรับรับข้อมูลจาก Telegram:
<?php // รับข้อมูล JSON จาก Webhook $content = file_get_contents("php://input"); $update = json_decode($content, true); if (!$update) { exit; // ออกจากการทำงานถ้าไม่มีข้อมูล } // ดึงข้อมูลที่จำเป็น $message = $update['message']['text'] ?? ''; $chatId = $update['message']['chat']['id'] ?? ''; // ตั้งค่า API Token $apiToken = "YOUR_API_TOKEN_HERE"; // ฟังก์ชันส่งข้อความกลับไปยัง Telegram function sendTelegramMessage($chatId, $message, $apiToken) { $url = "https://api.telegram.org/bot$apiToken/sendMessage"; $postData = [ 'chat_id' => $chatId, 'text' => $message, 'parse_mode' => 'HTML' ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_exec($ch); curl_close($ch); } // ตัวอย่าง: เมื่อผู้ใช้ส่งคำว่า "hello" ให้ตอบกลับ "สวัสดี!" if (strtolower($message) === "hello") { sendTelegramMessage($chatId, "สวัสดี! มีอะไรให้ช่วยไหม?", $apiToken); } ?>
🌐 3. ทดสอบการทำงาน
- ลองพิมพ์คำว่า
hello
ในแชทของบอท - บอทควรตอบกลับว่า
สวัสดี! มีอะไรให้ช่วยไหม?
🛠️ 4. เคล็ดลับและการแก้ปัญหา
- หาก Webhook ไม่ทำงาน ลองใช้คำสั่งลบ Webhook ก่อนตั้งค่าใหม่:
https://api.telegram.org/bot<YOUR_API_TOKEN>/deleteWebhook
- ตรวจสอบ Log ของ Server (เช่น Apache/Nginx) เพื่อดู Error
- ใช้
file_put_contents("log.txt", $content);
ใน PHP เพื่อ Debug ข้อมูลที่รับเข้ามา
วิธีการตรวจสอบ chatId หรือ chatGroup โดยไม่ผ่าน webhook/getUpdates/deleteWebhook
https://api.telegram.org/bot
(
**
ถ้าบอทมีการ active webhook จะใช้งานไม่ได้ต้องทำการรันเรียก
https://api.telegram.org/bot
ก่อน
**
)