簡體   English   中英

內聯鍵盤 Telegram bot [PHP]

[英]Inline keyboard Telegram bot [PHP]

我希望我的機器人在我寫 /orario 時他用內聯鍵盤回答我。

所以..我以這種方式為我的鍵盤創建了一個數組:

$tastierino_giorno = '[{"text":"Testo","callback_data":"StampaMessaggio"}]';

在另一個函數中我這樣寫:

function tastieraInline($chatid, $tastierino)
{
    global $token;
    $messaggio = "Scegli per che giorno inviare il messaggio:";
    $tastiera = '&reply_markup={"inline_keyboard": 
  ['.urlencode($tastierino).'],"resize_keyboard":true}';
    $url = "https://api.telegram.org/$token/sendMessage?chat_id=$chatId&parse_mode=HTML&text=".urlencode($messaggio).$tastiera;

    file_get_contents($url);

}

在此之后,使用 if,我檢查用戶是否寫入了“/orario”。

} elseif($message == "/orario"){
        tastieraInline($chatid, $tastierino_giorno); 
}

現在的問題是它不起作用......有什么問題?

您應該注意電報調用返回的結果。 file_get_contents非常適合讓某些事情快速運行但不返回任何錯誤信息。

您應該使用 curl 或像guzzle這樣的庫。 卷曲的一個例子:

$ch = curl_init( $url );
if ( $ch == FALSE )
{
  error_log( "Error initialising curl" );
  return FALSE;
}

curl_setopt( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_POST, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_FORBID_REUSE, 1 );
// Set TCP timeout to 30 seconds
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Connection: Close' ) );

$result = curl_exec( $ch );
$error = curl_errno( $ch );
$errorStr = curl_error( $ch );
curl_close( $ch );
if ( $error != 0 )
{
  return array( $errorStr, $result );
}
return $result;

如果您不介意安裝額外的庫,Guzzle 會簡單得多。

希望這能讓您從失敗的電報調用中獲取錯誤字符串。

到你的實際問題。 您應該使用json_encode而不是附加字符串為鍵盤標記創建 json。 http_build_query使構建 URL 變得更加容易。

改變

$tastiera = '&reply_markup={"inline_keyboard": 
  ['.urlencode($tastierino).'],"resize_keyboard":true}';

$tastiera = '&reply_markup='.urlencode('{"inline_keyboard": 
  ['.$tastierino.'],"resize_keyboard":true}');

你應該對整個 JSON 數據進行 URL 編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM