PHP code example of alirezax5 / telegram-base

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

    

alirezax5 / telegram-base example snippets



namespace alirezax5\TelegramBase\Plugin;

use alirezax5\TelegramBase\App\Attributes\ChatType;
use alirezax5\TelegramBase\App\Plugin\Contract\PluginInterface;
use telegramBotApiPhp\Telegram;

#[ChatType(['private'])]
class greet implements PluginInterface
{
    public function getPriority(): int { return 10; }

    public function onMessage($message, Telegram $Telegram): void
    {
        $chatId = $Telegram->fromId();
        $text   = $message->text ?? '';

        if ($text === '/start') {
            $Telegram->sendMessage($chatId, "Welcome!");
        }
    }
}

#[ChatType(['private', 'group'])]  // Restrict to chat types

use alirezax5\TelegramBase\App\Session\SessionManager;

// Start or resume session
$session = SessionManager::start($chatId);

// Set / get values
$session->set('step', 'waiting_email');
$step = $session->get('step');

// Persist automatically; TTL set by SESSION_TTL in .env

use alirezax5\TelegramBase\App\Button\Keyboard;

// Inline keyboard
$kb = Keyboard::inline()
    ->button('Help', 'btn_help')
    ->button('Settings', 'btn_settings')
    ->row()
    ->button('Close', 'btn_close')
    ->toArray();

$Telegram->sendMessage($chatId, 'Choose:', ['reply_markup' => $kb]);

// Reply keyboard
$reply = Keyboard::reply()
    ->button('Option A')
    ->button('Option B')
    ->resize()
    ->oneTime()
    ->toArray();

// App/Middleware/Middlewares/RateLimitMiddleware.php
// Built-in: RateLimit, AuditLog, AdminGuard

// Custom middleware:
namespace alirezax5\TelegramBase\App\Middleware;

class MyMiddleware implements MiddlewareInterface {
    public function handle(mixed $update, \Closure $next, Telegram $tg): mixed {
        // pre-process
        $result = $next($update);
        // post-process
        return $result;
    }
}

$scheduler->call('prune_old_sessions', '0 3 * * *');  // daily at 3am
$scheduler->call('send_summary',      '*/5 * * * *'); // every 5 min


use alirezax5\TelegramBase\App\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

return new class extends Migration {
    public function up(\Illuminate\Database\Schema\Builder $schema): void {
        $schema->create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down(\Illuminate\Database\Schema\Builder $schema): void {
        $schema->dropIfExists('users');
    }
};
bash
* * * * * cd /path/to/project && php bin/scheduler.php