
本文档介绍了如何使用 Telegram Bot API 发送包含可点击电话号码的消息。由于`sendMessage`方法对`phone_number`实体类型的支持有限,本文将介绍使用`sendContact`方法来安全有效地实现此功能。我们将提供代码示例和详细步骤,帮助开发者在 Telegram 消息中集成可点击的电话号码。
在 Telegram 机器人开发中,有时需要发送包含电话号码的消息,并希望用户能够直接点击该号码进行拨打。虽然sendMessage方法提供了entities参数来格式化消息,但对于phone_number实体类型的支持可能并不稳定。因此,推荐使用sendContact方法来实现此功能。
sendContact方法专门用于发送联系人信息,包括电话号码。这是一种更可靠且官方推荐的方式来发送可点击的电话号码。
以下是使用 PHP 和 GuzzleHttp 库的示例代码:
<?php
require 'vendor/autoload.php'; // 引入 Composer 自动加载
$apiKey = 'YOUR_BOT_API_KEY'; // 替换为你的 Bot API Key
$chatID = 'YOUR_CHAT_ID'; // 替换为你的 Chat ID
$phoneNumber = '+1234567890'; // 替换为你要发送的电话号码
$firstName = 'John'; // 替换为联系人的名字
$lastName = 'Doe'; // 替换为联系人的姓氏
$apiURL = 'https://api.telegram.org/bot' . $apiKey . '/';
$client = new \GuzzleHttp\Client(['base_uri' => $apiURL]);
try {
$response = $client->post('sendContact', [
'multipart' => [
[
'name' => 'chat_id',
'contents' => $chatID,
],
[
'name' => 'phone_number',
'contents' => $phoneNumber,
],
[
'name' => 'first_name',
'contents' => $firstName,
],
[
'name' => 'last_name',
'contents' => $lastName,
],
],
]);
$body = $response->getBody();
echo $body;
} catch (GuzzleHttp\Exception\GuzzleException $e) {
echo "Error: " . $e->getMessage();
}
?>代码解释:
注意事项:
虽然使用sendMessage方法的entities参数可能可以实现部分格式化效果,但对于发送可点击的电话号码,sendContact方法是更可靠和推荐的选择。 通过使用sendContact方法,您可以确保电话号码在 Telegram 消息中正确显示,并且用户可以方便地点击该号码进行拨打。 这种方法不仅提高了用户体验,也符合 Telegram Bot API 的最佳实践。
以上就是Telegram机器人发送可点击电话号码:使用sendContact方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号