2015-10-23 25 views
17

Tại sao webhook của tôi không hoạt động? Tôi không nhận được bất kỳ dữ liệu nào từ API bot điện tín. Dưới đây là lời giải thích chi tiết các vấn đề của tôi:Gặp sự cố với webhook với Telegram Bot API

tôi đã SSL cert từ StartSSL, nó hoạt động tốt trên trang web của tôi (theo GeoCerts SSL checker), nhưng vẫn có vẻ như webhook tôi để Telegram Bot API không hoạt động (mặc dù nó nói rằng webhook đã được thiết lập tôi không nhận được bất kỳ dữ liệu nào).

Tôi đang làm cho một webhook để kịch bản của tôi trên trang web của tôi dưới hình thức này:

https://api.telegram.org/bot<token>/setWebhook?url=https://mywebsite.com/path/to/giveawaysbot.php 

tôi nhận được văn bản này trong phản ứng:

{"ok":true,"result":true,"description":"Webhook was set"} 

Vì vậy, nó phải được làm việc, nhưng nó thực sự doesn 't.

Đây là mã kịch bản của tôi:

<?php 

ini_set('error_reporting', E_ALL); 

$botToken = "<token>"; 
$website = "https://api.telegram.org/bot".$botToken; 

$update = file_get_contents('php://input'); 
$update = json_decode($update); 

print_r($update); // this is made to check if i get any data or not 

$chatId = $update["message"]["chat"]["id"]; 
$message = $update["message"]["text"]; 


switch ($message) { 
    case "/test": 
     sendMessage($chatId,"test complete"); 
     break; 
    case "/hi": 
     sendMessage($chatId,"hey there"); 
     break; 
    default: 
     sendMessage($chatId,"nono i dont understand you"); 
} 


function sendMessage ($chatId, $message) { 
    $url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message); 
    file_get_contents($url); 
} 

?> 

Tôi không thực sự nhận được bất kỳ dữ liệu đến $ cập nhật. Vì vậy, webhook không hoạt động. Tại sao?

+1

Có thể liên quan đến việc không nhận được bất kỳ dữ liệu nào, bạn nên thực hiện 'json_decode ($ update, true)' để lấy dữ liệu dưới dạng mảng, thay vì 'stdClass'. – ixchi

+0

ixchi, 'json_decode (cập nhật $, đúng)' không thay đổi gì, vẫn không hoạt động: \ – markelov

+0

Bạn có chắc chắn rằng bạn đang thực sự nhận được webhook không? Nó hoạt động chính xác cho tôi. – ixchi

Trả lời

3

Tôi gặp sự cố tương tự. Bây giờ giải quyết. Sự cố có thể có trong chứng chỉ công khai sai. Hãy làm theo hướng dẫn sự chú ý của tôi đề xuất trong dự án của tôi:

https://github.com/solyaris/BOTServer/blob/master/wiki/usage.md#step-4-create-self-signed-certificate

openssl req -newkey rsa:2048 -sha256 -nodes -keyout /your_home/BOTServer/ssl/PRIVATE.key -x509 -days 365 -out /your_home/BOTServer/ssl/PUBLIC.pem -subj "/C=IT/ST=state/L=location/O=description/CN=your_domain.com" 

Telegram setWebhooks API không kiểm tra dữ liệu bên trong giấy chứng nhận kỹ thuật số tự ký của bạn, trở về "ok" ngay cả khi bằng ví dụ bạn làm không chỉ định/CN hợp lệ! Vì vậy, hãy cẩn thận để tạo một chứng chỉ .pem công khai có chứa /CN = your_domain tương ứng với tên miền REAL HOST của bạn!

4

Tôi đã gặp phải vấn đề này. Tôi đã cố gắng tìm khắp mọi nơi và không thể tìm ra giải pháp cho vấn đề của mình, bởi vì mọi người lúc nào cũng nói rằng vấn đề là chứng chỉ SSL. Nhưng tôi đã tìm thấy vấn đề, và đó là rất nhiều thứ bị thiếu trên mã để tương tác với điện tín API webhook curl curv và loại công cụ này. Sau khi tôi xem một ví dụ tại tài liệu về bot điện tín, tôi đã giải quyết được vấn đề của mình. Nhìn ví dụ này https://core.telegram.org/bots/samples/hellobot

<?php 
//telegram example 
define('BOT_TOKEN', '12345678:replace-me-with-real-token'); 
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/'); 

function apiRequestWebhook($method, $parameters) { 
    if (!is_string($method)) { 
    error_log("Method name must be a string\n"); 
    return false; 
    } 

    if (!$parameters) { 
    $parameters = array(); 
    } else if (!is_array($parameters)) { 
    error_log("Parameters must be an array\n"); 
    return false; 
    } 

    $parameters["method"] = $method; 

    header("Content-Type: application/json"); 
    echo json_encode($parameters); 
    return true; 
} 

function exec_curl_request($handle) { 
    $response = curl_exec($handle); 

    if ($response === false) { 
    $errno = curl_errno($handle); 
    $error = curl_error($handle); 
    error_log("Curl returned error $errno: $error\n"); 
    curl_close($handle); 
    return false; 
    } 

    $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE)); 
    curl_close($handle); 

    if ($http_code >= 500) { 
    // do not wat to DDOS server if something goes wrong 
    sleep(10); 
    return false; 
    } else if ($http_code != 200) { 
    $response = json_decode($response, true); 
    error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n"); 
    if ($http_code == 401) { 
     throw new Exception('Invalid access token provided'); 
    } 
    return false; 
    } else { 
    $response = json_decode($response, true); 
    if (isset($response['description'])) { 
     error_log("Request was successfull: {$response['description']}\n"); 
    } 
    $response = $response['result']; 
    } 

    return $response; 
} 

function apiRequest($method, $parameters) { 
    if (!is_string($method)) { 
    error_log("Method name must be a string\n"); 
    return false; 
    } 

    if (!$parameters) { 
    $parameters = array(); 
    } else if (!is_array($parameters)) { 
    error_log("Parameters must be an array\n"); 
    return false; 
    } 

    foreach ($parameters as $key => &$val) { 
    // encoding to JSON array parameters, for example reply_markup 
    if (!is_numeric($val) && !is_string($val)) { 
     $val = json_encode($val); 
    } 
    } 
    $url = API_URL.$method.'?'.http_build_query($parameters); 

    $handle = curl_init($url); 
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($handle, CURLOPT_TIMEOUT, 60); 

    return exec_curl_request($handle); 
} 

function apiRequestJson($method, $parameters) { 
    if (!is_string($method)) { 
    error_log("Method name must be a string\n"); 
    return false; 
    } 

    if (!$parameters) { 
    $parameters = array(); 
    } else if (!is_array($parameters)) { 
    error_log("Parameters must be an array\n"); 
    return false; 
    } 

    $parameters["method"] = $method; 

    $handle = curl_init(API_URL); 
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($handle, CURLOPT_TIMEOUT, 60); 
    curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters)); 
    curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); 

    return exec_curl_request($handle); 
} 

function processMessage($message) { 
    // process incoming message 
    $message_id = $message['message_id']; 
    $chat_id = $message['chat']['id']; 
    if (isset($message['text'])) { 
    // incoming text message 
    $text = $message['text']; 

    if (strpos($text, "/start") === 0) { 
     apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
     'keyboard' => array(array('Hello', 'Hi')), 
     'one_time_keyboard' => true, 
     'resize_keyboard' => true))); 
    } else if ($text === "Hello" || $text === "Hi") { 
     apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you')); 
    } else if (strpos($text, "/stop") === 0) { 
     // stop now 
    } else { 
     apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool')); 
    } 
    } else { 
    apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages')); 
    } 
} 


define('WEBHOOK_URL', 'https://my-site.example.com/secret-path-for-webhooks/'); 

if (php_sapi_name() == 'cli') { 
    // if run from console, set or delete webhook 
    apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL)); 
    exit; 
} 


$content = file_get_contents("php://input"); 
$update = json_decode($content, true); 

if (!$update) { 
    // receive wrong update, must not happen 
    exit; 
} 

if (isset($update["message"])) { 
    processMessage($update["message"]); 
} 
?> 
+0

Tôi đã đọc ở rất nhiều nơi vấn đề là giấy chứng nhận của tôi .. Khi tôi đã thử ví dụ này, nó hoạt động hoàn hảo. Cảm ơn bạn rất nhiều vì đã chỉ ra điều này. – ddz

-1

Điều này là do bạn không thiết lập các chứng như

curl -F "url=https://bot.sapamatech.com/tg" -F "[email protected]/etc/apache2/ssl/bot.pem" https://api.telegram.org/bot265033849:AAHAs6vKVlY7UyqWFUHoE7Toe2TsGvu0sf4/setWebhook 

Kiểm tra này link này về cách thiết Telegram Tự Signed

0

này có thể giúp người làm việc với SDK Laravel Telegram. Tôi gặp sự cố với webhook tự ký trong Laravel 5.3. Sau khi thiết lập và nhận kết quả OK từ Telegram với thông báo "Webhook đã được đặt", nó không hoạt động.
Sự cố liên quan đến xác minh CSRF.Vì vậy, tôi đã thêm url webhook vào các trường hợp ngoại lệ của CSRF và giờ đây mọi thứ hoạt động như một sự quyến rũ.

0

Hãy thử mã này. Nếu bạn có một SSL hợp lệ trên máy chủ web của bạn và bạn đã chạy đúng setWebhook, nó sẽ hoạt động (không cho tôi). Hãy chắc chắn rằng bạn tạo ra một tập tin gọi là "log.txt" và cung cấp cho quyền ghi với nó:

<?php 
define('BOT_TOKEN', '????'); 
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/'); 

// read incoming info and grab the chatID 
$content = file_get_contents("php://input"); 
$update  = json_decode($content, true); 
$chatID  = $update["message"]["chat"]["id"]; 
$message = $update["message"]["text"]; 

// compose reply 
$reply =""; 
switch ($message) { 
    case "/start": 
     $reply = "Welcome to Siamaks's bot. Type /help to see commands"; 
     break; 
    case "/test": 
     $reply = "test complete"; 
     break; 
    case "/hi": 
     $reply = "hey there"; 
     break; 
    case "/help": 
     $reply = "commands: /start , /test , /hi , /help "; 
     break; 
    default: 
     $reply = "NoNo, I don't understand you"; 
} 

// send reply 
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply; 
file_get_contents($sendto); 

// Create a debug log.txt to check the response/repy from Telegram in JSON format. 
// You can disable it by commenting checkJSON. 
checkJSON($chatID,$update); 
function checkJSON($chatID,$update){ 

    $myFile = "log.txt"; 
    $updateArray = print_r($update,TRUE); 
    $fh = fopen($myFile, 'a') or die("can't open file"); 
    fwrite($fh, $chatID ."nn"); 
    fwrite($fh, $updateArray."nn"); 
    fclose($fh); 
} 
1

Tôi có vấn đề này quá, sau khi bằng cách nào đó bức điện không chạy bot của tôi, vì vậy tôi cố gắng để làm mới giấy chứng nhận và thiết lập các móc nối web một lần nữa, nhưng một lần nữa nó không hoạt động, vì vậy tôi cập nhật VPS của tôi (cập nhật yum) và sau đó gia hạn chứng chỉ của tôi và thiết lập lại các móc nối web. sau khi nó bắt đầu hoạt động trở lại.

Các vấn đề liên quan