PHP code example of koot-labs / telegram-bot-dialogs
1. Go to this page and download the library: Download koot-labs/telegram-bot-dialogs 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/ */
koot-labs / telegram-bot-dialogs example snippets
use KootLabs\TelegramBotDialogs\Dialog;
use Telegram\Bot\Objects\Update;
final class HelloDialog extends Dialog
{
/** @var list<string> List of method to execute. The order defines the sequence */
protected array $steps = ['sayHello', 'sayOk'];
public function sayHello(Update $update): void
{
$this->bot->sendMessage([
'chat_id' => $this->getChatId(),
'text' => 'Hello! How are you?',
]);
}
public function sayOk(Update $update): void
{
$this->bot->sendMessage([
'chat_id' => $this->getChatId(),
'text' => 'I’m also OK :)',
]);
$this->nextStep('sayHello');
}
}
use App\Dialogs\HelloDialog;
use KootLabs\TelegramBotDialogs\Laravel\Facades\Dialogs;
use Telegram\Bot\Commands\Command;
final class HelloCommand extends Command
{
protected $name = 'hello';
protected $description = 'Start a hello dialog';
public function handle(): void
{
Dialogs::activate(new HelloDialog($this->update->getChat()->id));
}
}
use Telegram\Bot\BotsManager;
use KootLabs\TelegramBotDialogs\DialogManager;
final class TelegramWebhookHandler
{
public function handle(DialogManager $dialogs, BotsManager $botsManager): void
{
// Find a \Telegram\Bot\Commands\Command instance for the Update and execute it
// for /hello command, it should call HelloCommand that will activate HelloDialog
$update = $bot->commandsHandler(true);
$dialogs->hasActiveDialog($update)
? $dialogs->processUpdate($update) // Run the next step of the active dialog
: $botsManager->sendMessage([ // send a fallback message
'chat_id' => $update->getChat()->id,
'text' => 'No active dialog. Type /hello to start.',
]);
}
}
abstract class Dialog
{
// Navigation
public function nextStep(string $stepName): void;
public function switch(string $stepName): void;
public function complete(): void;
// State Management
public function isAtStart(): bool;
public function isLastStep(): bool;
public function isCompleted(): bool;
// Lifecycle Hooks
protected function beforeEveryStep(Update $update, int $stepIndex): void;
protected function afterEveryStep(Update $update, int $stepIndex): void;
protected function beforeFirstStep(Update $update): void;
protected function afterLastStep(Update $update): void;
// Properties Access
public function getChatId(): int;
public function getUserId(): ?int;
public function getTtl(): ?int;
}
use KootLabs\TelegramBotDialogs\Laravel\Facades\Dialogs;
// Activate a dialog
Dialogs::activate($dialog);
// Process an update
Dialogs::processUpdate($update);
// Check for active dialog
Dialogs::hasActiveDialog($update);
// Set custom bot instance
Dialogs::setBot($bot);