Telegram Bot中reply_parameters方法无法正常回复消息的求助
解决Telegram Bot中reply_parameters无法正常回复消息的问题
问题核心在于请求发送方式不正确:Telegram API处理包含嵌套结构的参数(比如reply_parameters)时,要求请求体为JSON格式,但你的sendRequest函数使用了http_build_query将数据编码为表单格式,这种方式无法正确传递嵌套数组参数。
解决方案
修改sendRequest函数,改为发送JSON格式的请求体,并设置对应的HTTP头:
- 将POST数据用
json_encode转为JSON字符串 - 添加
Content-Type: application/json请求头
修改后的完整代码
<?php //set Variables define('BOT_URL', 'https://api.telegram.org/bot'); define('BOT_TOKEN', ''); $url = BOT_URL . BOT_TOKEN; //Get updates $content = file_get_contents("php://input"); $update = json_decode($content, true); if (isset($update['message']['text'])) { $message = $update['message']['text']; $messageId = $update['message']['message_id']; $chat_id = $update['message']['chat']['id']; $threadId = $update['message']['message_thread_id']; $username = $update['message']['from']['username']; switch ($message) { case "/start": sendMessage($chat_id, $messageId, "Hi, {$username}", $threadId); } } function sendRequest($method, $arr = []) { global $url; $ch = curl_init(); $options = array( CURLOPT_URL => $url . $method, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => json_encode($arr), CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json' ] ); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); return $response; } function sendMessage($chat_id, $messageId, $message, $threadId) { global $url; $data = [ 'chat_id' => $chat_id, 'text' => $message, 'message_thread_id' => $threadId, 'reply_parameters' => [ 'message_id' => $messageId, 'chat_id' => $chat_id, ] ]; sendRequest('/sendMessage', $data); }
额外说明
reply_parameters中的chat_id如果和外层的chat_id一致,可以省略,只保留message_id即可- 之前
reply_to_message_id能正常工作,是因为它是单一参数,表单编码可以正确传递,而嵌套结构必须用JSON格式
内容的提问来源于stack exchange,提问作者user23521740
相关产品推荐
相关产品推荐

