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

如何用PHP实现Telegram Bot菜单按钮修改?求助

解决Telegram Bot菜单按钮修改无变化的问题

你的代码存在两个关键问题,导致接口返回成功但菜单按钮未生效:

1. MenuButton结构错误

Telegram API要求menu_button直接是对应类型的对象,不需要额外嵌套MenuButtonWebApp键。你的代码多了这一层嵌套,导致API无法正确解析按钮配置。

2. 请求方式与数据编码问题

用file_get_contents发送GET请求时,http_build_query处理嵌套数组会生成不符合API要求的参数格式。Telegram API更推荐用POST请求发送JSON格式的数据,确保结构能正确传递。

修正后的代码示例

<?php
$botToken = 'MYAPITOKEN';
$chatId = 'MYCHATID';
$webAppUrl = 'MYWEBSITE';

// 正确的menu_button结构
$data = [
    'chat_id' => $chatId,
    'menu_button' => [
        'type' => 'web_app',
        'text' => 'New Menu',
        'web_app' => [
            'url' => $webAppUrl
        ]
    ]
];

// 用POST请求发送JSON数据
$options = [
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/json',
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$response = file_get_contents("https://api.telegram.org/bot{$botToken}/setChatMenuButton", false, $context);

print_r($response);
?>

额外注意事项

  • 确保chat_id是正确的数字ID(个人用户ID可通过getUpdates接口获取,不要使用用户名)
  • web_app的URL必须使用HTTPS协议,且域名需符合Telegram的安全要求
  • 如果之前设置过菜单按钮,可先调用接口将其恢复为默认(menu_button设为['type' => 'default']),再重新设置新按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:08