Telegram Bot API sendPoll 使用教程
## 1. sendPoll 方法用途介绍


sendPoll 是 Telegram Bot API 提供的一个核心方法,用于向指定聊天发送投票/问卷,支持多种投票类型和高级选项。
**主要用途:**
- 向用户、群组或频道发起投票调查
- 收集用户反馈和意见
- 进行决策或选择活动
- 创建互动式内容增加用户参与度
**核心特点:**
- 支持单选和多选投票
- 可设置匿名或公开投票
- 支持设置投票截止时间
- 可公开投票结果
- 最多支持12个选项
- 可选择是否禁用通知
- 支持回复到聊天中的特定消息
- 可将投票发送到 Direct Messages 聊天主题
- 支持设置建议的帖子参数
## 2. 原生 PHP 调用实例
### 2.1 准备工作
确保你的 PHP 环境满足以下要求:
- PHP 5.6 或更高版本
- 已安装 cURL 扩展
- 已创建 Telegram Bot 并获取 Bot Token
### 2.2 发送基本单选投票
<?php
/**
* 使用 Telegram Bot API 发送基本单选投票
* @param string $botToken Bot Token
* @param int|string $chatId 聊天 ID
* @param string $question 投票问题
* @param array $options 投票选项
* @return array 响应结果
*/
function sendBasicPoll($botToken, $chatId, $question, $options) {
$url = "https://api.telegram.org/bot{$botToken}/sendPoll";
$data = [
'chat_id' => $chatId,
'question' => $question,
'options' => json_encode($options)
];
$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
$question = "你最喜欢的编程语言是什么?";
$options = ["PHP", "Python", "JavaScript", "Java", "C++"];
$result = sendBasicPoll($botToken, $chatId, $question, $options);
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 $question 投票问题
* @param array $options 投票选项
* @param array $advancedOptions 高级选项
* @return array 响应结果
*/
function sendAdvancedPoll($botToken, $chatId, $question, $options, $advancedOptions = []) {
$url = "https://api.telegram.org/bot{$botToken}/sendPoll";
$data = [
'chat_id' => $chatId,
'question' => $question,
'options' => json_encode($options)
];
// 合并高级选项
$allowedOptions = [
'is_anonymous', 'type', 'allows_multiple_answers', 'correct_option_id',
'explanation', 'explanation_parse_mode', 'open_period', 'close_date',
'is_closed', '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($advancedOptions[$option])) {
$data[$option] = $advancedOptions[$option];
}
}
$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;
$question = "你最常用的开发工具是什么?";
$options = ["VS Code", "PhpStorm", "Sublime Text", "Atom", "Vim", "Emacs"];
// 设置24小时后自动关闭的多选投票
$closeDate = time() + 86400; // 24小时后
$result = sendAdvancedPoll(
$botToken,
$chatId,
$question,
$options,
[
'is_anonymous' => false, // 公开投票
'type' => 'regular', // 普通投票类型
'allows_multiple_answers' => true, // 允许多选
'explanation' => "请选择你日常开发中使用的工具,可以多选哦!",
'explanation_parse_mode' => 'HTML',
'close_date' => $closeDate, // 自动关闭时间
'disable_notification' => false,
'protect_content' => false
]
);
if ($result['ok']) {
echo "高级投票发送成功!消息 ID: " . $result['result']['message_id'];
} else {
echo "发送失败:" . $result['description'];
}
?>
```
### 2.4 完整的 Telegram Bot 投票发送类
```php
<?php
class TelegramPollBot {
private $botToken;
/**
* 构造函数
* @param string $botToken Bot Token
*/
public function __construct($botToken) {
$this->botToken = $botToken;
}
/**
* 发送基本单选投票
* @param int|string $chatId 聊天 ID
* @param string $question 投票问题
* @param array $options 投票选项
* @return array 响应结果
*/
public function sendPoll($chatId, $question, $options) {
return $this->sendAdvancedPoll($chatId, $question, $options, []);
}
/**
* 发送多选投票
* @param int|string $chatId 聊天 ID
* @param string $question 投票问题
* @param array $options 投票选项
* @param array $additional 额外选项
* @return array 响应结果
*/
public function sendMultiChoicePoll($chatId, $question, $options, $additional = []) {
$params = $additional;
$params['allows_multiple_answers'] = true;
return $this->sendAdvancedPoll($chatId, $question, $options, $params);
}
/**
* 发送匿名投票
* @param int|string $chatId 聊天 ID
* @param string $question 投票问题
* @param array $options 投票选项
* @param array $additional 额外选项
* @return array 响应结果
*/
public function sendAnonymousPoll($chatId, $question, $options, $additional = []) {
$params = $additional;
$params['is_anonymous'] = true;
return $this->sendAdvancedPoll($chatId, $question, $options, $params);
}
/**
* 发送带高级选项的投票
* @param int|string $chatId 聊天 ID
* @param string $question 投票问题
* @param array $options 投票选项
* @param array $advancedOptions 高级选项
* @return array 响应结果
*/
public function sendAdvancedPoll($chatId, $question, $options, $advancedOptions = []) {
$url = "https://api.telegram.org/bot{$this->botToken}/sendPoll";
// 验证选项数量(最多12个)
if (count($options) < 2 || count($options) > 12) {
return [
'ok' => false,
'error_code' => 400,
'description' => '选项数量必须在2-12个之间'
];
}
$data = [
'chat_id' => $chatId,
'question' => $question,
'options' => json_encode($options)
];
// 合并高级选项
$allowedOptions = [
'is_anonymous', 'type', 'allows_multiple_answers', 'correct_option_id',
'explanation', 'explanation_parse_mode', 'open_period', 'close_date',
'is_closed', '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($advancedOptions[$option])) {
$data[$option] = $advancedOptions[$option];
}
}
return $this->sendRequest($url, $data);
}
/**
* 停止投票
* @param int|string $chatId 聊天 ID
* @param int $messageId 投票消息 ID
* @return array 响应结果
*/
public function stopPoll($chatId, $messageId) {
$url = "https://api.telegram.org/bot{$this->botToken}/stopPoll";
$data = [
'chat_id' => $chatId,
'message_id' => $messageId
];
return $this->sendRequest($url, $data);
}
/**
* 发送 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);
}
/**
* 获取更新
* @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 TelegramPollBot($botToken);
$chatId = 123456789;
// 发送基本单选投票
echo "发送基本单选投票...\n";
$result1 = $bot->sendPoll(
$chatId,
"你最喜欢的开发框架是什么?", // 投票问题
["Laravel", "Symfony", "CodeIgniter", "Yii", "Zend Framework"] // 选项
);
if ($result1['ok']) {
echo "基本投票发送成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
echo "发送失败:" . $result1['description'] . "\n";
}
// 发送多选投票
echo "\n发送多选投票...\n";
$result2 = $bot->sendMultiChoicePoll(
$chatId,
"你使用哪些数据库?",
["MySQL", "PostgreSQL", "MongoDB", "Redis", "SQLite", "Oracle"],
[
'is_anonymous' => false,
'explanation' => "请选择你熟悉并使用过的数据库,可多选",
'explanation_parse_mode' => 'HTML'
]
);
if ($result2['ok']) {
echo "多选投票发送成功!消息 ID: " . $result2['result']['message_id'] . "\n";
} else {
echo "发送失败:" . $result2['description'] . "\n";
}
// 发送带截止时间的投票
echo "\n发送带截止时间的投票...\n";
$closeDate = time() + 3600; // 1小时后关闭
$result3 = $bot->sendAdvancedPoll(
$chatId,
"你觉得这个Bot功能如何?",
["非常好", "好", "一般", "需要改进"],
[
'is_anonymous' => true,
'close_date' => $closeDate,
'disable_notification' => false
]
);
if ($result3['ok']) {
echo "带截止时间的投票发送成功!消息 ID: " . $result3['result']['message_id'] . "\n";
// 示例:停止投票(实际使用时取消注释)
// sleep(60); // 等待1分钟
// $stopResult = $bot->stopPoll($chatId, $result3['result']['message_id']);
// if ($stopResult['ok']) {
// echo "投票已停止!\n";
// }
} else {
echo "发送失败:" . $result3['description'] . "\n";
}
?>
2.5 注意事项
1. **选项要求:**
- 选项数量必须在2-12个之间
- 每个选项的长度不宜过长,建议控制在60个字符以内
2. **投票类型:**
- `type`:投票类型,可选值为 `regular`(普通)或 `quiz`(测验)
- `quiz` 类型需要设置 `correct_option_id` 指定正确答案
3. **时间设置:**
- `open_period`:投票开放时间(秒),范围5-604800(1周)
- `close_date`:投票关闭时间戳,与 `open_period` 二选一
4. **高级选项:**
- `is_anonymous`:是否匿名投票(默认true)
- `allows_multiple_answers`:是否允许多选(默认false)
- `correct_option_id`:正确答案索引(仅quiz类型可用)
- `explanation_parse_mode`:解释文本的解析模式(HTML或MarkdownV2)
5. **聊天 ID 格式:**
- 私人聊天 ID 是整数
- 群组和频道 ID 通常以 `-100` 开头的负数
## 3. 应用场景
- **用户调研:** 收集用户反馈和偏好
- **决策制定:** 群组内进行民主决策
- **知识测验:** 创建问答测验,测试用户知识
- **活动选择:** 选择聚会时间、地点等
- **内容互动:** 增加用户参与度和互动性
## 4. 运行指南
1. 将以上代码保存为 `.php` 文件
2. 替换 `YOUR_BOT_TOKEN` 为你的实际 Bot Token
3. 替换聊天 ID、投票问题和选项为实际值
4. 在命令行或浏览器中运行 PHP 文件
```bash
php telegram-send-poll.php

发表评论 取消回复