У вас есть проблемы с webhook в Telegram Bot API

Почему мой webhook не работает? Я не получаю никаких данных из API телеграмм бота. Вот подробное объяснение моей проблемы:

Я получил сертификат SSL от StartSSL, он отлично работает на моем сайте (согласно GeoCerts SSL checker) но по-прежнему кажется, что мой webhook для Telegram Bot API не работает (несмотря на то, что он говорит, что установлен веб-хост, я не получаю никаких данных).

Я создаю webhook для своего script на своем веб-сайте в этой форме:

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

Я получаю этот текст в ответ:

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

Поэтому он должен работать, но на самом деле этого не делает.

Вот мой код 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);
}

?>

Фактически я не получаю никаких данных для обновления $. Так что webhook не работает. Почему?

Ответы

Ответ 1

У меня была эта проблема. Я пытался повсюду искать и не мог найти решение проблемы, потому что люди все время говорили, что проблема связана с сертификатом SSL. Но я нашел проблему, и в коде было много чего не хватает, чтобы взаимодействовать с веб-браузером API телеграмм, включающим завиток и подобные вещи. После того, как я посмотрел в примере в документации телеграммы бота, я решил свою проблему. Посмотрите этот пример 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"]);
}
?>

Ответ 2

У меня была аналогичная проблема. Теперь решено. Возможно, проблема связана с неправильным публичным сертификатом. Пожалуйста, следуйте инструкциям с вниманием, которые я предлагаю в своем проекте:

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 не проверяет данные в вашем самозаверяющем цифровом сертификате, возвращая "ok", даже если на примере вы не указываете действительный /CN! Поэтому будьте осторожны, чтобы создать общедоступный сертификат .pem, содержащий /CN = your_domain, соответствующий вашему доменному имени REAL HOST!

Ответ 4

У меня тоже была эта проблема, так как телеграмма не запускала моего бота, поэтому я снова попытался обновить сертификат и снова установить веб-крючки, но опять-таки это не сработало, поэтому я обновил VPS (yum update) а затем возобновить мой сертификат и снова установить веб-крючки. после этого он снова начал работать.

Ответ 5

Это может помочь тому, кто работает с SDK Laravel Telegram. У меня была проблема с самозаверяющим webhook в Laravel 5.3. После настройки и получения OK результата Telegram с сообщением "Webhook был установлен", это не сработало.
Проблема была связана с проверкой CSRF. Поэтому я добавил URL-адрес webhook к исключениям CSRF, и теперь все работает как прелесть.

Ответ 6

Попробуйте этот код. Если у вас есть действующий SSL на вашем веб-хостинге, и вы правильно запустили setWebhook, он должен работать (для меня). Убедитесь, что вы создали файл с именем "log.txt" и предоставили ему разрешение на запись:

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

Ответ 7

Это связано с тем, что вы не устанавливаете этот сертификат как

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

Проверьте ссылку о том, как установить самоподписанный сертификат Telegram