当前位置: 动力学知识库 > 问答 > 编程问答 >

PHP WebHook Telegram Bot - SSL CloudFlare

问题描述:

after several researches on the forum I decided to write to see if you can help me.

I want to create a bot telegram in PHP for educational purposes.

I read its documentation, I created a Flexible SSL certificate on CloudFlare for my domain.

I created my bot by telegram and received the token, and set my webhook with the following code

https://api.telegram.org/bot <my token>? url = https: //miodominio.eu/page.php

the answer is :

{"Ok": true, "result": false, "description": "Webhook was set"}

I put this code in my page.php

<?php

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 ."\n\n");

fwrite($fh, $updateArray."\n\n");

fclose($fh);

}

function sendMessage()

{

$message = "I am a baby bot.";

return $message;

}

define('BOT_TOKEN', '< mio 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"];

// compose reply

$reply = sendMessage();

// send reply

$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;

file_get_contents($sendto);

checkJSON($chatID,$update);

?>

But nothing, if I write to boot I do not receive any answer and the log file is not entered anything.

how can I debug?

Do you have any recommendations??

thanks to all in advance

网友答案:

Use This code and replace your API:

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


 $params = array( 
 'chat_id'   => $content["message"]["chat"]["id"],  
 'action'     => 'typing'   
 );
$api="123";
$url = 'https://api.telegram.org/bot'.$api."/sendChatAction";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_POST,1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
   curl_setopt($ch, CURLOPT_URL,$url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
   enter code herecurl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
   $result=curl_exec ($ch); 
网友答案:

I am not sure this solves your problem, but I find two problems with your code.

To set a webhook, your PHP string should be:

'https://api.telegram.org/bot<token>/setWebhook?url='.urlencode('https://miodominio.eu/page.php');

To send a message, your PHP string should be:

API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($reply)

For any non-trivial parameters, you should always urlencode() them before adding them to the query string.

Hope it helps.

分享给朋友:
您可能感兴趣的文章:
随机阅读: