vjik/telegram-bot-api

用于操作Telegram API的PHP库

0.4.3 2024-09-06 18:09 UTC

This package is auto-updated.

Last update: 2024-09-06 18:10:59 UTC


README

Latest Stable Version Total Downloads Build status Code coverage Mutation score static analysis

该软件包提供了一种简单便捷的方式与Telegram Bot API交互。

✔️ Telegram Bot API 7.10(2024年9月6日)完全支持。

要求

  • PHP 8.2或更高版本。

安装

该软件包可以使用 Composer 安装

composer require vjik/telegram-bot-api

通用用法

要向Telegram Bot API发送请求,您需要创建一个包含 TelegramClientInterface 实现的实例的 TelegramBotApi 类。该软件包提供了基于 PSR-18 HTTP客户端和 PSR-17 HTTP工厂的 PsrTelegramClient

例如,您可以使用 php-http/curl-clienthttpsoft/http-message

composer require php-http/curl-client httpsoft/http-message

在这种情况下,创建 TelegramBotApi 实例的方法如下

use Http\Client\Curl\Client;
use HttpSoft\Message\RequestFactory;
use HttpSoft\Message\ResponseFactory;
use HttpSoft\Message\StreamFactory;
use Vjik\TelegramBot\Api\Client\PsrTelegramClient;
use Vjik\TelegramBot\Api\TelegramBotApi;

// Telegram bot authentication token
$token = '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw';

// Dependencies
$streamFactory = new StreamFactory();
$responseFactory = new ResponseFactory();
$requestFactory = new RequestFactory();
$client = new Client($responseFactory, $streamFactory);

// API
$api = new TelegramBotApi(
    new PsrTelegramClient(
        $token,
        $client,
        $requestFactory,
        $streamFactory,
    ),
);

现在您可以使用 $api 实例与Telegram Bot API交互。方法名称与 Telegram Bot API文档 中的一致。例如

use Vjik\TelegramBot\Api\Type\InputFile

// Specify a URL for outgoing webhook
$api->setWebhook('https://example.com/webhook');

// Send text message
$api->sendMessage(
    chatId: 22351, 
    text: 'Hello, world!',
);

// Send local photo
$api->sendPhoto(
    chatId: 22351, 
    photo: InputFile::fromLocalFile('/path/to/photo.jpg'),
);

结果将是错误时的 FailResult 实例或成功时的对应类型对象。例如

// Result is an array of `Vjik\TelegramBot\Api\Update\Update` objects
$updates = $api->getUpdates();

文档

如果您对该软件包有任何疑问或问题,请使用 作者Telegram聊天 进行沟通。

许可

vjik/telegram-bot-api 是免费软件。它根据BSD许可证的条款发布。有关更多信息,请参阅 LICENSE

鸣谢

该软件包受到由 Botasis 创建并由 Viktor Babanov 初始创建的代码的启发。