fardadev/telegram-objects-php 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fardadev/telegram-objects-php

最新稳定版本:v0.1.0-beta

Composer 安装命令:

composer require fardadev/telegram-objects-php

包简介

Framework-agnostic PHP library providing strongly-typed Telegram Bot API DTOs and objects

README 文档

README

Tests Coverage Security PHP Version License

A solid foundation for building Telegram bots in PHP.

This library provides strongly-typed, immutable DTOs (Data Transfer Objects) for the Telegram Bot API. It's designed as a base layer that other PHP libraries and frameworks can build upon, offering robust object representations without magic methods or dynamic properties.

Why This Library?

For Library Authors:

  • Build your Telegram bot framework on a solid, type-safe foundation
  • No need to reimplement DTOs - focus on your unique features
  • Stable API that follows Telegram's official types

For Bot Developers:

  • 🚀 Zero Dependencies - No framework lock-in, works anywhere
  • 💪 Type-Safe - Full PHP 8.1+ strict typing with readonly properties
  • 📦 Complete - 37 DTOs, 5 enums, 4 keyboard builders, 6 exceptions
  • ✅ Well-Tested - 506 tests with comprehensive coverage
  • 🎯 Modern PHP - Uses enums, match expressions, named arguments
  • 📖 Well-Documented - Extensive docs and working examples

Installation

composer require fardadev/telegram-objects-php

Requirements: PHP 8.1+

Quick Start

Parse Telegram Webhooks

use Telegram\Objects\DTO\TelegramUpdate;

// Parse incoming webhook
$update = TelegramUpdate::fromArray(
    json_decode(file_get_contents('php://input'), true)
);

// Access message data
if ($update->message()) {
    $text = $update->message()->text();
    $user = $update->message()->from();
    
    echo "{$user->firstName()}: {$text}";
}

// Handle button clicks
if ($update->callbackQuery()) {
    $data = $update->callbackQuery()->data();
    $user = $update->callbackQuery()->from();
    
    echo "{$user->firstName()} clicked: {$data}";
}

Create DTOs

use Telegram\Objects\DTO\User;
use Telegram\Objects\DTO\Message;

// From array (Telegram API response)
$user = User::fromArray([
    'id' => 123456789,
    'first_name' => 'John',
    'last_name' => 'Doe',
    'username' => 'johndoe',
    'is_bot' => false
]);

// Access properties
echo $user->fullName();  // "John Doe"
echo $user->id();        // 123456789
echo $user->isBot();     // false

// Convert back to array
$array = $user->toArray();

Build Keyboards

use Telegram\Objects\Keyboard\Keyboard;
use Telegram\Objects\Keyboard\Button;

// Inline keyboard
$keyboard = Keyboard::make()
    ->row([
        Button::make('Visit Site')->url('https://example.com'),
        Button::make('Contact')->action('contact_support')
    ])
    ->row([
        Button::make('Settings')->action('settings')
    ]);

// Use in Telegram API request
$response = [
    'chat_id' => $chatId,
    'text' => 'Choose an option:',
    'reply_markup' => [
        'inline_keyboard' => $keyboard->toArray()
    ]
];
use Telegram\Objects\Keyboard\ReplyKeyboard;
use Telegram\Objects\Keyboard\ReplyButton;

// Reply keyboard
$keyboard = ReplyKeyboard::make()
    ->row([
        ReplyButton::make('📱 Share Contact')->requestContact(),
        ReplyButton::make('📍 Share Location')->requestLocation()
    ])
    ->resize()
    ->oneTime();

// Use in Telegram API request
$response = [
    'chat_id' => $chatId,
    'text' => 'Share your info:',
    'reply_markup' => $keyboard->toArray()
];

What's Included

37 Data Transfer Objects

Core: TelegramUpdate, Message, User, Chat
Media: Photo, Video, Audio, Voice, Document, Animation, Sticker
Interactive: CallbackQuery, InlineQuery, Poll, PollAnswer
Payments: Invoice, SuccessfulPayment, PreCheckoutQuery
Admin: ChatMember, ChatInviteLink, ChatJoinRequest
More: Location, Contact, Venue, Entity, Reaction, and more

See full list →

5 Enums

use Telegram\Objects\Enums\ChatActions;
use Telegram\Objects\Enums\ChatPermissions;
use Telegram\Objects\Enums\Emojis;

ChatActions::TYPING;
ChatPermissions::CAN_SEND_MESSAGES;
Emojis::THUMBS_UP;

4 Keyboard Builders

  • Keyboard - Inline keyboards with callbacks, URLs, web apps
  • Button - Inline keyboard buttons
  • ReplyKeyboard - Reply keyboards with custom buttons
  • ReplyButton - Reply keyboard buttons with special requests

6 Exception Types

use Telegram\Objects\Exceptions\ValidationException;
use Telegram\Objects\Exceptions\TelegramException;

try {
    $user = User::fromArray($data);
} catch (ValidationException $e) {
    // Handle validation errors
}

Documentation

Examples

Check the examples/ directory for complete working examples:

Testing

# Run all tests
composer test

# Run specific tests
composer test:unit      # Unit tests
composer test:types     # Static analysis (PHPStan level 8)
composer test:lint      # Code style (PSR-12)

# Generate coverage
composer coverage

Features

Type Safety

// Full IDE autocompletion and type checking
$update = TelegramUpdate::fromArray($data);
$messageId = $update->message()?->id();        // int|null
$text = $update->message()?->text();           // string
$userId = $update->message()?->from()?->id();  // int|null

Immutability

All DTOs are immutable (readonly properties) - safe for concurrent use.

Validation

Built-in validation when creating from arrays:

// Throws ValidationException if required fields missing
$message = Message::fromArray($data);

Framework Agnostic

Works with any PHP framework or vanilla PHP:

  • ✅ Laravel
  • ✅ Symfony
  • ✅ Slim
  • ✅ Pure PHP
  • ✅ Any framework

Attribution

Inspired by and adapted from DefStudio/Telegraph, chosen for its robust DTO architecture that avoids magic methods and dynamic properties in favor of explicit, type-safe objects.

All source files include proper attribution headers tracking the original Telegraph files and commit hashes. Development assisted by Kiro AI IDE.

License

MIT License - see LICENSE file.

Support

Made with ❤️ by FardaDev

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-07