jaykee1 / api
轻松使用telegram bot api。
Requires
- yiisoft/yii2: *
This package is not auto-updated.
Last update: 2024-09-27 07:27:37 UTC
README
此API是一个基于HTTP的接口,专为喜欢为Telegram构建机器人的开发者创建。要了解如何创建和设置机器人,请参阅Telegram机器人生入门和机器人常见问题解答。
要求
- PHP 5.5+
- Composer - PHP依赖管理器
- yiisoft/yii2 - Yii PHP框架版本2
- 机器人令牌 - Telegram机器人API访问令牌
安装
通过Composer安装此包。编辑您的项目composer.json
文件以要求"jaykee1/api": "*"
。或者,在您的命令行中运行此命令
composer require jaykee1/api
用法
使用此库最常见的方法是从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; }
注意
使用请求对象直接发出的任何请求都将发送一个数组响应,而不是对象。
方法
我们将支持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
用于发送音频等)。 - 在发送文档中,通过URL发送目前仅适用于gif、pdf和zip文件。
- 要使用发送语音,文件类型必须是
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目前支持文本和表情符号作为按钮。
以下是一些自定义键盘示例
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();
格式化
机器人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许可证发布。