# Telegram Bot API sendMessage 方法教程
## 1. Telegram Bot API 简介
Telegram Bot API 是一个基于 HTTP 的接口,专为开发者构建 Telegram 机器人而设计。它允许开发者通过简单的 HTTP 请求与 Telegram 服务器进行交互,实现各种机器人功能。
## 2. sendMessage 方法简介
`sendMessage` 是 Telegram Bot API 中最常用的方法之一,用于向指定聊天发送文本消息。
### 方法特点:
- 需要多个必填参数(聊天ID、消息文本等)
- 支持丰富的可选参数(格式、键盘、回复等)
- 返回发送的消息对象
- 是机器人与用户交互的基础
## 3. 准备工作
### 3.1 创建 Telegram 机器人
1. 在 Telegram 中搜索 `@BotFather`
2. 发送 `/newbot` 命令创建新机器人
3. 按照提示设置机器人名称和用户名
4. 获取 BotFather 提供的 API 令牌(类似:`123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ`)
### 3.2 获取聊天 ID
要向用户发送消息,需要知道用户的聊天 ID:
1. 让用户在 Telegram 中搜索并启动你的机器人
2. 用户发送一条消息给机器人
3. 通过 `getUpdates` 方法或 Webhook 接收更新,从中获取 `chat.id` 字段
### 3.3 环境要求
- PHP 5.6 或更高版本
- 启用 cURL 扩展(用于发送 HTTP 请求)
## 4. sendMessage 方法参数详解
### 4.1 必填参数
| 参数 | 类型 | 描述 |
|------|------|------|
| `chat_id` | Integer/String | 目标聊天的唯一标识符或用户名 |
| `text` | String | 要发送的消息文本,最大 4096 个字符 |
### 4.2 可选参数
| 参数 | 类型 | 描述 |
|------|------|------|
| `message_thread_id` | Integer | 消息主题标识符(用于超级群组中的主题) |
| `parse_mode` | String | 消息文本的解析模式(MarkdownV2、HTML、Markdown) |
| `entities` | Array | 消息文本中的特殊实体列表 |
| `disable_web_page_preview` | Boolean | 禁用链接的网页预览 |
| `disable_notification` | Boolean | 发送消息时不触发通知 |
| `protect_content` | Boolean | 保护消息不被转发和保存 |
| `reply_to_message_id` | Integer | 要回复的消息 ID |
| `allow_sending_without_reply` | Boolean | 即使目标消息已被删除,也允许回复 |
| `reply_markup` | Object | 自定义键盘、内联键盘、强制回复等 |
| `direct_messages_topic_id` | Integer | 直接消息主题 ID(用于频道直接消息) |
| `suggested_post_parameters` | Object | 建议帖子参数(用于频道直接消息) |
## 5. PHP 代码实现
### 5.1 发送简单文本消息
```php
<?php
// 机器人 API 令牌
$token = 'YOUR_BOT_TOKEN';
// 目标聊天 ID
$chatId = 123456789;
// 消息文本
$text = '你好!这是一条来自 Telegram 机器人的消息。';
// API URL
$url = "https://api.telegram.org/bot{$token}/sendMessage";
// 请求参数
$params = [
'chat_id' => $chatId,
'text' => $text
];
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
// 发送请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)) {
echo 'cURL 错误:' . curl_error($ch);
exit;
}
// 关闭 cURL
curl_close($ch);
// 解析 JSON 响应
$data = json_decode($response, true);
// 输出响应结果
if($data['ok']) {
echo '消息发送成功!消息 ID:' . $data['result']['message_id'];
} else {
echo '错误:' . $data['description'] . '(错误码:' . $data['error_code'] . ')';
}
?>
```
### 5.2 发送带有 Markdown 格式的消息
```php
<?php
// 机器人 API 令牌
$token = 'YOUR_BOT_TOKEN';
// 目标聊天 ID
$chatId = 123456789;
// 带有 Markdown 格式的消息文本
$text = "*这是粗体文本*\n" .
"_这是斜体文本_\n" .
"[这是链接](https://example.com)\n" .
"`这是代码`\n" .
"```\n这是代码块\n```";
// API URL
$url = "https://api.telegram.org/bot{$token}/sendMessage";
// 请求参数
$params = [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'MarkdownV2'
];
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
// 发送请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)) {
echo 'cURL 错误:' . curl_error($ch);
exit;
}
// 关闭 cURL
curl_close($ch);
// 解析 JSON 响应
$data = json_decode($response, true);
// 输出响应结果
if($data['ok']) {
echo '格式化消息发送成功!';
} else {
echo '错误:' . $data['description'] . '(错误码:' . $data['error_code'] . ')';
}
?>
```
### 5.3 发送带有回复的消息
```php
<?php
// 机器人 API 令牌
$token = 'YOUR_BOT_TOKEN';
// 目标聊天 ID
$chatId = 123456789;
// 要回复的消息 ID
$replyToMessageId = 123;
// 消息文本
$text = '这是对您消息的回复。';
// API URL
$url = "https://api.telegram.org/bot{$token}/sendMessage";
// 请求参数
$params = [
'chat_id' => $chatId,
'text' => $text,
'reply_to_message_id' => $replyToMessageId
];
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
// 发送请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)) {
echo 'cURL 错误:' . curl_error($ch);
exit;
}
// 关闭 cURL
curl_close($ch);
// 解析 JSON 响应
$data = json_decode($response, true);
// 输出响应结果
if($data['ok']) {
echo '回复消息发送成功!';
} else {
echo '错误:' . $data['description'] . '(错误码:' . $data['error_code'] . ')';
}
?>
```
### 5.4 发送带有自定义键盘的消息
```php
<?php
// 机器人 API 令牌
$token = 'YOUR_BOT_TOKEN';
// 目标聊天 ID
$chatId = 123456789;
// 消息文本
$text = '请选择一个选项:';
// 自定义键盘
$replyMarkup = [
'keyboard' => [
['选项 1', '选项 2'],
['选项 3', '选项 4']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
];
// API URL
$url = "https://api.telegram.org/bot{$token}/sendMessage";
// 请求参数
$params = [
'chat_id' => $chatId,
'text' => $text,
'reply_markup' => json_encode($replyMarkup)
];
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
// 发送请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if(curl_errno($ch)) {
echo 'cURL 错误:' . curl_error($ch);
exit;
}
// 关闭 cURL
curl_close($ch);
// 解析 JSON 响应
$data = json_decode($response, true);
// 输出响应结果
if($data['ok']) {
echo '带有键盘的消息发送成功!';
} else {
echo '错误:' . $data['description'] . '(错误码:' . $data['error_code'] . ')';
}
?>
```
## 6. 响应格式解析
`sendMessage` 方法成功调用后,会返回以下 JSON 格式的响应:
```json
{
"ok": true,
"result": {
"message_id": 123,
"from": {
"id": 987654321,
"is_bot": true,
"first_name": "ExampleBot",
"username": "example_bot"
},
"chat": {
"id": 123456789,
"first_name": "User",
"username": "user",
"type": "private"
},
"date": 1620000000,
"text": "你好!这是一条来自 Telegram 机器人的消息。"
}
}
```
### 响应字段说明:
| 字段 | 类型 | 描述 |
|------|------|------|
| `ok` | Boolean | 请求是否成功 |
| `result` | Object | 发送的消息对象 |
| `result.message_id` | Integer | 消息的唯一标识符 |
| `result.from` | Object | 发送消息的机器人信息 |
| `result.chat` | Object | 接收消息的聊天信息 |
| `result.date` | Integer | 消息发送时间戳 |
| `result.text` | String | 消息文本内容 |
## 7. 错误处理
当请求失败时,API 会返回类似以下格式的响应:
```json
{
"ok": false,
"error_code": 400,
"description": "Bad Request: chat not found"
}
```
### 常见错误码:
| 错误码 | 描述 | 解决方法 |
|--------|------|----------|
| 400 | 请求参数错误 | 检查参数格式和内容 |
| 401 | 未授权(令牌无效) | 检查令牌是否正确 |
| 403 | 禁止访问(机器人被屏蔽) | 检查机器人是否被目标用户屏蔽 |
| 404 | 聊天未找到 | 检查 chat_id 是否正确 |
| 429 | 请求过于频繁 | 减少请求频率,遵守 Telegram API 限制 |
| 500 | 服务器错误 | 稍后重试 |
## 8. 完整示例:创建一个功能完整的 PHP 类
```php
<?php
/**
* Telegram Bot 类
*/
class TelegramBot {
private $token;
private $apiUrl;
/**
* 构造函数
* @param string $token 机器人 API 令牌
*/
public function __construct($token) {
$this->token = $token;
$this->apiUrl = "https://api.telegram.org/bot{$token}/";
}
/**
* 获取机器人信息
* @return array|null 机器人信息或 null
*/
public function getMe() {
return $this->sendRequest('getMe');
}
/**
* 注销机器人所有会话
* @return bool|null 是否注销成功或 null
*/
public function logOut() {
return $this->sendRequest('logOut', [], 'POST');
}
/**
* 关闭 Webhook 连接
* @return bool|null 是否关闭成功或 null
*/
public function close() {
return $this->sendRequest('close', [], 'POST');
}
/**
* 发送消息
* @param int|string $chatId 目标聊天 ID
* @param string $text 消息文本
* @param array $options 可选参数
* @return array|null 发送的消息对象或 null
*/
public function sendMessage($chatId, $text, $options = []) {
$params = array_merge([
'chat_id' => $chatId,
'text' => $text
], $options);
return $this->sendRequest('sendMessage', $params, 'POST');
}
/**
* 获取更新
* @param array $params 请求参数
* @return array|null 更新列表或 null
*/
public function getUpdates($params = []) {
return $this->sendRequest('getUpdates', $params);
}
/**
* 发送 API 请求
* @param string $method API 方法名
* @param array $params 请求参数
* @param string $methodType 请求类型(GET 或 POST)
* @return mixed 响应结果或 null
*/
private function sendRequest($method, $params = [], $methodType = 'GET') {
// 构建完整的 API URL
$url = $this->apiUrl . $method;
// 如果是 GET 请求且有参数,添加到 URL
if($methodType === 'GET' && !empty($params)) {
$url .= '?' . http_build_query($params);
}
// 初始化 cURL
$ch = curl_init();
// 设置基本 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
// 设置请求类型
if($methodType === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
// 设置 POST 数据
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($params))
]);
}
// 发送请求
$response = curl_exec($ch);
// 检查错误
if(curl_errno($ch)) {
error_log('cURL 错误:' . curl_error($ch));
curl_close($ch);
return null;
}
// 关闭 cURL
curl_close($ch);
// 解析 JSON 响应
$data = json_decode($response, true);
// 检查响应是否有效
if(json_last_error() !== JSON_ERROR_NONE) {
error_log('JSON 解析错误:' . json_last_error_msg());
return null;
}
// 返回结果
return $data['ok'] ? $data['result'] : null;
}
}
// 使用示例
$token = 'YOUR_BOT_TOKEN';
$bot = new TelegramBot($token);
// 获取最新的更新,用于获取 chat_id
$updates = $bot->getUpdates();
if($updates && count($updates) > 0) {
// 获取最后一条更新的 chat_id
$chatId = $updates[count($updates) - 1]['message']['chat']['id'];
// 发送简单文本消息
$bot->sendMessage($chatId, '你好!这是一条来自 Telegram 机器人的消息。');
// 发送带有 Markdown 格式的消息
$bot->sendMessage($chatId, '*粗体文本* _斜体文本_ [链接](https://example.com)', [
'parse_mode' => 'MarkdownV2'
]);
// 发送带有自定义键盘的消息
$bot->sendMessage($chatId, '请选择一个选项:', [
'reply_markup' => [
'keyboard' => [
['选项 1', '选项 2'],
['选项 3', '选项 4']
],
'resize_keyboard' => true
]
]);
echo "消息发送完成!\n";
} else {
echo "没有新的更新或请求失败。\n";
}
?>
```
## 9. 高级用法和技巧
### 9.1 使用 HTML 格式
```php
<?php
// 发送带有 HTML 格式的消息
$bot->sendMessage($chatId, '<b>粗体文本</b> <i>斜体文本</i> <a href="https://example.com">链接</a>', [
'parse_mode' => 'HTML'
]);
?>
```
### 9.2 发送内联键盘
```php
<?php
// 发送带有内联键盘的消息
$bot->sendMessage($chatId, '请选择一个选项:', [
'reply_markup' => [
'inline_keyboard' => [
[
['text' => '选项 1', 'callback_data' => 'option1'],
['text' => '选项 2', 'callback_data' => 'option2']
],
[
['text' => '选项 3', 'callback_data' => 'option3']
]
]
]
]);
?>
```
### 9.3 设置消息的生命周期
```php
<?php
// 发送一条 60 秒后自动删除的消息
$bot->sendMessage($chatId, '这条消息将在 60 秒后自动删除。', [
'protect_content' => true
]);
?>
```
## 10. 应用场景
### 10.1 发送通知和警报
机器人可以向用户发送各种通知和警报,如系统状态、事件提醒、重要更新等。
### 10.2 提供信息查询服务
机器人可以根据用户的请求,查询并返回相关信息,如天气、新闻、股票价格等。
### 10.3 实现交互式对话
机器人可以通过发送消息和接收用户回复,实现复杂的交互式对话,如问卷调查、客户支持等。
### 10.4 自动化工作流
机器人可以集成到自动化工作流中,如接收表单提交、处理订单、发送确认信息等。
## 11. 运行示例
1. 将上述代码保存为 `bot_sendmessage.php`
2. 替换 `YOUR_BOT_TOKEN` 为你从 BotFather 获取的实际令牌
3. 在命令行中运行:
```bash
php bot_sendmessage.php
```
## 12. 注意事项
1. `sendMessage` 方法是一个 POST 请求,需要特别注意请求类型
2. 遵守 Telegram API 的限制,不要发送过于频繁的请求
3. 注意消息文本的长度限制(最大 4096 个字符)
4. 使用 Markdown 或 HTML 格式时,注意转义特殊字符
5. 保护用户隐私,不要发送未经授权的消息
6. 定期检查机器人的状态和错误日志
## 13. 总结
`sendMessage` 是 Telegram Bot API 中最核心、最常用的方法之一,它为机器人与用户之间的交互提供了基础:
- 支持发送各种格式的文本消息
- 提供丰富的参数选项,满足不同的需求
- 是实现复杂机器人功能的基础
- 掌握 `sendMessage` 方法是开发 Telegram 机器人的必备技能
通过本教程的学习,你应该已经掌握了 `sendMessage` 方法的基本用法和高级技巧,可以开始开发功能丰富的 Telegram 机器人了。
## 14. 参考资料
- [Telegram Bot API 官方文档](https://core.telegram.org/bots/api)
- [Telegram Bot API sendMessage 方法](https://core.telegram.org/bots/api#sendmessage)
- [Telegram Bot API 格式选项](https://core.telegram.org/bots/api#formatting-options)
- [Telegram Bot API 键盘选项](https://core.telegram.org/bots/api#keyboard)

发表评论 取消回复