vorona-yurii / botstanapi
轻松使用telegram bot api。
Requires
- php: >=5.5.0
- yiisoft/yii2: >=2.0.5
This package is auto-updated.
Last update: 2024-09-15 14:27:37 UTC
README
该API是一个基于HTTP的接口,专为希望为Telegram构建机器人的开发者创建。要了解如何创建和设置机器人,请参阅Telegram机器人简介和机器人常见问题解答。
要求
- PHP 5.5+
- Composer - PHP的依赖管理器
- yiisoft/yii2 - Yii PHP框架版本2
- 机器人令牌 - Telegram机器人API访问令牌
安装
通过 Composer 安装此包。编辑你的项目 composer.json
文件以要求 "vorona-yurii/botstanapi": "dev-master"
。或者在你的命令行中运行此命令
composer require vorona-yurii/botstanapi
用法
使用此库最常见的方式是从API类创建一个新对象,这允许你访问所有授权的Telegram方法。通过使用API类,你也可以使用事件,本文末尾将介绍如何使用它。
$token = '<token>'; $api = new \api\base\API($token);
请求
正如我们所说,此库是一个基于HTTP的接口,所有请求都使用 POST 方法发送。要创建一个简单的请求,你必须从Request类创建一个新的对象,并发送输入参数,例如方法名。
$request = new \api\base\Request($token, [ 'method' => 'sendMessage', 'chat_id' => '<chat_id>', 'text' => 'Hello !!' ]);
你不需要以这种方式创建自己的请求,你可以使用之前创建API类时使用的同一个对象。我们已经为你准备了Telegram文档中的所有方法。
$request = $api->sendMessage(); $request->chat_id = '<chat_id>'; $request->text = 'Hello !!';
在发送你的所需参数之后,你的请求对象就准备好了,可以发送到Telegram。
响应
发送任何请求后,你会收到一个响应,这是一个Response对象类型。要发送你在上一步创建的请求,你必须使用 send()
方法,并将响应保存在一个变量中。
$response = $request->send();
根据Telegram文档关于发送消息的说明,发送消息后,你会收到一个类似于Message对象的响应。在响应对象中,你可以使用 has<Field>()
方法验证字段,并使用 get<Field>()
获取字段的值。
if ($response instanceof \api\response\Message) { // request succeed if ($response->hasText()) $text = $response->getText(); // OR // if (isset($response->text)) // $text = $response->text; }
注意
使用Request对象直接发出的任何请求都将发送数组响应,而不是对象。
方法
我们将支持所有已在Telegram文档中列出的方法。你可以通过 src\methods
访问它们,如果你愿意,还可以编辑它们。API中的所有方法都不区分大小写。我们只支持 POST HTTP方法,并将使用 multipart/form-data
将文件传递到Telegram服务器。
发送文件
通过 file_id
如果文件已存储在Telegram服务器上,则不需要重新上传:每个文件对象都有一个 file_id 字段,只需将这个 file_id 作为参数传递即可,而不是上传。这种方式发送的文件没有 限制。
$request = $api->sendPhoto(); $request->chat_id = '<chat_id>'; $request->caption = 'sent by file_id.'; $request->photo = 'AgADBAADXME4GxQXZAc6zkxv265UJKGYEAAEC'; $request->send();
注意
file_id 对于每个机器人是唯一的,并且不能从一个机器人转移到另一个机器人。
通过 URL
为Telegram提供一个要发送的文件的HTTP URL。Telegram将下载并发送文件。照片最大5MB,其他类型的内容最大20MB。
- 通过URL发送时,目标文件必须具有正确的MIME类型(例如,
audio/mpeg
用于sendAudio等)。 - 在sendDocument中,通过URL发送目前仅适用于gif、pdf和zip文件。
- 要使用sendVoice,文件类型必须是
audio/ogg
且大小不超过1MB。1-20MB的语音笔记将作为文件发送。 - 其他配置可能有效,但我们无法保证。
$request = $api->sendPhoto(); $request->chat_id = '<chat_id>'; $request->caption = 'sent by url.'; $request->photo = 'http://example.com/photos/dogs.jpg'; $request->send();
通过InputFile
此对象表示要上传的文件的内容。必须使用multipart/form-data
以通常方式(如同浏览器上传文件的方式)提交。
$request = $api->sendPhoto(); $request->chat_id = '<chat_id>'; $request->caption = 'sent by InputFile.'; $request->photo = new \api\InputFile('@photos/cats.jpg'); $request->send();
键盘
当然,传统的聊天机器人可以教会它们理解人类语言。但有时您可能需要用户输入更正式的内容——这就是自定义键盘变得极其有用的地方。
$request->reply_markup = $markup;
回复键盘
无论您的机器人发送什么消息,它都可以传递一个包含预定义回复选项的特殊键盘(见ReplyKeyboardMarkup)。接收消息的Telegram应用将向用户显示键盘。点击任何按钮将立即发送相应的命令。这样您可以极大地简化用户与机器人的交互。Telegram目前支持文本和emoji作为您的按钮。
以下是一些自定义键盘的示例
use api\keyboard\ReplyKeyboardMarkup; use api\keyboard\button\KeyboardButton; // Keyboard plan $markup = new ReplyKeyboardMarkup(); $markup->resize_keyboard = true; // button for request user location $locationBtn = new KeyboardButton(); $locationBtn->text = 'Send your location'; $locationBtn->request_location = true; $markup->addButton($locationBtn, 1); // button for request user phone number $NumberBtn = new KeyboardButton(); $NumberBtn->text = 'Send your phone number'; $NumberBtn->request_contact = true; $markup->addButton($NumberBtn, 2);
内嵌键盘
有时您可能希望在不发送任何消息到聊天的情况下进行操作。例如,当用户正在更改设置或翻阅搜索结果时。在这种情况下,您可以使用内嵌键盘,它直接集成到它们所属的消息中。
与自定义回复键盘不同,按下内嵌键盘上的按钮不会导致发送消息到聊天。相反,内嵌键盘支持在幕后工作的按钮:回调按钮、URL按钮和切换到内嵌按钮。
当使用回调按钮时,您的机器人可以更新其现有消息(或只是它们的键盘),以便聊天保持整洁。
use api\keyboard\InlineKeyboardMarkup; use api\keyboard\button\InlineKeyboardButton; // Keyboard plan $markup = new InlineKeyboardMarkup(); // url button $urlBtn = new InlineKeyboardButton(); $urlBtn->text = 'Go to Google'; $urlBtn->url = 'https://google.com'; $markup->addButton($urlBtn, 1, 1); // callback button $callbackBtn = new InlineKeyboardButton(); $callbackBtn->text = 'Callback Btn'; $callbackBtn->callback_data = 'onclickCallbackBtn'; $markup->addButton($callbackBtn, 1, 2); // switch button $switchBtn = new InlineKeyboardButton(); $switchBtn->text = 'Switch to ...'; $switchBtn->switch_inline_query = 'my query'; $markup->addButton($switchBtn, 2);
内嵌模式
以下方法和对象允许您的机器人在内嵌模式下工作。请参阅Telegram 内嵌机器人介绍以获取更多详细信息。要启用此选项,向@BotFather发送/setinline
命令,并提供用户在输入字段中看到占位文本。
结果
InlineQueryResult
对象代表内嵌查询的一个结果。Telegram客户端目前支持以下20种类型的结果,您可以通过src\inline
找到它们并编辑。
$article = new \api\inline\InlineQueryResultArticle(); $article->id = 'result_1'; $article->title = 'Article'; $article->description = 'This is a article result.'; $input = new \api\input\InputTextMessageContent(); $input->message_text = '*Hello* my friend.'; $input->parse_mode = \api\ParseMode::MARKDOWN; $article->input_message_content = $input; $results[] = $article;
对查询的回复
使用answerInlineQuery
方法向内嵌查询发送答案。成功时返回True。
每个查询的结果不超过50个。
$getUpdates = $api->getUpdates(); $getUpdates->limit = 1; $getUpdates->allowed_updates = ['inline_query']; $updates = $getUpdates->send(); if (sizeof($updates) == 1) { $inlineQuery = $updates[0]; $request = $api->answerInlineQuery(); $request->results = $results; $request->inline_query_id = $inlineQuery->id; $response = $request->send(); }
辅助工具
动作
聊天动作允许您根据用户即将接收的内容类型广播一种动作。状态设置为5秒或更短(当从您的机器人收到消息时,Telegram客户端清除其输入状态)。
$request = $api->sendChatAction(); $request->chat_id = '<chat_id>'; $request->action = \api\Actions::TYPING; $request->send();
格式化
Bot API 支持消息的基本格式化。您可以在消息中使用粗体和斜体文本,以及内联链接和预格式化代码。Telegram 客户端将相应地渲染它们。您可以使用 Markdown 风格或 HTML 风格的格式化。
注意
在打开内联链接之前,Telegram 客户端将向用户显示一个警报(“打开此链接?”以及完整的 URL)。
$request = $api->sendMessage(); $request->text = '*bold text*'; $request->chat_id = '<chat_id>'; $request->parse_mode = \api\ParseMode::MARKDOWN; $response = $request->send(); if ($response instanceof \api\response\Error) { // request failed }
事件
对于想要制作更好、更有效的开发者,我们在本库中也包含了事件,以便我们可以完全访问接收到的所有请求、响应以及错误。
API 对象有四个事件
- AfterSend -
API::EVENT_AFTER_SEND
- BeforeSend -
API::EVENT_BEFORE_SEND
- RequestFailed -
API::EVENT_REQUEST_FAILED
- RequestSucceed -
API::EVENT_REQUEST_SUCCEED
use api\method\sendMessage; use api\event\RequestFailed; API::on(API::EVENT_REQUEST_FAILED, function (RequestFailed $event) { $error = $event->error; $method = $event->method; $code = $error->error_code; $description = $error->description; $message = '[' . $code . '] ' . $description; if ($method->has('chat_id')) { $token = $event->token; $chat_id = $method->get('chat_id'); (new sendMessage($token)) ->setChatId($chat_id) ->setText($message) ->send(); } });
免责声明
本项目及其作者与 Telegram 没有任何关联或隶属关系。
许可
本项目遵循 MIT 许可证 发布。