PHP code example of makhnanov / php-telegram-bot

1. Go to this page and download the library: Download makhnanov/php-telegram-bot 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/ */

    

makhnanov / php-telegram-bot example snippets




# hnanov\TelegramBot\Bot;

$bot = new Bot('ENTER-BOT-TOKEN-HERE');
# $secondBot = new Bot('BOT_TOKEN'); # For another bot

# $bot = bot(); # Automatically gets TELEGRAM_BOT_TOKEN from env and make single global instance

# $chatId = 'ENTER_CHAT_ID_HERE_FOR_GET_FIRST_MESSAGES';

# $bot->sendMessage(chatId: $chatId, text: 'Hello, World!');
# $bot->sendMessage(
#     chatId: $chatId,
#     text: '<b>Bold</b> and <i>italic</i>',
#     parseMode: 'HTML',
# );

# Simple Echo Long Polling
foreach ($bot->poll() as $update) {
    if ($update->message?->text === '/start') {
        $bot->sendMessage(
            chatId: $update->message->chat->id,
            text: 'Welcome!',
        );
    } elseif ($update->message?->text) {
        $bot->sendMessage(
            chatId: $update->message->chat->id,
            text: $update->message->text,
        );
    } else {
        $bot->sendMessage(
            chatId: $update->message->chat->id,
            text: 'Not simple message!',
        );
    }
}

# ToDo: think about catch exceptions & $allowedUpdates

$bot = new Bot('TOKEN');
$bot->sendMessage(chatId: 123, text: 'Hello');

// Named arguments instead of parameter arrays
$bot->sendMessage(
    chatId: $chatId,
    text: 'Hello',
    parseMode: 'HTML',
    disableNotification: true,
);

bot()->sendMessage(chatId: 123, text: 'Quick message');

readonly class Message {
    public function __construct(
        public int $messageId,
        public ?User $from,
        public Chat $chat,
        public int $date,
        public ?string $text,
        // ...
    ) {}
}

class Bot {
    use SendMessageTrait;
    use SendPhotoTrait;
    use GetUpdatesTrait;
    // ...
}

bot()
    ->sendMessage(chatId: 123, text: 'First')
    ->sendMessage(chatId: 123, text: 'Second');
shell
composer 

Src/
├── Bot.php              # Main class, entry point
├── Functions.php        # Global helper bot()
├── Api.php              # HTTP client for API requests
├── Method/              # API methods (traits for Bot)
│   ├── SendMessage.php
│   ├── SendPhoto.php
│   ├── GetUpdates.php
│   └── ...
└── Type/                # Data types (DTO)
    ├── Message.php
    ├── Update.php
    ├── Chat.php
    ├── User.php
    └── ...