2015-10-23 26 views
17

Perché il mio webhook non funziona? Non ottengo alcun dato dall'API del bot del telegramma. Ecco la spiegazione dettagliata del mio problema:Hai problemi con il webhook per l'API Bot di Telegram

ho ottenuto CERT dello SSL da StartSSL, funziona benissimo sul mio sito (secondo GeoCerts SSL checker), ma sembra ancora come il mio webhook al telegramma Bot API non funziona (nonostante dice che il webhook è stato impostato, non ho ricevuto alcun dato).

Sto facendo un webhook per il mio script sul mio sito in questa forma:

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

ottengo questo testo in risposta:

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

Così deve essere di lavoro, ma in realtà doesn 't.

Ecco il mio codice script:

<?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); 
} 

?> 

Io in realtà non ricevono alcun dato a $ aggiornamento. Quindi il webhook non funziona. Perché?

+1

Forse correlato a non ottenere alcun dato, dovresti fare 'json_decode ($ update, true)' per ottenere i dati come array, piuttosto che come 'stdClass'. – ixchi

+0

ixchi, 'json_decode ($ update, true)' non ha modificato nulla, ancora non funziona: \ – markelov

+0

Sei sicuro di ricevere effettivamente il webhook? Funziona correttamente per me. – ixchi

risposta

3

Ho avuto problemi simili. Ora risolto. Il problema è probabilmente in un certificato pubblico errato. Si prega di seguire le istruzioni di attenzione propongo nel mio progetto:

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 non controlla i dati all'interno del vostro certificato digitale autofirmato, tornando "ok", anche se per esempio si fa non specificare un CN valido /! Quindi fai attenzione a generare un certificato .pem pubblico contenente /CN = tuo_dominio corrispondente al tuo nome di dominio REAL HOST!

4

Ero con questo problema. Stavo cercando di cercare ovunque e non riuscivo a trovare la soluzione per il mio problema, perché le persone dicevano sempre che il problema era il certificato SSL. Ma ho trovato il problema, e c'erano molte cose che mancavano nel codice per interagire con il webhook dell'API telegramma che avvolgeva il ricciolo e questo genere di cose. Dopo aver esaminato un esempio nella documentazione del bot del telegramma, ho risolto il mio problema. Guardate questo esempio 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

Ho letto in così tanti posti che il problema era il mio certificato. Quando ho provato questo esempio, ha funzionato perfettamente. Grazie mille per averlo indicato. – ddz

-1

Questo è perché non sta impostando il certificato come questo

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

Scegli questa link su come impostare telegramma certificato autofirmato

0

Questo può aiutare chi lavora con Laravel Telegram SDK. Ho avuto un problema con il webhook autofirmato in Laravel 5.3. Dopo l'installazione e il risultato OK da Telegram con il messaggio "Webhook è stato impostato", non ha funzionato.
Il problema era correlato alla verifica CSRF.Quindi ho aggiunto l'URL del webhook alle eccezioni CSRF e ora tutto funziona come un incantesimo.

0

Prova questo codice. Se hai un SSL valido sul tuo host web e hai eseguito correttamente il setWebhook, dovrebbe funzionare (fa per me). Assicurarsi che si crea un file chiamato "log.txt" e dare il permesso di scrittura ad esso:

<?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

ho avuto anche questo problema, dopo aver in qualche modo il telegramma non ha funzionato il mio bot, così ho cercato di rinnovare il certificato e impostare di nuovo il web hook, ma di nuovo non ha funzionato, quindi ho aggiornato il mio VPS (aggiornamento yum), quindi ho rinnovato il mio certificato e ho impostato di nuovo i web hook. dopo questi ha iniziato a funzionare di nuovo.

Problemi correlati