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

sendContact 是 Telegram Bot API 提供的一个核心方法,用于向指定聊天发送联系人信息,包含姓名、电话号码和可选的额外信息。
**主要用途:**
- 向用户、群组或频道发送联系人的完整信息
- 提供结构化的联系人数据,便于用户直接保存到手机通讯录
- 可附加联系人的用户名、公司名称、职位等详细信息
**核心特点:**
- 发送包含姓名和电话号码的基本联系人信息
- 支持附加联系人的 Telegram 用户名
- 可选择是否禁用通知
- 支持回复到聊天中的特定消息
- 可将联系人信息发送到 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 $phoneNumber 电话号码
* @param string $firstName 联系人姓名
* @return array 响应结果
*/
function sendBasicContact($botToken, $chatId, $phoneNumber, $firstName) {
$url = "https://api.telegram.org/bot{$botToken}/sendContact";
$data = [
'chat_id' => $chatId,
'phone_number' => $phoneNumber,
'first_name' => $firstName
];
$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
$phoneNumber = "+1234567890";
$firstName = "张三";
$result = sendBasicContact($botToken, $chatId, $phoneNumber, $firstName);
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 $phoneNumber 电话号码
* @param string $firstName 联系人姓名
* @param array $options 高级选项
* @return array 响应结果
*/
function sendAdvancedContact($botToken, $chatId, $phoneNumber, $firstName, $options = []) {
$url = "https://api.telegram.org/bot{$botToken}/sendContact";
$data = [
'chat_id' => $chatId,
'phone_number' => $phoneNumber,
'first_name' => $firstName
];
// 合并高级选项
$allowedOptions = [
'last_name', 'vcard', '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, $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;
$phoneNumber = "+8613800138000";
$firstName = "李四";
// 创建 VCARD 格式的联系人信息
$vcard = "BEGIN:VCARD\nVERSION:3.0\nFN:李四\nN:李;四;;;\nTEL;TYPE=CELL:+8613800138000\nEMAIL:lisi@example.com\nORG:示例公司\nTITLE:技术总监\nURL:https://example.com\nEND:VCARD";
$result = sendAdvancedContact(
$botToken,
$chatId,
$phoneNumber,
$firstName,
[
'last_name' => 'Wang', // 姓氏
'vcard' => $vcard, // VCARD 格式的完整联系人信息
'disable_notification' => false,
'protect_content' => true, // 防止内容被转发
'direct_messages_topic_id' => 67890 // Direct Messages 聊天主题 ID
]
);
if ($result['ok']) {
echo "高级联系人信息发送成功!";
} else {
echo "发送失败:" . $result['description'];
}
?>
```
### 2.4 完整的 Telegram Bot 联系人发送类
```php
<?php
class TelegramContactBot {
private $botToken;
/**
* 构造函数
* @param string $botToken Bot Token
*/
public function __construct($botToken) {
$this->botToken = $botToken;
}
/**
* 发送基本联系人信息
* @param int|string $chatId 聊天 ID
* @param string $phoneNumber 电话号码
* @param string $firstName 联系人姓名
* @return array 响应结果
*/
public function sendContact($chatId, $phoneNumber, $firstName) {
return $this->sendAdvancedContact($chatId, $phoneNumber, $firstName, []);
}
/**
* 发送带高级选项的联系人信息
* @param int|string $chatId 聊天 ID
* @param string $phoneNumber 电话号码
* @param string $firstName 联系人姓名
* @param array $options 高级选项
* @return array 响应结果
*/
public function sendAdvancedContact($chatId, $phoneNumber, $firstName, $options = []) {
$url = "https://api.telegram.org/bot{$this->botToken}/sendContact";
$data = [
'chat_id' => $chatId,
'phone_number' => $phoneNumber,
'first_name' => $firstName
];
// 验证电话号码格式(简单验证)
if (!preg_match('/^\+?[0-9\s\-\(\)]{7,15}$/', $phoneNumber)) {
return [
'ok' => false,
'error_code' => 400,
'description' => '无效的电话号码格式'
];
}
// 合并高级选项
$allowedOptions = [
'last_name', 'vcard', '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);
}
/**
* 发送 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);
}
/**
* 创建 VCARD 格式的联系人信息
* @param string $firstName 姓名
* @param string $lastName 姓氏
* @param string $phoneNumber 电话号码
* @param array $additional 附加信息
* @return string VCARD 格式的字符串
*/
public static function createVCard($firstName, $lastName = '', $phoneNumber, $additional = []) {
$vcard = "BEGIN:VCARD\nVERSION:3.0\n";
$vcard .= "FN:{$firstName} {$lastName}\n";
$vcard .= "N:{$lastName};{$firstName};;;\n";
$vcard .= "TEL;TYPE=CELL:{$phoneNumber}\n";
if (isset($additional['email'])) {
$vcard .= "EMAIL:{$additional['email']}\n";
}
if (isset($additional['company'])) {
$vcard .= "ORG:{$additional['company']}\n";
}
if (isset($additional['title'])) {
$vcard .= "TITLE:{$additional['title']}\n";
}
if (isset($additional['url'])) {
$vcard .= "URL:{$additional['url']}\n";
}
$vcard .= "END:VCARD";
return $vcard;
}
}
// 使用示例
$botToken = "YOUR_BOT_TOKEN";
$bot = new TelegramContactBot($botToken);
$chatId = 123456789;
// 发送基本联系人信息
echo "发送基本联系人信息...\n";
$result1 = $bot->sendContact(
$chatId,
"+1234567890", // 电话号码
"张三" // 姓名
);
if ($result1['ok']) {
echo "基本联系人信息发送成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
echo "发送失败:" . $result1['description'] . "\n";
}
// 创建并发送带有 VCARD 的完整联系人信息
echo "\n发送完整联系人信息...\n";
$vcard = TelegramContactBot::createVCard(
"李四",
"Wang",
"+8613800138000",
[
'email' => 'lisi@example.com',
'company' => '示例科技有限公司',
'title' => '技术总监',
'url' => 'https://example.com'
]
);
$result2 = $bot->sendAdvancedContact(
$chatId,
"+8613800138000",
"李四",
[
'last_name' => 'Wang',
'vcard' => $vcard,
'direct_messages_topic_id' => 67890,
'protect_content' => true
]
);
if ($result2['ok']) {
echo "完整联系人信息发送成功!";
} else {
echo "发送失败:" . $result2['description'] . "\n";
}
?>
```
2.5 注意事项
1. **电话号码格式:**
- 建议使用国际格式(带 + 号前缀)
- 支持数字、空格、连字符和括号等常见分隔符
- 长度通常在 7-15 位之间
2. **联系人信息:**
- `first_name`:联系人姓名,不能为空
- `last_name`:联系人姓氏,可选
- `vcard`:VCARD 格式的完整联系人信息,可选
3. **VCARD 格式:**
- 支持标准 VCARD 3.0 格式
- 可包含 email、公司、职位、URL 等附加信息
- 格式必须正确,否则可能无法正确解析
4. **聊天 ID 格式:**
- 私人聊天 ID 是整数
- 群组和频道 ID 通常以 `-100` 开头的负数
5. **高级选项:**
- `direct_messages_topic_id` 用于将联系人信息发送到 Direct Messages 聊天主题
- `protect_content` 可防止联系人信息被转发或保存
- `suggested_post_parameters` 可设置建议的帖子参数
## 3. 应用场景
- **联系人分享:** 向用户分享其他联系人的信息
- **客服支持:** 提供客服人员的联系方式
- **业务合作:** 分享业务伙伴的联系信息
- **团队介绍:** 向群组介绍团队成员的联系方式
- **活动组织:** 分享活动负责人的联系方式
## 4. 运行指南
1. 将以上代码保存为 `.php` 文件
2. 替换 `YOUR_BOT_TOKEN` 为你的实际 Bot Token
3. 替换聊天 ID、电话号码和联系人信息为实际值
4. 在命令行或浏览器中运行 PHP 文件
```bash
php telegram-send-contact.php
```
所有代码均为原生 PHP 编写,无需任何框架依赖,可直接使用。

发表评论 取消回复