PHP code example of devrabie / php-telegram-bot-plus

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

    

devrabie / php-telegram-bot-plus example snippets




api_key  = 'YOUR_BOT_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';

$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

// Initialize the Redis client and make it available to all commands
// Default connection: 127.0.0.1:6379
$telegram->enableRedis();

// Or with custom connection parameters:
// $telegram->enableRedis([
//    'host'   => 'your-redis-host',
//    'port'   => 6379,
//    // 'password' => 'your-redis-password'
// ]);

// Handle updates
$telegram->handle();



namespace Longman\TelegramBot\Commands\UserCommands;

use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

class SettingsCommand extends UserCommand
{
    protected $name = 'settings';
    protected $description = 'Manage user settings using Redis';
    protected $usage = '/settings';
    protected $version = '1.0.0';

    /**
     * @var \Redis
     */
    protected $redis;

    public function execute()
    {
        $message = $this->getMessage();
        $chat_id = $message->getChat()->getId();

        if ($this->redis) {
            $settings_key = 'bot:settings:' . $chat_id;

            // Example: Use Redis to store custom settings for a chat
            $this->redis->hset($settings_key, 'language', 'en');
            $lang = $this->redis->hget($settings_key, 'language');

            $text = 'Language set to: ' . $lang . ' (using Redis!)';
        } else {
            $text = 'Redis is not enabled.';
        }

        return Request::sendMessage([
            'chat_id' => $chat_id,
            'text'    => $text,
        ]);
    }
}

$redis = \Longman\TelegramBot\Telegram::getRedis();

// Set retention time to 120 seconds
Longman\TelegramBot\Telegram::setUpdateRetentionTime(120);

use Longman\TelegramBot\Request;

// Set request timeout to 30 seconds
Request::setClientTimeout(30);

$telegram->setWebhook('https://your-domain.com/hook.php', [
    'secret_token' => 'YOUR_SECRET_TOKEN',
]);



api_key  = 'YOUR_BOT_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';
$bot_secret   = 'YOUR_SECRET_TOKEN';

try {
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

    // Set the secret token for incoming webhook requests
    $telegram->setSecretToken($bot_secret);

    // Handle the update
    $telegram->handle();

} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Log the error
    error_log($e->getMessage());
}