amemorypro/botstanapi

轻松使用telegram bot api。

dev-master 2023-12-15 12:22 UTC

This package is not auto-updated.

Last update: 2024-09-20 15:30:05 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文件,添加"amemorypro/botstanapi": "dev-master"。或者,在命令行中运行以下命令

composer require amemorypro/botstanapi

用法

使用此库最常见的方式是从API类创建一个新的对象,这允许您访问所有授权的Telegram方法。通过使用API类,还可以为您使用事件,在本文末尾已介绍如何使用它。

$token = '<token>';
$api = new \api\base\API($token);

请求

正如我们所说的,这个库是一个基于HTTP的接口,所有请求都使用POST方法发送。要创建一个简单的请求,您必须从请求类创建一个新的对象,并发送输入参数,如方法名称。

$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了。

响应

发送任何请求后,您将收到一个响应,即响应对象类型。要发送您在上一步骤中创建的请求,您必须使用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用于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目前支持文本和表情符号作为按钮。

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

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许可证发布。