1. Go to this page and download the library: Download phenogram/bindings library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
declare(strict_types=1);
namespace Phenogram\Bindings\Tests\Readme;
use Phenogram\Bindings\ClientInterface;
use Phenogram\Bindings\Types;
final readonly class ReadmeLocalFile implements Types\Interfaces\InputFileInterface
{
public function __construct(
public string $filePath
) {}
}
final readonly class ReadmeClient implements ClientInterface
{
public function __construct(
private string $token,
private string $apiUrl = 'https://api.telegram.org',
) {
}
public function sendRequest(string $method, array $data): Types\Interfaces\ResponseInterface
{
$ch = curl_init("{$this->apiUrl}/bot{$this->token}/{$method}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach ($data as $key => $value) {
if ($value instanceof ReadmeLocalFile) {
if (!file_exists($value->filePath)) {
throw new \RuntimeException("File not found: {$value->filePath}");
}
$data[$key] = new \CURLFile($value->filePath);
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new \RuntimeException('Request Error: ' . curl_error($ch));
}
curl_close($ch);
$responseData = json_decode($response, true);
if (!isset($responseData['ok']) || !isset($responseData['result'])) {
return new Types\Response(
ok: false,
errorCode: $responseData['error_code'] ?? null,
description: $responseData['description'] ?? null,
parameters: isset($responseData['parameters']) ? new Types\ResponseParameters(
migrateToChatId: $responseData['parameters']['migrate_to_chat_id'] ?? null,
retryAfter: $responseData['parameters']['retry_after'] ?? null,
) : null,
);
}
return new Types\Response(
ok: $responseData['ok'],
result: $responseData['result'],
errorCode: $responseData['error_code'] ?? null,
description: $responseData['description'] ?? null,
parameters: isset($responseData['parameters']) ? new Types\ResponseParameters(
migrateToChatId: $responseData['parameters']['migrate_to_chat_id'] ?? null,
retryAfter: $responseData['parameters']['retry_after'] ?? null,
) : null,
);
}
}
$api = new Api(
client: new TelegramBotApiClient($token),
serializer: new Serializer(),
);
$me = $api->getMe();
assert($me instanceof User::class);
class MyChatLocation extends \Phenogram\Bindings\Types\ChatLocation
{
public string $address {
get => $this->normalizeAddress($this->address);
}
private function normalizeAddress(string $address): string
{
return mb_strtoupper($address);
}
}
use Phenogram\Bindings\Factory;
use Phenogram\Bindings\Types\Interfaces\ChatLocationInterface;
use Phenogram\Bindings\Types\Interfaces\LocationInterface;
class MyFactory extends Factory
{
public function makeChatLocation(
LocationInterface $location,
string $address
): ChatLocationInterface
{
return new MyChatLocation(
location: $location,
address: $address,
);
}
}
$api = new Api(
client: new TelegramBotApiClient($token),
serializer: new Serializer(
factory: new MyFactory()
),
);
use Phenogram\Bindings\Factories\UserFactory;
use Phenogram\Bindings\Factories\MessageFactory;
use Phenogram\Bindings\Types\Interfaces\UserInterface;
use Phenogram\Bindings\Types\Interfaces\MessageInterface;
// Создать пользователя со случайными данными
$randomUser = UserFactory::make();
assert($randomUser instanceof UserInterface);
echo "Создан пользователь: ID=" . $randomUser->id . ", Имя=" . $randomUser->firstName . "\n";
// Создать другого пользователя, указав ID и флаг бота
$specificBot = UserFactory::make(id: 12345, isBot: true);
echo "Создан бот: ID=" . $specificBot->id . ", Имя=" . $specificBot->firstName . "\n";
// Создать сообщение, указав некоторые параметры и оставив остальные случайными
$messageFromBot = MessageFactory::make(
from: UserFactory::make(
isBot: true,
firstName: 'MyTestBot'
), // Вложенный вызов фабрики
text: 'Привет из теста!'
);
assert($messageFromBot instanceof MessageInterface);
echo "ID сообщения: " . $messageFromBot->messageId . "\n";
echo "Текст: " . $messageFromBot->text . "\n";
echo "Отправитель: " . $messageFromBot->from->firstName . "\n";
echo "ID чата: " . $messageFromBot->chat->id . "\n"; // Chat также сгенерирован автоматически
// Создать массив случайных сущностей сообщения (MessageEntity)
use Phenogram\Bindings\Factories\MessageEntityFactory;
use Phenogram\Bindings\Types\Interfaces\MessageEntityInterface;
$entities = array_map(fn() => MessageEntityFactory::make(), range(1, 3));
assert(is_array($entities));
assert($entities[0] instanceof MessageEntityInterface);
echo "Сгенерировано сущностей: " . count($entities) . "\n";
echo "Тип первой сущности: " . $entities[0]->type . "\n";