PHP开发Telegram机器人:如何转发用户发送的图片?
解决Telegram机器人无法转发带文本图片的问题
你的问题核心在于两个点:
sendMessage接口仅支持纯文本发送,无法处理图片内容;- 使用
sendPhoto时,没有正确获取图片的file_id,且请求方式或参数构造有误。
正确处理流程
用户发送带文本的图片消息时,Telegram推送的更新数据里,图片信息会放在message->photo数组中(数组元素按分辨率从低到高排列,通常取最后一个元素的file_id),附带的文本则在message->caption字段。
实现代码示例
方式1:使用cURL发送POST请求(推荐,更稳定)
<?php // 从Telegram的Webhook更新中获取数据 $update = json_decode(file_get_contents('php://input'), true); $chatID = $update['message']['chat']['id']; // 判断是否为图片消息 if (isset($update['message']['photo'])) { // 获取最高分辨率图片的file_id $photo = end($update['message']['photo']); $photoFileId = $photo['file_id']; // 获取附带的文本说明 $caption = isset($update['message']['caption']) ? $update['message']['caption'] : ''; $botToken = '你的机器人Token'; $apiUrl = "https://api.telegram.org/bot{$botToken}/sendPhoto"; // 构造POST参数 $postData = [ 'chat_id' => $chatID, 'photo' => $photoFileId, 'caption' => $caption ]; // 初始化cURL $ch = curl_init($apiUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行请求并获取响应 $response = curl_exec($ch); curl_close($ch); // 调试用:打印API返回结果 // var_dump($response); } ?>
方式2:使用file_get_contents发送POST请求
<?php $update = json_decode(file_get_contents('php://input'), true); $chatID = $update['message']['chat']['id']; if (isset($update['message']['photo'])) { $photo = end($update['message']['photo']); $photoFileId = $photo['file_id']; $caption = isset($update['message']['caption']) ? $update['message']['caption'] : ''; $botToken = '你的机器人Token'; $apiUrl = "https://api.telegram.org/bot{$botToken}/sendPhoto"; $postData = http_build_query([ 'chat_id' => $chatID, 'photo' => $photoFileId, 'caption' => $caption ]); $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => $postData ] ]); $response = file_get_contents($apiUrl, false, $context); // var_dump($response); } ?>
关键注意事项
- 必须使用POST请求调用
sendPhoto接口,GET请求无法处理复杂参数且有长度限制; - 转发图片时直接使用原消息中的
file_id即可,无需重新上传图片; - 若需要处理其他类型的媒体(如视频、文档),逻辑类似,对应使用
sendVideo、sendDocument等接口。
内容的提问来源于stack exchange,提问作者sudhakar singh
相关产品推荐
相关产品推荐

