PHP定时任务:如何通过Telegram用户名而非chat_id发送私信
解决Telegram Bot通过用户名发送消息的问题
核心问题说明
Telegram Bot的sendMessage接口不支持直接使用用户名(@username)作为chat_id参数,必须传入用户的数字chat_id才能正常发送消息,这就是你用用户名调用时出现Bad Request: chat not found错误的原因。
解决方案:先通过用户名获取chat_id,再发送消息
你可以使用Telegram Bot API的getChat接口,通过用户名获取对应的chat_id,之后再用这个chat_id调用sendMessage接口发送消息。
1. 调用getChat接口获取chat_id
接口格式:
https://api.telegram.org/bot<MY_TOKEN>/getChat?chat_id=@username
(注:这里的chat_id参数可以带@符号,也可以直接传用户名)
返回的JSON数据中,result.id就是你需要的数字chat_id。
2. PHP代码示例
以下是完整的PHP实现逻辑,先获取chat_id再发送消息:
<?php $botToken = '你的BotToken'; $username = '目标用户名'; // 可以带@或不带 // 第一步:获取chat_id $getChatUrl = "https://api.telegram.org/bot{$botToken}/getChat?chat_id={$username}"; $response = file_get_contents($getChatUrl); $chatData = json_decode($response, true); if ($chatData['ok']) { $chatId = $chatData['result']['id']; // 第二步:发送消息 $sendMessageUrl = "https://api.telegram.org/bot{$botToken}/sendMessage?text=ok&chat_id={$chatId}"; $sendResponse = file_get_contents($sendMessageUrl); $sendResult = json_decode($sendResponse, true); if ($sendResult['ok']) { echo "消息发送成功"; } else { echo "发送失败:" . $sendResult['description']; } } else { echo "获取chat_id失败:" . $chatData['description']; } ?>
注意事项
- 确保目标用户已经和你的Bot发送过消息,否则
getChat接口会返回错误(你已经满足这个条件,可忽略)。 - 如果服务器禁用了
file_get_contents,可以改用curl实现HTTP请求,逻辑一致。
内容的提问来源于stack exchange,提问作者Frank Martin
相关产品推荐
相关产品推荐

