Telegram Bot API sendPhoto 使用教程
## 1. sendPhoto 方法用途介绍
sendPhoto 是 Telegram Bot API 提供的一个核心方法,用于向指定聊天发送照片。
**主要用途:**
- 向用户、群组或频道发送单张照片
- 支持从 URL 或本地文件系统发送照片
- 可添加照片描述、回复到特定消息等
- 实现图片分享、视觉内容展示和通知功能
**核心特点:**
- 支持 JPG、PNG、GIF 等常见图片格式
- 支持从 URL 发送或上传本地文件
- 可设置照片标题(caption)并支持 Markdown 或 HTML 格式
- 支持回复到聊天中的特定消息
- 可选择禁用通知和保护内容
- 支持发送到 Direct Messages 聊天主题
## 2. 原生 PHP 调用实例


### 2.1 准备工作
确保你的 PHP 环境满足以下要求:
- PHP 5.6 或更高版本
- 已安装 cURL 扩展
- 已创建 Telegram Bot 并获取 Bot Token
### 2.2 从 URL 发送照片
```php
<?php
/**
* 使用 Telegram Bot API 从 URL 发送照片
* @param string $botToken Bot Token
* @param int|string $chatId 聊天 ID
* @param string $photoUrl 照片 URL
* @param string|null $caption 照片标题
* @return array 响应结果
*/
function sendPhotoFromUrl($botToken, $chatId, $photoUrl, $caption = null) {
$url = "https://api.telegram.org/bot{$botToken}/sendPhoto";
$data = [
'chat_id' => $chatId,
'photo' => $photoUrl
];
if ($caption !== null) {
$data['caption'] = $caption;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 使用示例
$botToken = "YOUR_BOT_TOKEN";
$chatId = 123456789; // 用户或群组的聊天 ID
$photoUrl = "https://example.com/photo.jpg";
$caption = "这是一张测试照片";
$result = sendPhotoFromUrl($botToken, $chatId, $photoUrl, $caption);
if ($result['ok']) {
echo "照片发送成功!消息 ID: " . $result['result']['message_id'];
} else {
echo "发送失败:" . $result['description'];
}
?>
```
### 2.3 从本地文件发送照片
```php
<?php
/**
* 使用 Telegram Bot API 从本地文件发送照片
* @param string $botToken Bot Token
* @param int|string $chatId 聊天 ID
* @param string $filePath 本地照片文件路径
* @param string|null $caption 照片标题
* @return array 响应结果
*/
function sendPhotoFromFile($botToken, $chatId, $filePath, $caption = null) {
$url = "https://api.telegram.org/bot{$botToken}/sendPhoto";
$data = [
'chat_id' => $chatId
];
if ($caption !== null) {
$data['caption'] = $caption;
}
// 准备文件上传
$files = [
'photo' => new CURLFile(realpath($filePath))
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array_merge($data, $files));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 使用示例
$botToken = "YOUR_BOT_TOKEN";
$chatId = 123456789;
$filePath = "local-photo.jpg"; // 本地照片文件路径
$caption = "这是一张本地测试照片";
$result = sendPhotoFromFile($botToken, $chatId, $filePath, $caption);
if ($result['ok']) {
echo "本地照片发送成功!";
} else {
echo "发送失败:" . $result['description'];
}
?>
```
### 2.4 带高级选项的照片发送
```php
<?php
/**
* 使用 Telegram Bot API 发送照片(带高级选项)
* @param string $botToken Bot Token
* @param int|string $chatId 聊天 ID
* @param string $photo 照片 URL 或文件路径
* @param array $options 高级选项
* @return array 响应结果
*/
function sendPhotoAdvanced($botToken, $chatId, $photo, $options = []) {
$url = "https://api.telegram.org/bot{$botToken}/sendPhoto";
$data = [
'chat_id' => $chatId
];
$files = [];
// 检查是 URL 还是本地文件
if (filter_var($photo, FILTER_VALIDATE_URL)) {
$data['photo'] = $photo;
} else {
$files['photo'] = new CURLFile(realpath($photo));
}
// 合并高级选项
$allowedOptions = [
'caption', 'parse_mode', 'caption_entities', 'disable_notification',
'protect_content', 'reply_to_message_id', 'allow_sending_without_reply',
'reply_markup', 'direct_messages_topic_id', 'suggested_post_parameters'
];
foreach ($allowedOptions as $option) {
if (isset($options[$option])) {
$data[$option] = $options[$option];
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, empty($files) ? $data : array_merge($data, $files));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 使用示例 - 带 Markdown 标题和回复功能
$botToken = "YOUR_BOT_TOKEN";
$chatId = 123456789;
$photoUrl = "https://example.com/beautiful-photo.jpg";
$result = sendPhotoAdvanced(
$botToken,
$chatId,
$photoUrl,
[
'caption' => '*美丽的风景*\n这是一张带有 **Markdown** 格式的照片标题',
'parse_mode' => 'MarkdownV2',
'reply_to_message_id' => 12345, // 回复到聊天中的特定消息
'disable_notification' => true, // 禁用通知
'protect_content' => true, // 保护内容(防止转发/保存)
'direct_messages_topic_id' => 67890 // Direct Messages 聊天主题 ID
]
);
if ($result['ok']) {
echo "高级照片发送成功!";
} else {
echo "发送失败:" . $result['description'];
}
?>
```
### 2.5 完整的 Telegram Bot 照片发送类
```php
<?php
class TelegramPhotoBot {
private $botToken;
/**
* 构造函数
* @param string $botToken Bot Token
*/
public function __construct($botToken) {
$this->botToken = $botToken;
}
/**
* 从 URL 发送照片
* @param int|string $chatId 聊天 ID
* @param string $photoUrl 照片 URL
* @param string|null $caption 照片标题
* @param array $options 其他选项
* @return array 响应结果
*/
public function sendPhotoFromUrl($chatId, $photoUrl, $caption = null, $options = []) {
$params = $options;
if ($caption !== null) {
$params['caption'] = $caption;
}
return $this->sendPhoto($chatId, $photoUrl, $params);
}
/**
* 从本地文件发送照片
* @param int|string $chatId 聊天 ID
* @param string $filePath 本地照片路径
* @param string|null $caption 照片标题
* @param array $options 其他选项
* @return array 响应结果
*/
public function sendPhotoFromFile($chatId, $filePath, $caption = null, $options = []) {
$params = $options;
if ($caption !== null) {
$params['caption'] = $caption;
}
return $this->sendPhoto($chatId, $filePath, $params);
}
/**
* 发送照片(通用方法)
* @param int|string $chatId 聊天 ID
* @param string $photo 照片 URL 或本地路径
* @param array $options 选项
* @return array 响应结果
*/
public function sendPhoto($chatId, $photo, $options = []) {
$url = "https://api.telegram.org/bot{$this->botToken}/sendPhoto";
$data = [
'chat_id' => $chatId
];
$files = [];
// 检查是 URL 还是本地文件
if (filter_var($photo, FILTER_VALIDATE_URL)) {
$data['photo'] = $photo;
} else {
if (!file_exists($photo)) {
return [
'ok' => false,
'error_code' => 404,
'description' => 'File not found: ' . $photo
];
}
$files['photo'] = new CURLFile(realpath($photo));
}
// 合并选项
$allowedOptions = [
'caption', 'parse_mode', 'caption_entities', 'disable_notification',
'protect_content', 'reply_to_message_id', 'allow_sending_without_reply',
'reply_markup', 'direct_messages_topic_id', 'suggested_post_parameters'
];
foreach ($allowedOptions as $option) {
if (isset($options[$option])) {
$data[$option] = $options[$option];
}
}
return $this->sendRequest($url, $data, $files);
}
/**
* 发送 HTTP 请求
* @param string $url 请求 URL
* @param array $data 请求数据
* @param array $files 文件数据
* @return array 响应结果
*/
private function sendRequest($url, $data, $files = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
// 合并数据和文件
$postFields = empty($files) ? $data : array_merge($data, $files);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
return [
'ok' => false,
'error_code' => $httpCode,
'description' => 'cURL 错误: ' . $error
];
}
curl_close($ch);
return json_decode($response, true);
}
/**
* 获取更新
* @param int|null $offset 更新偏移量
* @param int|null $limit 更新数量
* @return array 响应结果
*/
public function getUpdates($offset = null, $limit = null) {
$url = "https://api.telegram.org/bot{$this->botToken}/getUpdates";
$data = [];
if ($offset !== null) $data['offset'] = $offset;
if ($limit !== null) $data['limit'] = $limit;
return $this->sendRequest($url, $data);
}
}
// 使用示例
$botToken = "YOUR_BOT_TOKEN";
$bot = new TelegramPhotoBot($botToken);
$chatId = 123456789;
// 从 URL 发送简单照片
echo "发送简单照片...\n";
$result1 = $bot->sendPhotoFromUrl($chatId, "https://example.com/simple.jpg", "简单照片");
if ($result1['ok']) {
echo "简单照片发送成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
echo "发送失败:" . $result1['description'] . "\n";
}
// 从本地文件发送带格式的照片
echo "\n发送本地带格式照片...\n";
$result2 = $bot->sendPhotoFromFile(
$chatId,
"local-image.jpg",
"*本地照片标题*\n这是一张 **本地** 照片,使用了 Markdown 格式",
[
'parse_mode' => 'MarkdownV2',
'protect_content' => true
]
);
if ($result2['ok']) {
echo "本地照片发送成功!\n";
} else {
echo "发送失败:" . $result2['description'] . "\n";
}
// 发送带回复的照片
echo "\n发送带回复的照片...\n";
$result3 = $bot->sendPhoto(
$chatId,
"https://example.com/reply.jpg",
[
'caption' => '这是对之前消息的回复',
'reply_to_message_id' => 12345,
'disable_notification' => true
]
);
if ($result3['ok']) {
echo "带回复的照片发送成功!\n";
} else {
echo "发送失败:" . $result3['description'] . "\n";
}
?>
```
2.5 注意事项
1. **照片要求:**
- 照片最大尺寸为 10MB
- 支持 JPG、PNG、GIF 等格式
- 对于 GIF 动图,建议使用 sendAnimation 方法
2. **文件路径:**
- 使用本地文件时,确保文件路径正确且 PHP 进程有读取权限
- 建议使用绝对路径或相对路径配合 __DIR__
3. **聊天 ID 格式:**
- 私人聊天 ID 是整数
- 群组和频道 ID 通常以 `-100` 开头的负数
4. **权限要求:**
- 机器人必须在目标聊天中具有发送消息的权限
- 对于私有频道,机器人需要是管理员
5. **高级选项:**
- `parse_mode` 支持 MarkdownV2、HTML 和 Markdown
- `protect_content` 可防止照片被转发或保存
- `direct_messages_topic_id` 用于将照片发送到 Direct Messages 聊天主题
## 3. 应用场景
- **图片分享:** 分享新闻图片、产品图片等
- **视觉通知:** 发送警报、状态变化的可视化通知
- **内容展示:** 展示产品目录、相册等
- **用户交互:** 发送验证码图片、验证信息等
## 4. 运行指南
1. 将以上代码保存为 `.php` 文件
2. 替换 `YOUR_BOT_TOKEN` 为你的实际 Bot Token
3. 替换聊天 ID 和照片 URL/路径为实际值
4. 在命令行或浏览器中运行 PHP 文件
```bash
php telegram-send-photo.php

发表评论 取消回复