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

PHP/JS+cURL实现的Telegram机器人消息转发无限循环问题求助

Telegram机器人消息转发无限循环异常

问题概况

  • 技术实现:无框架,基于PHP+JS开发,通过cURL调用Telegram API,机器人绑定Webhook运行
  • 核心功能:仅将允许的user_id发送的转发消息,批量转发到机器人所在的目标群组
  • 异常现象:此前运行完全正常,近期偶发消息无限循环转发;测试小群组(2-5名成员)无异常,但活跃群组(约50个,单群规模10-200人)中会触发该问题
  • 排查动作:因怀疑代码逻辑问题或Telegram API结构更新,已从零重写三次代码,确认核心逻辑无错误

补充背景

曾使用带数据库配置的版本,包含允许用户列表管理、OpenAI驱动的新成员自动问候功能,当前简化版本仍出现相同异常。

核心代码

// 获取Telegram的Update负载
$update = json_decode(file_get_contents('php://input'), true);

// 检查是否存在Update且包含消息
if (isset($update['message'])) {
    // 检查发送者是否在允许的用户ID列表中
    if (in_array($update['message']['from']['id'], $allowedUserIds)) {
        // 判断是否为转发消息
        if(isset($update['message']['forward_date']) || isset($update['message']['forward_from'])) {
            // 将消息转发到目标群组
            $debug_message = forwardMessageToGroups($update['message'], $targetGroupIds);
            // 发送调试日志
            $args = [
                'chat_id' => $debug_chat_id,
                'text' => json_encode($debug_message, JSON_PRETTY_PRINT),
                'parse_mode' => 'HTML',
            ];
            cUrl('sendMessage', $args);
        }
    } else {
        // 记录未授权用户日志
        error_log('未授权用户ID: ' . $update['message']['from']['id']);
    }
}

function cUrl($action,$args = false) {

    global $telegram_url, $botToken;

    $full_url = $telegram_url . $botToken . '/' . $action;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $full_url);
    if($args) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
    }

    $res = curl_exec($ch);

    if (curl_error($ch)) {
        $result['error'] = curl_error($ch);
    } else {
        $result['success'] = json_decode($res);
    }

    curl_close($ch);

    // var_dump($result);
    // return $result;

}

内容的提问来源于stack exchange,提问作者marcushorndt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:24:58