PHP code example of uzdevid / php-telegram-bot

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

    

uzdevid / php-telegram-bot example snippets


$config = [
    'token' => '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', // Bot tokeni
];

$bot = new \uzdevid\telegram\bot\Bot($config);

use uzdevid\telegram\bot\message\messages\methods\SendMessage;

$bot->sender()
    ->chatId(123456789) // yoki ->username('@uzdevid')
    ->method(new SendMessage('Salom. Bu matnli habar'))
    ->send();

use uzdevid\telegram\bot\message\messages\methods\SendPhoto;

$sendPhoto = new SendPhoto('https://uzdevid.com/img/logo.png');
$sendPhoto->caption('Bu rasmli habar')->hasSpoiler();

$bot->sender()
    ->chatId(123456789)
    ->method($sendPhoto)
    ->send();

use uzdevid\telegram\bot\message\messages\methods\SendMessage;
use uzdevid\telegram\bot\message\messages\keyboard\reply\ReplyButton;
use uzdevid\telegram\bot\message\messages\keyboard\reply\ReplyKeyboardMarkup;
use uzdevid\telegram\bot\message\messages\keyboard\reply\ReplyRow;

$replyMarkup = new ReplyKeyboardMarkup();
$replyMarkup->resizeKeyboard()->addRow(
    (new ReplyRow())
        ->addButton(new ReplyButton('Tugma 1'))
        ->addButton((new ReplyButton('Joylashuv uchun tugma'))->requestLocation())
        ->addButton((new ReplyButton('Telefon raqam uchun tugma'))->requestContact())
);

$sendMessage = new SendMessage('Bu tugmali habar');
$sendMessage->addReplyMarkup($replyMarkup);

$bot->sender()
    ->chatId(123456789)
    ->method($sendMessage)
    ->send();

use uzdevid\telegram\bot\message\messages\methods\SendMessage;
use uzdevid\telegram\bot\message\messages\keyboard\reply\ReplyKeyboardRemove;

$sendMessage = new SendMessage('Bu oddiy habar');
$sendMessage->addReplyMarkup(new ReplyKeyboardRemove());

namespace App;

$requestBody = json_decode(file_get_contents('php://input'), true);

$bot->handler($requestBody)
    ->on(ChatStart::class)

namespace App\Handlers;

use uzdevid\telegram\bot\handler\updates\MessageUpdate;
use uzdevid\telegram\bot\handler\MessageUpdateInterface;
use uzdevid\telegram\bot\objects\Message;

class ChatStart extends MessageUpdate implements MessageUpdateInterface {
    public static function canHandle(Bot $bot, Message $message): bool {
        return $message->text == '/start';
    }
    
    public function handle(Bot $bot, Message $message): void {
        $bot->sender()
            ->chatId($message->chat->id)
            ->method(new SendMessage('Salom. Botga xush kelibsiz'))
            ->send();
    }
}
bash
composer