如何识别对应不同Telegram机器人的Webhook请求?
如何区分同一Webhook(或不同)下的Telegram机器人请求
嘿,这个问题我刚好踩过坑,给你几个实用的方案,轻松搞定不同机器人的请求识别:
方案1:给每个机器人分配专属的Webhook路径(最推荐)
这是最直观也最容易维护的方式——给每个机器人设置不同的Webhook URL路径,比如:
- 机器人1:
https://your-domain.com/webhook/bot1 - 机器人2:
https://your-domain.com/webhook/bot2 - 机器人3:
https://your-domain.com/webhook/bot3
然后在PHP代码里,通过请求的URI来判断当前属于哪个机器人:
// 获取当前请求的路径 $requestPath = $_SERVER['REQUEST_URI']; // 定义机器人token和路径的对应关系 $botConfigs = [ '/webhook/bot1' => 'YOUR_BOT1_TOKEN', '/webhook/bot2' => 'YOUR_BOT2_TOKEN', '/webhook/bot3' => 'YOUR_BOT3_TOKEN', ]; // 匹配对应的机器人 $currentBotToken = null; foreach ($botConfigs as $path => $token) { if (strpos($requestPath, $path) === 0) { $currentBotToken = $token; break; } } if ($currentBotToken) { // 继续处理该机器人的update逻辑 $content = file_get_contents("php://input"); $update = json_decode($content, true); // ... 你的业务代码 } else { // 无效请求,直接返回 http_response_code(404); exit; }
方案2:用Secret Token区分(适合必须共用同一URL的场景)
如果你的业务场景要求所有机器人共用同一个Webhook URL,那可以利用Telegram Webhook的secret_token参数:
- 设置Webhook时,给每个机器人指定不同的secret token,比如机器人1用
my-secret-bot-1,机器人2用my-secret-bot-2 - 接收请求时,读取请求头里的
X-Telegram-Bot-Api-Secret-Token,匹配对应的机器人
代码示例:
// 获取请求头中的secret token $receivedSecret = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? ''; // 定义secret和机器人token的对应关系 $botSecrets = [ 'my-secret-bot-1' => 'YOUR_BOT1_TOKEN', 'my-secret-bot-2' => 'YOUR_BOT2_TOKEN', 'my-secret-bot-3' => 'YOUR_BOT3_TOKEN', ]; if (isset($botSecrets[$receivedSecret])) { $currentBotToken = $botSecrets[$receivedSecret]; // 处理该机器人的请求 $content = file_get_contents("php://input"); $update = json_decode($content, true); // ... 你的业务代码 } else { // 验证失败,拒绝请求 http_response_code(403); exit; }
注意事项
- 不要尝试从
update数据本身直接识别机器人——Telegram的update里不会携带机器人自身的ID或标识,所以这条路走不通 - 方案1的扩展性更好,后续新增机器人只需要加新的路径和配置即可,不会影响现有逻辑
内容的提问来源于stack exchange,提问作者user9614762
相关产品推荐
相关产品推荐

