Configuration
tueen/telegram features an immutable configuration architecture paired with an expressive, fluent ConfigBuilder. Every parameter — from networking timeouts and persistent connection pooling to progress event hooks, running modes, and error handling strategies — is strictly typed and discoverable via IDE autocompletion.
🛠️ 1. Creating Configuration
You can configure the client using Telegram::create('TOKEN'), Config::builder('TOKEN'), or by instantiating Config directly:
Fluent Builder via Telegram::create()
The recommended and most expressive approach:
use Tueen\Telegram\Telegram;
use Tueen\Telegram\Enums\ErrorHandlingMode;
use Tueen\Telegram\Running\WebhookMode;
$config = Telegram::create('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')
->withTimeout(30.0)
->withConnectTimeout(10.0)
->withProxy('http://127.0.0.1:10809')
->withRetryCount(3)
->withErrorObjectMode()
->withRunningMode(new WebhookMode(secretToken: 'my_super_secret_token'))
->build();
$bot = new Telegram($config);Direct Instantiation of Config
For configuration files or dependency injection factories:
use Tueen\Telegram\Config;
$config = new Config(
botToken: 'YOUR_BOT_TOKEN',
timeout: 45.0,
connectTimeout: 5.0,
retryCount: 5,
testEnvironment: false
);
$bot = new Telegram($config);🧭 2. Detailed Configuration Reference
Below is the exhaustive catalog of all configuration options available on ConfigBuilder and Config.
🌐 Server & Credentials
withToken(string $token)staticdefault: ''withApiServer(string $url)staticdefault: 'https://api.telegram.org'withTestEnvironment(bool $enabled = true)staticdefault: false⚡ HTTP Client, Networking & Transport
withTimeout(float $seconds)staticdefault: 30.0withConnectTimeout(float $seconds)staticdefault: 10.0withProxy(?string $proxy)staticdefault: nullwithVerifySsl(bool|string $verifySsl = true)staticdefault: falsewithHttpClient(?HttpClientInterface $client)staticdefault: GuzzleHttpClientwithCurlClient(bool $persistent = true)staticdefault: true📊 Progress Tracking Callbacks
withUploadProgress(?Closure $callback)staticdefault: nullwithDownloadProgress(?Closure $callback)staticdefault: nullProgress Callback Signature
Both progress callbacks receive three informative parameters:
$config = Telegram::create('YOUR_TOKEN')
->withUploadProgress(function (int $bytesUploaded, int $totalBytes, float $percentage): void {
printf("Uploading: %5.1f%% (%d / %d bytes)\r", $percentage, $bytesUploaded, $totalBytes);
})
->withDownloadProgress(function (int $bytesDownloaded, int $totalBytes, float $percentage): void {
printf("Downloading: %5.1f%% (%d / %d bytes)\r", $percentage, $bytesDownloaded, $totalBytes);
})
->build();🛡️ Error Handling Strategy
withErrorHandlingMode(ErrorHandlingMode $mode)staticdefault: EXCEPTIONwithErrorObjectMode(array $catchExceptions = [ApiException::class])withExceptionMode()staticmode: exceptionwithCatchAllErrors()staticmode: catch-allwithConvertExceptions(array $classes)staticlist<class-string<Throwable>>🚀 Running Modes & Resiliency
withRunningMode(?RunningModeInterface $mode)staticdefault: WebhookModewithPollingMode(PollingMode $mode)staticPollingModewithWebhookMode(WebhookMode $mode)staticWebhookModewithAutoMode(?PollingMode $polling = null, ?WebhookMode $webhook = null, bool $autoDeleteWebhook = false, bool $dropPendingUpdatesOnDelete = false, ?callable $detector = null)staticAutoModewithRetryCount(int $count)staticdefault: 3🔄 Conversation Flow & Orchestration
withRootFlow(?string $flowClass)static?class-string<Flow>withDefaultFlow(?string $flowClass)staticAliaswithFlowAllowedUpdates(array $types)staticdefault: [] (all updates)📋 Logging & Observability
withLogger(?LoggerInterface $logger)staticdefault: null💉 Dependency Injection & Container
withContainer(mixed $container)staticPSR-11 / callable⚡ Client Instantiation Shortcuts
client()TelegramFactorymake()TelegramAlias🧬 3. Immutability & Modern PHP 8.5 Patterns
The Config class is completely immutable. Every with...() method creates and returns a clean new instance using PHP 8.5's clone with and #[\NoDiscard] attributes:
$baseConfig = Telegram::create('YOUR_TOKEN')
->withTimeout(30.0)
->build();
// Derive a specialized configuration without modifying $baseConfig:
$fastConfig = $baseConfig
->withTimeout(5.0)
->withRetryCount(1);
// $baseConfig->timeout remains 30.0
// $fastConfig->timeout is 5.0🌐 4. Standard URI & URL Resolution Properties
Config provides convenient properties powered by PHP 8.4 property hooks to resolve target URLs and standards-compliant Uri\Rfc3986\Uri objects:
public string $baseApiUrlstringProperty Hookpublic string $baseFileUrlstringProperty Hookpublic Uri|string $apiUriUri|stringProperty Hookpublic Uri|string $fileUriUri|stringProperty Hook$config = Telegram::create('123456:ABC')->build();
echo $config->baseApiUrl;
// "https://api.telegram.org/bot123456:ABC"
$uri = $config->apiUri;
echo $uri->getHost(); // "api.telegram.org"
echo $uri->getPath(); // "/bot123456:ABC"💡 5. Real-World Configuration Recipes
Recipe 1: Production Webhook with Persistent cURL & Monolog
use Tueen\Telegram\Telegram;
use Tueen\Telegram\Running\WebhookMode;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('telegram');
$logger->pushHandler(new StreamHandler(storage_path('logs/telegram.log')));
$config = Telegram::create($_ENV['TELEGRAM_BOT_TOKEN'])
// High-performance persistent cURL handles
->withCurlClient(persistent: true)
->withTimeout(15.0)
->withConnectTimeout(3.0)
->withRetryCount(3)
->withLogger($logger)
// Production Webhook mode with secret token verification
->withRunningMode(new WebhookMode(secretToken: $_ENV['TELEGRAM_WEBHOOK_SECRET']))
->build();
$bot = new Telegram($config);Recipe 2: High-Volume CLI Long-Polling Worker
use Tueen\Telegram\Telegram;
use Tueen\Telegram\Running\PollingMode;
$polling = new PollingMode(
timeout: 50, // Long-polling timeout in seconds
limit: 100, // Max updates per batch
errorBackoffSeconds: 5 // Auto-backoff on network interruptions
);
// Enable multi-process concurrency on CLI:
$polling->forkProcess(true);
$config = Telegram::create(getenv('BOT_TOKEN'))
->withTimeout(60.0) // Must exceed polling timeout
->withRunningMode($polling)
->build();
$bot = new Telegram($config);
$bot->run(App\Handlers\UpdateHandler::class);Recipe 3: Tor / SOCKS5 Proxy for Restricted Environments
use Tueen\Telegram\Telegram;
$config = Telegram::create('YOUR_TOKEN')
->withProxy('socks5h://127.0.0.1:9050')
->withTimeout(60.0)
->withConnectTimeout(15.0)
->withRetryCount(5)
->build();
$bot = new Telegram($config);Recipe 4: Self-Hosted Local Bot API Server (2GB Uploads)
use Tueen\Telegram\Telegram;
$config = Telegram::create('YOUR_TOKEN')
// Point to your local Telegram Bot API Docker container:
->withApiServer('http://telegram-bot-api:8081')
->withTimeout(300.0) // 5 minutes for massive files
->build();
$bot = new Telegram($config);Recipe 5: Laravel & Symfony PSR-11 Container Integration
use Tueen\Telegram\Telegram;
// In Laravel service provider or Symfony dependency injection:
$config = Telegram::create(config('services.telegram.token'))
->withContainer(app()) // Injects Laravel's IoC container
->build();
$bot = new Telegram($config);
// Handlers and Flow classes now automatically resolve with full dependency injection!
$bot->run(App\Handlers\OnboardingHandler::class);Recipe 6: Adaptive AutoMode Execution (Unified CLI & HTTP Webhook)
use Tueen\Telegram\Telegram;
use Tueen\Telegram\Running\PollingMode;
use Tueen\Telegram\Running\WebhookMode;
$bot = Telegram::create($_ENV['BOT_TOKEN'])
->withPollingMode(new PollingMode(timeout: 45))
->withWebhookMode(new WebhookMode(secretToken: $_ENV['WEBHOOK_SECRET']))
->withAutoMode(autoDeleteWebhook: true)
->client();
// In CLI (php bot.php): executes PollingMode
// In Web Server (POST /webhook): executes WebhookMode
$bot->run(App\Handlers\BotHandler::class);