botstan/api

该包已被废弃,不再维护。未建议替代包。

轻松使用Telegram机器人API。

1.6 2018-07-19 21:34 UTC

This package is not auto-updated.

Last update: 2018-11-25 10:50:06 UTC


README

Download Version API Version Stars

该API是一个基于HTTP的接口,专为热衷于为Telegram构建机器人的开发者创建。要了解如何创建和设置机器人,请参阅Telegram机器人简介机器人常见问题解答

要求

  1. PHP 5.5+
  2. Composer - PHP的依赖管理器
  3. yiisoft/yii2 - Yii PHP框架版本2
  4. 机器人令牌 - Telegram机器人API访问令牌

安装

通过Composer安装此包。编辑你的项目的composer.json文件,以要求"botstan/api": "*",或者在你的命令行中运行此命令

composer require botstan/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;
}

注意

直接使用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发送目前仅适用于 gifpdfzip 文件。
  • 要使用 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目前支持文本和表情符号作为您的按钮。

以下是一些自定义键盘示例

68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303138342f312f35594a78782d726f7374412f616433663734303934343835666239376264 68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303838302f312f6a532d5953566b44434e512f623339376466636566633664613064633730 68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303733332f322f4b6f7973714a4b515f6b492f613165653436613337373739366333393631

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按钮切换到内联按钮

68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303231372f312f4e6b5243434c65515a56632f313761383034383337383032373030656134 68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303635392f312f52524a79756c62744c42592f656136313633343131633765623466346463 68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303939392f312f324a536f55566c574b61302f346661643265323734336463386564613034

当使用回调按钮时,您的机器人可以更新其现有消息(或仅它们的键盘),以便聊天保持整洁。

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命令,并提供用户在输入字段中输入您的机器人名称后看到的占位文本。

68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303939352f312f492d7775627558416e7a6b2f326533393733396430616336626435343538

结果

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

68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303034392f322f4d326d7a716a5a6f6955772f326438373266306466326165643138326436 68747470733a2f2f636f72652e74656c656772616d2e6f72672f66696c652f3831313134303539322f322f50342d7446686d427343672f353734313861663038663161323532643435

每个查询的结果不得超过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许可发布。