我希望我的机器人在我写/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);
}
现在的问题是它不起作用...怎么了?
更改
$tastiera = '&reply_markup={"inline_keyboard":
['.urlencode($tastierino).'],"resize_keyboard":true}';
自
$tastiera = '&reply_markup='.urlencode('{"inline_keyboard":
['.$tastierino.'],"resize_keyboard":true}');
您应该对整个 JSON 数据进行 URL 编码
您应该注意电报呼叫返回的结果。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 变得更加容易。