bahramali / telegram-bot-php
Telegram-Bot-PHP 是一个用于与官方 Telegram Bot API 交互的 PHP 库
Requires
- php: >=7.4
- ext-curl: *
- ext-json: *
- ext-mbstring: *
- ext-openssl: *
README
Telegram Bot PHP 是一个用于与 Telegram Bot API 5.4(2021年11月5日)交互的 PHP 库。
表格
要求
请至少阅读一次 Telegram API 文档
- 阅读 Telegram API 文档
- php >=7.4
- ext-curl: *
- ext-json: *
- ext-mbstring: *
- ext-openssl: *
安装
使用 composer 来要求它,
composer require bahramali/telegram-bot-php
或者
php composer.phar require bahramali/telegram-bot-php
或者
创建 composer.json 文件并添加
{
"name": "<vendor>/<name>",
"require": {
"bahramali/telegram-bot-php": "*"
}
}
然后运行
composer update
注意:如果您没有 Composer,您可以在这里下载它 HERE。
使用
要使用此库,您需要引入 Composer 自动加载器,并从 bot 类创建一个新的对象
请至少阅读一次 Telegram API 文档
use TelegramBotPHP\Bot; require_once __DIR__ . '/vendor/autoload.php'; /** * @link https://core.telegram.org/bots/api#authorizing-your-bot */ $bot = new Bot('__BOT_API_TOKEN__');
安全性
您可以将特定的参数添加到您的 webhook url 中,以便只有您知道该链接。
示例
https://example.com/bot?example=1a79a4d60de6718e8e5b326e338ae533
然后在您的代码中检查必须存在的参数
if ($_GET['example'] == '1a79a4d60de6718e8e5b326e338ae533') { // code } else { // 404 not found }
请确保检查 IP 是 Telegram IP 的发送者。
您可以使用 'bot' 类的 'isTelegramIp' 函数来检查 Telegram IP
示例
$ip = $_SERVER['REMOTE_ADDR']; if (Bot::isTelegramIp($ip)) { // code } else { // 404 not found }
配置
配置项
您可以根据每个部分调整配置并更改它
如果您使用本地 bot api 服务器,设置您的服务器 URL
/** * bot api server url * @link https://core.telegram.org/bots/api#using-a-local-bot-api-server */ public string $botApiServerUrl = 'https://api.telegram.org/bot'; // https://example.com/bot{__BOT_API_TOKEN__}/MethodName?parameters=values
如果您使用本地 bot api 服务器,设置您的服务器文件 URL,用于下载文件
/** * bot api server file url * @link https://core.telegram.org/bots/api#file */ public string $botApiServerFileUrl = 'https://api.telegram.org/file/bot'; // https://example.com/example/file/bot{__BOT_API_TOKEN__}/{__FILE_PATH__}
将更新和响应转换为对象,以便更容易访问
您也可以将变量设置为 false 并以数组形式接收更新和响应
/** * auto convert update and response to class For easier access */ public bool $convertToObject = true;
如果您不想自动使用 Webhook,将此变量设置为 false
/** * Use webhook by default * if use getUpdates Set this variable to false */ public bool $autoUseWebhook = true;
如果您不想某些方法的一些参数自动设置,将此变量设置为 false
其准确性不一定总是保证
/** * In certain methods, some parameters are filled in automatically * * For example, in `sendMessage` method, * You can, not set "chat_id", * And the "chat_id" of the sender is considered automatic. */ public bool $autofillParameters = true;
如果您希望程序在出现错误后继续运行,将此变量设置为 false
这仅适用于提交请求的响应代码不等于 200 的情况
/** * Stop the program when it encounters an error */ public bool $throwOnError = true;
日志记录
此库可以记录所有更新、请求、响应和错误
只需设置所需的日志函数即可
您可以在应用程序的任何位置更改任何函数
获取信息,并可以使用您想要的任何方法来记录它
onLog
对于更新、请求、响应和错误
最后,程序被调用并输出更新以及所有请求和响应和错误的列表作为输入
示例
$config->onLog = function (array $log) { $log = json_encode($log); file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND); };
onLogUpdate
仅更新
收到更新时调用函数
示例
$config->onLogUpdate = function (array $update) { $logUpdate = json_encode($update); file_put_contents(__DIR__ . '/Bot_update.log', "{$logUpdate}\n", FILE_APPEND); };
onLogRequestAndResponse
仅请求和响应
发送请求且响应代码为 200 时
示例
$config->onLogRequestAndResponse = function (array $request, array $response) { $logRequestAndResponse = [$request, $response]; $logRequestAndResponse = json_encode($logRequestAndResponse); file_put_contents(__DIR__ . '/Bot_request_response.log', "{$logRequestAndResponse}\n", FILE_APPEND); };
onLogError
仅错误
发送请求且响应代码不为 200 时
示例
$config->onLogError = function (array $error) { $logError = json_encode($error); file_put_contents(__DIR__ . '/Bot_error.log', "{$logError}\n", FILE_APPEND); };
主要配置
主要配置在程序中的每个地方都是恒定的。当创建新的配置时,默认值是为主配置设置的值。
您可以根据每个部分调整主要配置并更改它
注意:您可以在上面看到默认值
使用
它应该只静态使用
MainConfig::$onLog = function (array $log) { $log = json_encode($log); file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND); }; // MainConfig::.... = ... ;
使用配置
只需创建配置类的对象并更改值
注意:默认配置值是主配置的值
$config = new Config(); $config->onLog = function (array $log) { $log = json_encode($log); file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND); }; $config->onLogUpdate = function ($update) { $logUpdate = json_encode($update); file_put_contents(__DIR__ . '/Bot_update.log', "{$logUpdate}\n", FILE_APPEND); }; // $config-> ... = ... ;
设置
要使用创建的配置,可以将它设置为机器人类第二个参数
$bot = new Bot('__BOT_API_TOKEN__' , $config);
如果需要,也可以稍后更改
$config->throwOnError = true; // or $bot->config->throwOnError = true; $config->onLog = function (array $log) { $log = json_encode($log); file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND); }; // $bot->config->... = ...;
更新
有两种方式可以接收更新
在获取参数时,驼峰式和下划线没有区别
Webhook
如果您使用webhook,您可以使用'getUpdate'和'getInput'函数获取更新
https://core.telegram.org/bots/api#setwebhook
// Do not confuse this function with the 'getUpdates' method of Telegram, it is 'getupdate' $update = $bot->getUpdate(); // TelegramBotPHP\Types\Update Object ([updateId] => 585985242 [message] => TelegramBotPHP\Types\Message Object ( ... )) $update = $bot->getInput(); // Array ([update_id] => 585985243 [message] => Array ( ... ))
示例
$update = $bot->getUpdate(); // TelegramBotPHP\Types\Update Object ([updateId] => 585985242 [message] => TelegramBotPHP\Types\Message Object ( ... )) $messageId = $update->message->message_id; // 28236 // or $messageId = $update->message->messageId; // 28236 $text = $update->message->text; // Example Text // or $update = $bot->getInput(); // Array ([update_id] => 585985243 [message] => Array ( ... )) $messageId = $update['message']['message_id']; // 28236 $text = $update['message']['text']; // Example Text
获取更新
返回一个更新对象数组
https://core.telegram.org/bots/api#getupdates
$updates = $bot->getUpdates()->getResult();// Array ([0] => TelegramBotPHP\Types\Update Object ( ... ) [1] => TelegramBotPHP\Types\Update Object ( ... ) [2] => TelegramBotPHP\Types\Update Object ( ... ))
示例
$updates = $bot->getUpdates()->getResult();// Array ([0] => TelegramBotPHP\Types\Update Object ( ... ) [1] => TelegramBotPHP\Types\Update Object ( ... ) [2] => TelegramBotPHP\Types\Update Object ( ... )) foreach ($updates as $key => $update) { $chatId = $update->chat->id; // 184171927 // or you can create helper }
方法
要使用这些方法,您只需输入方法名,并传递Telegram API文档中列出的参数数组。
// now you can use all of telegram methods $bot->methodName([ // parameters 'example' => 'test', ]);
示例
// https://core.telegram.org/bots/api#available-methods // chat_id is Unique identifier for the target chat or username of the target channel (in the format @channelusername) // send message $bot->sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', ]); // send photo $bot->sendPhoto([ 'chat_id' => 184171927, 'photo' => new CURLFile('example.png'), 'caption' => 'Example caption', ]); // send document $bot->sendDocument([ 'chat_id' => 184171927, 'document' => new CURLFile('example.zip'), 'caption' => 'Example caption', ]); // ... // $bot->...([ // ... // ]);
您也可以使用静态
示例
// send message Bot::sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', ]); // send photo Bot::sendPhoto([ 'chat_id' => 184171927, 'photo' => new CURLFile('example.png'), 'caption' => 'Example caption', ]); // send document Bot::sendDocument([ 'chat_id' => 184171927, 'document' => new CURLFile('example.zip'), 'caption' => 'Example caption', ]);
也可以使用不同的BOT_API_TOKEN
您可以在每个方法的第二个参数中输入新的BOT_API_TOKEN
示例
// send message Bot::sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', ], '__BOT_API_TOKEN__');
键盘
InlineKeyboardMarkup
// send message $bot->sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', 'reply_markup' => [ 'inline_keyboard' => [ [['text' => 'one', 'callback_data' => 'one'], ['text' => 'two', 'callback_data' => 'two']], [['text' => 'three', 'callback_data' => 'three'], ['text' => 'four', 'callback_data' => 'four']], [['text' => 'url', 'url' => 'https://github.com/ErfanBahramali/Telegram-Bot-PHP']], ] ] ]);
ReplyKeyboardMarkup
// send message $bot->sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', 'reply_markup' => [ 'keyboard' => [ [['text' => 'one'], ['text' => 'two']], [['text' => 'three'], ['text' => 'four']], [['text' => 'request contact', 'request_contact' => true]], [['text' => 'request location', 'request_location' => true]], ], 'resize_keyboard' => true, ] ]);
ReplyKeyboardRemove
// send message $bot->sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', 'reply_markup' => [ 'remove_keyboard' => true ] ]);
ForceReply
// send message $bot->sendMessage([ 'chat_id' => 184171927, 'text' => 'Example Text', 'reply_markup' => [ 'force_reply' => true, 'input_field_placeholder' => 'test', ] ]);
响应
在获取参数时,驼峰式和下划线没有区别
获取响应
$response = $bot->methodName([ // parameters 'example' => 'test', ]); // (TelegramBotPHP\Response\Response Object( .... ))
结果
// { // "ok": true, // "result": { // "message_id": 28236, // "from": { // "id": 93372553, // "is_bot": true, // "first_name": "BotFather", // "username": "BotFather" // }, // "chat": { // "id": 184171927, // "first_name": "Erfan", // "type": "private" // }, // "date": 1627277790, // "text": "Example Text" // } // } $response->isOk(); // check response ok is true (true) $response->getResult(); // get response Result. The result is not always an object and may be an array and a bool (TelegramBotPHP\Types\Message Object([messageId] => 28236 [from] => TelegramBotPHP\Types\User Object( ... ) [date] => 1627277790[chat] => TelegramBotPHP\Types\Chat Object( ... )[text] => Example Text)) $response->getResponseData(); // get all of response as an array (Array ([ok] => 1 [result] => Array ( [message_id] => 28236 [from] => Array ( ... ) [chat] => Array ( ... ) [date] => 1627277790 [text] => Example Text )))
示例
$result = $response->getResult();// TelegramBotPHP\Types\Message Object( ... ) $messageId = $result->message_id; // 28236 $chatId = $result->chat->id; // 184171927 $text = $result->text; // Example Text // or in array $result = $response->getResponseData(); // Array ( ... ) $result = $result['result']; // Array ( ... ) $messageId = $result['message_id']; // 28236 $chatId = $result['chat']['id']; // 184171927 $text = $result['text']; // Example Text
错误
// { // "ok": false, // "error_code": 400, // "description": "Bad Request: chat not found" // } $response->getErrorCode(); // check response error_code (400) $response->getDescription(); // check response description ("Bad Request: chat not found")
请求
$response->getRequestMethod(); // get request method name (sendMessage) $response->getRequestParameters(); // get request parameters as an array (['chat_id' => '184171927', 'text' => 'Example Text'])
下载文件
// downloadFile($filePath, $localFilePath) // $fileSource = self::$config->botApiServerFileUrl . self::$token . '/' . $filePath; $bot->downloadFile('documents/example.txt', __DIR__ . '/documents/example.txt'); // $fileSource = self::$config->botApiServerFileUrl . self::$token . '/' . 'documents/example.txt'; // or Bot::downloadFile('documents/example.txt', __DIR__ . '/documents/example.txt');
通过file_id下载文件
// downloadFileByFileId($fileId, $localFilePath) $bot->downloadFileByFileId('BQACAgQAAxkBAAJ0T2EJUDHTeXGcSBUrqFMgzZCQ0OJGAAIhCQACg2tJUEqm6016cXE9IAQ', __DIR__ . '/documents/example.txt'); // or Bot::downloadFileByFileId('BQACAgQAAxkBAAJ0T2EJUDHTeXGcSBUrqFMgzZCQ0OJGAAIhCQACg2tJUEqm6016cXE9IAQ', __DIR__ . '/documents/example.txt');
助手
辅助函数是用于接收某些值或检查某些项目或执行某些任务的辅助函数
注意:您可以在辅助函数文件夹中看到完整的函数列表
在获取参数时,驼峰式和下划线没有区别
示例
$chatId = $bot->getHelper()->getChatId(); // or $chatId = Helper::getChatId(); // or $chatId = $bot->getUpdate()->message->chat->id;
您还可以使用输入更新数组创建新的辅助函数
$helper = new Helper({__Input_Update_Array__}); // Example: $helper = new Helper($bot->getInput());
当然,机器人会自动构建辅助函数,无需用其值构建辅助函数,您可以使用'getHelper'获取机器人辅助函数
示例
$helper = $bot->getHelper();
格式
Format类是一个帮助创建不同文本格式的类
https://core.telegram.org/bots/api#formatting-options
提及
您可以轻松提及用户
$text = Format::mention('184171927','Erfan'); // [Erfan](tg://user?id=184171927)
样式
// escape markdownV2 style $text = Format::markdownV2(''); // escape HTML style $text = Format::html(''); // escape markdown style $text = Format::markdown('');
示例
// escape markdownV2 style $text = Format::markdownV2('*bold \*text*'); // \*bold \\\*text\* // escape HTML style $text = Format::html('<b>bold</b>, <strong>bold</strong>'); // &lt;b&gt;bold&lt;/b&gt;, &lt;strong&gt;bold&lt;/strong&gt; // escape markdown style $text = Format::markdown('*bold text*'); // \*bold text\*
示例
$text = Format::markdownV2('*bold \*text*'); Bot::sendMessage([ 'chat_id' => '184171927', 'text' => "*{$text}*", 'parse_mode' => ParseMode::MARKDOWNV2, ]);
异常
您可以使用try catch管理错误
BotException: 用于异常处理的主体异常类
BotLogException: 用于日志的异常类
BotNotSupportException: 当功能不受支持时抛出的异常类
更新类型
如果您想检查更新的类型
您可以使用辅助函数
您可以在辅助类型类中查看'updateTypeIs...'函数的完整列表
示例
if (Helper::updateTypeIsMessage()) { # code... } elseif (Helper::updateTypeIsCallbackQuery()) { # code... } elseif (Helper::updateTypeIsMyChatMember()) { # code... } // or ... // Helper::updateTypeIs...()
或者
您可以使用'getUpdateType'辅助函数获取更新的类型,然后使用不同类型的更新进行检查
您可以在更新类型类中查看更新类型的完整列表
示例
$updateType = Helper::getUpdateType(); if ($updateType === UpdateType::MESSAGE) { } elseif ($updateType === UpdateType::EDITED_MESSAGE) { } elseif ($updateType === UpdateType::CALLBACK_QUERY) { }
聊天动作
您可以使用现有的聊天操作发送聊天操作
您可以在操作类中查看聊天操作的完整列表
示例
Bot::sendChatAction([ 'chat_id' => 184171927, 'action' => ChatAction::TYPING, ]); Bot::sendChatAction([ 'chat_id' => 184171927, 'action' => ChatAction::RECORD_VOICE, ]); Bot::sendChatAction([ 'chat_id' => 184171927, 'action' => ChatAction::FIND_LOCATION, ]);
示例
故障排除
请将您发现的任何错误在问题页面上报告。
关于我们
这个库可以用于轻松与Telegram Bot API交互
许可协议
Telegram-Bot-PHP在MIT许可证下授权 - 有关详细信息,请参阅LICENSE文件