Telegram Bot API forwardMessage 使用教程

## 1. forwardMessage 方法用途介绍

forwardMessage 是 Telegram Bot API 提供的一个核心方法,用于将一条消息从一个聊天(chat)转发到另一个聊天。

**主要用途:**
- 跨聊天转发消息,保留原始消息的属性和格式
- 在群组、频道和私人聊天之间传递信息
- 实现消息同步、内容共享和通知转发功能
- 作为机器人自动化工作流中的信息传递环节

**核心特点:**
- 转发后的消息会显示原始发送者的名称和头像
- 支持转发各种类型的消息:文本、照片、视频、音频、文档、位置、联系方式等
- 可选择隐藏原始发送者信息(匿名转发)
- 与 Bot API 的其他方法无缝集成
- 支持转发到 Direct Messages 聊天主题和发送建议帖子

## 2. 原生 PHP 调用实例

### 2.1 准备工作

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

### 2.2 简单的 forwardMessage 调用
<?php
/**
 * 使用 Telegram Bot API 转发消息
 * @param string $botToken Bot Token
 * @param int|string $chatId 目标聊天 ID
 * @param int|string $fromChatId 源聊天 ID
 * @param int $messageId 要转发的消息 ID
 * @return array 响应结果
 */
function forwardMessage($botToken, $chatId, $fromChatId, $messageId) {
    $url = "https://api.telegram.org/bot{$botToken}/forwardMessage";
    
    $data = [
        'chat_id' => $chatId,
        'from_chat_id' => $fromChatId,
        'message_id' => $messageId
    ];
    
    $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";
$targetChatId = -1001234567890; // 目标聊天 ID(群组/频道)
$sourceChatId = 123456789; // 源聊天 ID(用户/群组)
$messageId = 123; // 要转发的消息 ID

$result = forwardMessage($botToken, $targetChatId, $sourceChatId, $messageId);

if ($result['ok']) {
    echo "消息转发成功!";
    echo "转发后消息 ID: " . $result['result']['message_id'];
} else {
    echo "转发失败:" . $result['description'];
}
?>

2.3 带可选参数的 forwardMessage 调用

```php
<?php
/**
 * 使用 Telegram Bot API 转发消息(带可选参数)
 * @param string $botToken Bot Token
 * @param int|string $chatId 目标聊天 ID
 * @param int|string $fromChatId 源聊天 ID
 * @param int $messageId 要转发的消息 ID
 * @param bool $disableNotification 是否禁用通知
 * @param bool $protectContent 是否保护内容(防止转发/保存)
 * @param bool $hideSenderName 是否隐藏原始发送者名称
 * @param int|null $messageThreadId 主题 ID(用于超级群组)
 * @param int|null $directMessagesTopicId Direct Messages 聊天主题 ID
 * @return array 响应结果
 */
function forwardMessageWithOptions($botToken, $chatId, $fromChatId, $messageId, $disableNotification = false, $protectContent = false, $hideSenderName = false, $messageThreadId = null, $directMessagesTopicId = null) {
    $url = "https://api.telegram.org/bot{$botToken}/forwardMessage";
    
    $data = [
        'chat_id' => $chatId,
        'from_chat_id' => $fromChatId,
        'message_id' => $messageId,
        'disable_notification' => $disableNotification,
        'protect_content' => $protectContent,
        'hide_sender_name' => $hideSenderName
    ];
    
    if ($messageThreadId !== null) {
        $data['message_thread_id'] = $messageThreadId;
    }
    
    if ($directMessagesTopicId !== null) {
        $data['direct_messages_topic_id'] = $directMessagesTopicId;
    }
    
    $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);
}

// 使用示例 - 匿名转发到 Direct Messages 聊天主题
$botToken = "YOUR_BOT_TOKEN";
$targetChatId = -1001234567890;
$sourceChatId = 123456789;
$messageId = 123;

$result = forwardMessageWithOptions(
    $botToken,
    $targetChatId,
    $sourceChatId,
    $messageId,
    true, // 禁用通知
    true, // 保护内容
    true, // 隐藏发送者名称
    null,
    456   // Direct Messages 聊天主题 ID
);

if ($result['ok']) {
    echo "匿名消息转发成功!";
} else {
    echo "转发失败:" . $result['description'];
}
?>
```

### 2.4 完整的 Telegram Bot 消息转发类

```php
<?php
class TelegramForwardBot {
    private $botToken;
    
    /**
     * 构造函数
     * @param string $botToken Bot Token
     */
    public function __construct($botToken) {
        $this->botToken = $botToken;
    }
    
    /**
     * 转发消息
     * @param int|string $chatId 目标聊天 ID
     * @param int|string $fromChatId 源聊天 ID
     * @param int $messageId 要转发的消息 ID
     * @param array $options 可选参数
     * @return array 响应结果
     */
    public function forwardMessage($chatId, $fromChatId, $messageId, $options = []) {
        $url = "https://api.telegram.org/bot{$this->botToken}/forwardMessage";
        
        $data = [
            'chat_id' => $chatId,
            'from_chat_id' => $fromChatId,
            'message_id' => $messageId
        ];
        
        // 合并可选参数
        $allowedOptions = ['disable_notification', 'protect_content', 'hide_sender_name', 'message_thread_id', 'direct_messages_topic_id', 'suggested_post_parameters'];
        foreach ($allowedOptions as $option) {
            if (isset($options[$option])) {
                $data[$option] = $options[$option];
            }
        }
        
        return $this->sendRequest($url, $data);
    }
    
    /**
     * 批量转发消息
     * @param int|string $chatId 目标聊天 ID
     * @param int|string $fromChatId 源聊天 ID
     * @param array $messageIds 要转发的消息 ID 数组
     * @param array $options 可选参数(适用于所有转发)
     * @return array 所有转发结果
     */
    public function forwardMessages($chatId, $fromChatId, $messageIds, $options = []) {
        $results = [];
        
        foreach ($messageIds as $messageId) {
            $result = $this->forwardMessage($chatId, $fromChatId, $messageId, $options);
            $results[$messageId] = $result;
        }
        
        return $results;
    }
    
    /**
     * 发送 HTTP 请求
     * @param string $url 请求 URL
     * @param array $data 请求数据
     * @return array 响应结果
     */
    private function sendRequest($url, $data) {
        $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);
        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);
    }
    
    /**
     * 获取更新(用于获取消息 ID)
     * @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 TelegramForwardBot($botToken);

// 基本转发
$result1 = $bot->forwardMessage(
    -1001234567890, // 目标聊天 ID
    123456789,      // 源聊天 ID
    123             // 消息 ID
);

if ($result1['ok']) {
    echo "基本转发成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
    echo "基本转发失败:" . $result1['description'] . "\n";
}

// 带高级选项的转发
$result2 = $bot->forwardMessage(
    -1001234567890,
    123456789,
    456,
    [
        'hide_sender_name' => true,
        'protect_content' => true,
        'direct_messages_topic_id' => 789
    ]
);

if ($result2['ok']) {
    echo "高级转发成功!\n";
} else {
    echo "高级转发失败:" . $result2['description'] . "\n";
}

// 批量转发
$messageIds = [123, 456, 789];
$batchResults = $bot->forwardMessages(-1001234567890, 123456789, $messageIds);

foreach ($batchResults as $messageId => $result) {
    if ($result['ok']) {
        echo "消息 {$messageId} 转发成功!\n";
    } else {
        echo "消息 {$messageId} 转发失败:" . $result['description'] . "\n";
    }
}
?>
2.5 注意事项

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

2. **权限要求**
   - 机器人必须在源聊天和目标聊天中都具有访问权限
   - 对于私有频道,机器人需要是管理员

3. **转发限制**
   - 遵守 Telegram 的速率限制,避免频繁转发
   - 某些聊天可能限制了转发功能

4. **特殊参数**
   - `hide_sender_name` 仅在转发到超级群组或频道时有效
   - `direct_messages_topic_id` 用于将消息转发到 Direct Messages 聊天主题
   - `suggested_post_parameters` 用于将转发的消息作为建议帖子发送

## 3. 应用场景

- **消息同步**:在多个群组之间同步重要消息
- **内容聚合**:从多个源聊天收集信息到一个中央聊天
- **通知转发**:将系统通知转发到管理员群组
- **用户支持**:将用户查询转发到支持团队
- **内容分享**:在频道和群组之间分享优质内容

## 4. 运行指南

1. 将以上代码保存为 `.php` 文件
2. 替换 `YOUR_BOT_TOKEN` 为你的实际 Bot Token
3. 替换聊天 ID 和消息 ID 为实际值
4. 在命令行或浏览器中运行 PHP 文件

```bash
php telegram-forward-message.php
```

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部