PHP code example of uzdevid / yii2-telegram-bot

1. Go to this page and download the library: Download uzdevid/yii2-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 / yii2-telegram-bot example snippets


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

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

use uzdevid\telegram\bot\Message\Message\Method\SendMessage;

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

use uzdevid\telegram\bot\Message\Message\Method\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\Message\Method\SendMessage;
use uzdevid\telegram\bot\Message\Message\Keyboard\reply\ReplyButton;
use uzdevid\telegram\bot\Message\Message\Keyboard\reply\ReplyKeyboardMarkup;
use uzdevid\telegram\bot\Message\Message\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\Message\Method\SendMessage;
use uzdevid\telegram\bot\Message\Message\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\update\Message\MessageUpdate;use uzdevid\telegram\bot\Handler\update\Message\MessageUpdateInterface;use uzdevid\telegram\bot\Type\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