Telegram Bot API sendDocument 使用教程

## 1. sendDocument 方法用途介绍

sendDocument 是 Telegram Bot API 提供的一个核心方法,用于向指定聊天发送各种类型的文档文件。

**主要用途:**
- 向用户、群组或频道发送各种格式的文档文件
- 支持从 URL 或本地文件系统发送文档
- 可添加文档描述、回复到特定消息等
- 实现文件分享、文档传输和内容分发功能

**核心特点:**
- 支持几乎所有文档格式(PDF、DOCX、ZIP、MP4等)
- 支持从 URL 发送或上传本地文件
- 可设置文档标题(caption)并支持 Markdown 或 HTML 格式
- 支持回复到聊天中的特定消息
- 可选择禁用通知和保护内容
- 支持发送到 Direct Messages 聊天主题
- 支持设置缩略图(thumbnail)

## 2. 原生 PHP 调用实例

### 2.1 准备工作

确保你的 PHP 环境满足以下要求:
- PHP 5.6 或更高版本
- 已安装 cURL 扩展
- 已创建 Telegram Bot 并获取 Bot Token

### 2.2 从 URL 发送文档
<?php
/**
 * 使用 Telegram Bot API 从 URL 发送文档
 * @param string $botToken Bot Token
 * @param int|string $chatId 聊天 ID
 * @param string $documentUrl 文档 URL
 * @param string|null $caption 文档标题
 * @return array 响应结果
 */
function sendDocumentFromUrl($botToken, $chatId, $documentUrl, $caption = null) {
    $url = "https://api.telegram.org/bot{$botToken}/sendDocument";
    
    $data = [
        'chat_id' => $chatId,
        'document' => $documentUrl
    ];
    
    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
$documentUrl = "https://example.com/document.pdf";
$caption = "这是一份测试文档";

$result = sendDocumentFromUrl($botToken, $chatId, $documentUrl, $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 sendDocumentFromFile($botToken, $chatId, $filePath, $caption = null) {
    $url = "https://api.telegram.org/bot{$botToken}/sendDocument";
    
    $data = [
        'chat_id' => $chatId
    ];
    
    if ($caption !== null) {
        $data['caption'] = $caption;
    }
    
    // 准备文件上传
    $files = [
        'document' => 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-document.pdf"; // 本地文档文件路径
$caption = "这是一份本地测试文档";

$result = sendDocumentFromFile($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 $document 文档 URL 或文件路径
 * @param array $options 高级选项
 * @return array 响应结果
 */
function sendDocumentAdvanced($botToken, $chatId, $document, $options = []) {
    $url = "https://api.telegram.org/bot{$botToken}/sendDocument";
    
    $data = [
        'chat_id' => $chatId
    ];
    
    $files = [];
    
    // 检查是 URL 还是本地文件
    if (filter_var($document, FILTER_VALIDATE_URL)) {
        $data['document'] = $document;
    } else {
        $files['document'] = new CURLFile(realpath($document));
    }
    
    // 处理缩略图
    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', 'disable_content_type_detection',
        '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;
$documentUrl = "https://example.com/report.pdf";

$result = sendDocumentAdvanced(
    $botToken,
    $chatId,
    $documentUrl,
    [
        'caption' => '*月度报告*\n这是一份 **2024年5月** 的销售报告',
        'parse_mode' => 'MarkdownV2',
        'thumbnail' => 'https://example.com/thumbnail.jpg', // 文档缩略图
        'disable_content_type_detection' => 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 TelegramDocumentBot {
    private $botToken;
    
    /**
     * 构造函数
     * @param string $botToken Bot Token
     */
    public function __construct($botToken) {
        $this->botToken = $botToken;
    }
    
    /**
     * 从 URL 发送文档
     * @param int|string $chatId 聊天 ID
     * @param string $documentUrl 文档 URL
     * @param string|null $caption 文档标题
     * @param array $options 其他选项
     * @return array 响应结果
     */
    public function sendDocumentFromUrl($chatId, $documentUrl, $caption = null, $options = []) {
        $params = $options;
        if ($caption !== null) {
            $params['caption'] = $caption;
        }
        
        return $this->sendDocument($chatId, $documentUrl, $params);
    }
    
    /**
     * 从本地文件发送文档
     * @param int|string $chatId 聊天 ID
     * @param string $filePath 本地文档路径
     * @param string|null $caption 文档标题
     * @param array $options 其他选项
     * @return array 响应结果
     */
    public function sendDocumentFromFile($chatId, $filePath, $caption = null, $options = []) {
        $params = $options;
        if ($caption !== null) {
            $params['caption'] = $caption;
        }
        
        return $this->sendDocument($chatId, $filePath, $params);
    }
    
    /**
     * 发送文档(通用方法)
     * @param int|string $chatId 聊天 ID
     * @param string $document 文档 URL 或本地路径
     * @param array $options 选项
     * @return array 响应结果
     */
    public function sendDocument($chatId, $document, $options = []) {
        $url = "https://api.telegram.org/bot{$this->botToken}/sendDocument";
        
        $data = [
            'chat_id' => $chatId
        ];
        
        $files = [];
        
        // 检查是 URL 还是本地文件
        if (filter_var($document, FILTER_VALIDATE_URL)) {
            $data['document'] = $document;
        } else {
            if (!file_exists($document)) {
                return [
                    'ok' => false,
                    'error_code' => 404,
                    'description' => 'File not found: ' . $document
                ];
            }
            $files['document'] = new CURLFile(realpath($document));
        }
        
        // 处理缩略图
        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', 'disable_content_type_detection',
            '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 TelegramDocumentBot($botToken);
$chatId = 123456789;

// 从 URL 发送简单文档
echo "发送简单文档...\n";
$result1 = $bot->sendDocumentFromUrl($chatId, "https://example.com/document.pdf", "简单文档");
if ($result1['ok']) {
    echo "简单文档发送成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
    echo "发送失败:" . $result1['description'] . "\n";
}

// 从本地文件发送带格式的文档
echo "\n发送本地带格式文档...\n";
$result2 = $bot->sendDocumentFromFile(
    $chatId,
    "local-report.docx",
    "*2024年销售报告*\n这是一份 **详细** 的年度销售报告,使用了 Markdown 格式",
    [
        'parse_mode' => 'MarkdownV2',
        'thumbnail' => 'report-thumbnail.jpg',
        'protect_content' => true
    ]
);

if ($result2['ok']) {
    echo "本地文档发送成功!\n";
} else {
    echo "发送失败:" . $result2['description'] . "\n";
}

// 发送带禁用内容类型检测的文档
echo "\n发送带高级选项的文档...\n";
$result3 = $bot->sendDocument(
    $chatId,
    "https://example.com/special-file.bin",
    [
        'caption' => '特殊二进制文件',
        'disable_content_type_detection' => true,
        'disable_notification' => true
    ]
);

if ($result3['ok']) {
    echo "高级文档发送成功!\n";
} else {
    echo "发送失败:" . $result3['description'] . "\n";
}
?>
```



2.6 注意事项

1. **文档要求:**
   - 文档最大尺寸为 50MB
   - 支持几乎所有文档格式(PDF、DOCX、ZIP、MP3、MP4等)
   - 对于特定媒体类型,建议使用专门的方法(如 sendAudio、sendVideo)

2. **缩略图要求:**
   - 缩略图最大尺寸为 200KB
   - 建议使用 JPG 格式
   - 最佳尺寸为 320x320 像素

3. **文件路径:**
   - 使用本地文件时,确保文件路径正确且 PHP 进程有读取权限
   - 建议使用绝对路径或相对路径配合 __DIR__

4. **聊天 ID 格式:**
   - 私人聊天 ID 是整数
   - 群组和频道 ID 通常以 `-100` 开头的负数

5. **高级选项:**
   - `disable_content_type_detection` 可防止 Telegram 自动检测并显示某些文件内容
   - `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-document.php
```

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部