You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:26