Telegram Bot API sendVideo 使用教程
## 1. sendVideo 方法用途介绍
sendVideo 是 Telegram Bot API 提供的一个核心方法,用于向指定聊天发送视频文件。
**主要用途:**
- 向用户、群组或频道发送视频文件
- 支持从 URL 或本地文件系统发送视频
- 可添加视频描述、设置缩略图、控制播放等
- 实现视频分享、媒体内容展示和视觉通知功能
**核心特点:**
- 支持 MP4、MKV 等常见视频格式
- 支持从 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 $videoUrl 视频 URL
* @param string|null $caption 视频标题
* @return array 响应结果
*/
function sendVideoFromUrl($botToken, $chatId, $videoUrl, $caption = null) {
$url = "https://api.telegram.org/bot{$botToken}/sendVideo";
$data = [
'chat_id' => $chatId,
'video' => $videoUrl
];
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
$videoUrl = "https://example.com/sample-video.mp4";
$caption = "这是一段测试视频";
$result = sendVideoFromUrl($botToken, $chatId, $videoUrl, $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 sendVideoFromFile($botToken, $chatId, $filePath, $caption = null) {
$url = "https://api.telegram.org/bot{$botToken}/sendVideo";
$data = [
'chat_id' => $chatId
];
if ($caption !== null) {
$data['caption'] = $caption;
}
// 准备文件上传
$files = [
'video' => 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-video.mp4"; // 本地视频文件路径
$caption = "这是一段本地测试视频";
$result = sendVideoFromFile($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 $video 视频 URL 或文件路径
* @param array $options 高级选项
* @return array 响应结果
*/
function sendVideoAdvanced($botToken, $chatId, $video, $options = []) {
$url = "https://api.telegram.org/bot{$botToken}/sendVideo";
$data = [
'chat_id' => $chatId
];
$files = [];
// 检查是 URL 还是本地文件
if (filter_var($video, FILTER_VALIDATE_URL)) {
$data['video'] = $video;
} else {
$files['video'] = new CURLFile(realpath($video));
}
// 处理缩略图
if (isset($options['thumbnail'])) {
if (filter_var($options['thumbnail'], FILTER_VALIDATE_URL)) {
$data['thumbnail'] = $options['thumbnail'];
} else {
$files['thumbnail'] = new CURLFile(realpath($options['thumbnail']));
}
unset($options['thumbnail']);
}
// 合并高级选项
$allowedOptions = [
'caption', 'parse_mode', 'caption_entities', 'width', 'height',
'duration', 'supports_streaming', '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);
}
// 使用示例 - 带缩略图和视频参数
$botToken = "YOUR_BOT_TOKEN";
$chatId = 123456789;
$videoUrl = "https://example.com/funny-video.mp4";
$result = sendVideoAdvanced(
$botToken,
$chatId,
$videoUrl,
[
'caption' => '*有趣的视频*\n这是一段带有 **Markdown** 格式的视频标题',
'parse_mode' => 'MarkdownV2',
'thumbnail' => 'https://example.com/video-thumbnail.jpg', // 视频缩略图
'width' => 1280, // 视频宽度
'height' => 720, // 视频高度
'duration' => 120, // 视频时长(秒)
'supports_streaming' => 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 TelegramVideoBot {
private $botToken;
/**
* 构造函数
* @param string $botToken Bot Token
*/
public function __construct($botToken) {
$this->botToken = $botToken;
}
/**
* 从 URL 发送视频
* @param int|string $chatId 聊天 ID
* @param string $videoUrl 视频 URL
* @param string|null $caption 视频标题
* @param array $options 其他选项
* @return array 响应结果
*/
public function sendVideoFromUrl($chatId, $videoUrl, $caption = null, $options = []) {
$params = $options;
if ($caption !== null) {
$params['caption'] = $caption;
}
return $this->sendVideo($chatId, $videoUrl, $params);
}
/**
* 从本地文件发送视频
* @param int|string $chatId 聊天 ID
* @param string $filePath 本地视频路径
* @param string|null $caption 视频标题
* @param array $options 其他选项
* @return array 响应结果
*/
public function sendVideoFromFile($chatId, $filePath, $caption = null, $options = []) {
$params = $options;
if ($caption !== null) {
$params['caption'] = $caption;
}
return $this->sendVideo($chatId, $filePath, $params);
}
/**
* 发送视频(通用方法)
* @param int|string $chatId 聊天 ID
* @param string $video 视频 URL 或本地路径
* @param array $options 选项
* @return array 响应结果
*/
public function sendVideo($chatId, $video, $options = []) {
$url = "https://api.telegram.org/bot{$this->botToken}/sendVideo";
$data = [
'chat_id' => $chatId
];
$files = [];
// 检查是 URL 还是本地文件
if (filter_var($video, FILTER_VALIDATE_URL)) {
$data['video'] = $video;
} else {
if (!file_exists($video)) {
return [
'ok' => false,
'error_code' => 404,
'description' => 'File not found: ' . $video
];
}
$files['video'] = new CURLFile(realpath($video));
}
// 处理缩略图
if (isset($options['thumbnail'])) {
if (filter_var($options['thumbnail'], FILTER_VALIDATE_URL)) {
$data['thumbnail'] = $options['thumbnail'];
} else {
if (!file_exists($options['thumbnail'])) {
return [
'ok' => false,
'error_code' => 404,
'description' => 'Thumbnail file not found: ' . $options['thumbnail']
];
}
$files['thumbnail'] = new CURLFile(realpath($options['thumbnail']));
}
unset($options['thumbnail']);
}
// 合并选项
$allowedOptions = [
'caption', 'parse_mode', 'caption_entities', 'width', 'height',
'duration', 'supports_streaming', '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, 60); // 视频上传可能需要更长时间
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 TelegramVideoBot($botToken);
$chatId = 123456789;
// 从 URL 发送简单视频
echo "发送简单视频...\n";
$result1 = $bot->sendVideoFromUrl($chatId, "https://example.com/simple.mp4", "简单视频");
if ($result1['ok']) {
echo "简单视频发送成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
echo "发送失败:" . $result1['description'] . "\n";
}
// 从本地文件发送带格式的视频
echo "\n发送本地带格式视频...\n";
$result2 = $bot->sendVideoFromFile(
$chatId,
"local-video.mp4",
"*精彩视频*\n这是一段 **高清** 视频,使用了 Markdown 格式",
[
'parse_mode' => 'MarkdownV2',
'thumbnail' => 'video-thumbnail.jpg',
'width' => 1920,
'height' => 1080,
'duration' => 180,
'supports_streaming' => true
]
);
if ($result2['ok']) {
echo "本地视频发送成功!\n";
} else {
echo "发送失败:" . $result2['description'] . "\n";
}
// 发送带保护内容的视频
echo "\n发送带保护内容的视频...\n";
$result3 = $bot->sendVideo(
$chatId,
"https://example.com/protected-video.mp4",
[
'caption' => '受保护的视频内容',
'protect_content' => true,
'disable_notification' => true
]
);
if ($result3['ok']) {
echo "受保护视频发送成功!\n";
} else {
echo "发送失败:" . $result3['description'] . "\n";
}
?>
```
2.6 注意事项
1. **视频要求:**
- 视频最大尺寸为 50MB
- 支持 MP4、MKV 等常见格式
- 对于 GIF 动图,建议使用 sendAnimation 方法
2. **缩略图要求:**
- 缩略图最大尺寸为 200KB
- 建议使用 JPG 格式
- 最佳尺寸为 320x320 像素
3. **文件路径:**
- 使用本地文件时,确保文件路径正确且 PHP 进程有读取权限
- 建议使用绝对路径或相对路径配合 __DIR__
4. **聊天 ID 格式:**
- 私人聊天 ID 是整数
- 群组和频道 ID 通常以 `-100` 开头的负数
5. **高级选项:**
- `supports_streaming` 对于长视频建议设置为 true
- `duration` 应与实际视频时长一致,否则可能影响播放体验
- `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-video.php
```

发表评论 取消回复