Telegram Bot PHP SDK
repository·3.x·Indexed 25 days ago
https://github.com/irazasyed/telegram-bot-sdkA PHP SDK providing a simplified interface for interacting with the Telegram Bot API. It includes native support for the Laravel framework, including a `telegram:webhook` Artisan command for managing webhooks. The library supports synchronous and asynchronous requests via GuzzleHttpClient and provides structured objects for handling Updates, CallbackQueries, and BotCommands. Current supported version is 3.x.
What's inside telegram-bot-sdk
- The Telegram Bot PHP SDK is a library designed to simplify the development of Telegram bots using PHP. It provides an easy-to-use interface for the Telegram Bot API, which is an HTTP-based interface for building bots. The SDK features built-in support for Laravel, making it highly compatible with the Laravel ecosystem.
Instantiate the Api class
3.xTo interact with the Telegram Bot API, create a new instance of the
Telegram\Bot\Apiclass. You can provide a bot token directly, or the SDK will attempt to retrieve it from the environment variable defined byApi::BOT_TOKEN_ENV_NAME(TELEGRAM_BOT_TOKEN).Supported constructor parameters:
string|null $token: The Telegram Bot API Access Token.bool $async: If set totrue, requests to Telegram will be asynchronous (non-blocking).HttpClientInterface|null $httpClientHandler: An optional custom HTTP Client implementation.string|null $baseBotUrl: An optional custom base URL for the Telegram Bot API.
Use the TELEGRAM_BOT_TOKEN environment variable
3.xIf you do not pass a token explicitly to theApiconstructor, the SDK looks for an environment variable namedTELEGRAM_BOT_TOKENto authenticate your bot.Configure webhook settings for the Artisan command
3.xThe
telegram:webhookcommand relies on the bot configuration (retrieved viaBotsManager::getBotConfig()) to perform its tasks. To ensure successful setup, ensure your bot configuration includes the following keys:webhook_url: (Required) The HTTPS URL where Telegram will send updates. Must start withhttps://.certificate_path: (Optional) The file path to your SSL certificate.allowed_updates: (Optional) An array of update types that the webhook should receive.bot: The identifier for the bot used in the configuration.
Check supported SDK versions
3.xThe SDK primarily supports the latest released version. While backward-incompatible changes are rare to facilitate upgrades, ensure you are using the correct version for your project requirements:
- 3.x: Current supported version.
- 4.x: Currently in development.
- 2.x: No longer supported.
Extract the message or related content from an Update
3.xTo retrieve the primary content of an update (such as a
Message,InlineQuery, orCallbackQuery), use the following methods:getMessage(): Returns aCollectioncontaining the message-like object (e.g.,Message,EditedMessage,ChannelPost,InlineQuery,ShippingQuery,PreCheckoutQuery, orPoll).getRelatedObject(): Returns the specific object instance corresponding to the update type (e.g.,Message|InlineQuery|ChosenInlineResult|CallbackQuery|ShippingQuery|PreCheckoutQuery|Poll|PollAnswer).getChat(): Returns thechatobject associated with the update.
Configure timeouts in GuzzleHttpClient
3.xYou can control the request timeout and connection timeout for all requests made through the
GuzzleHttpClientusingsetTimeOut()andsetConnectTimeOut().setTimeOut(int $timeOut): Sets the total request timeout in seconds.setConnectTimeOut(int $connectTimeOut): Sets the connection timeout in seconds.
Handle incoming Telegram Updates with the Update object
3.xTheTelegram\Bot\Objects\Updateclass represents an incoming update from the Telegram Bot API. It acts as a container for various types of interactions, such as messages, callback queries, or poll updates. You can use it to identify the type of update received and extract the relevant data (like the message or the chat object).Send requests with GuzzleHttpClient
3.xThe
sendmethod allows you to execute HTTP requests. It supports both synchronous and asynchronous execution.Parameters:
string $url: The target URL.string $method: The HTTP method (e.g., 'GET', 'POST').array $headers: An array of HTTP headers.array $options: Additional Guzzle request options (e.g.,['body' => $data]).bool $isAsyncRequest: Iftrue, the method returns aPromiseInterfaceinstead of waiting for the response. Iffalse, it waits and returns aResponseInterface.
Returns:
ResponseInterface|PromiseInterface|nullUse GuzzleHttpClient for custom HTTP requests
3.xTheGuzzleHttpClientimplementsHttpClientInterfaceand allows you to use a custom Guzzle client instance. This is useful if you need to configure specific Guzzle middleware, proxy settings, or custom handlers. You can inject your ownClientInterfacevia the constructor or thesetClientmethod.Reference: Update property types
3.xTheUpdateobject can contain the following properties (mapped from Telegram API):Inspect webhook configuration with WebhookInfo
3.xThe
WebhookInfoobject contains information about the current status of a bot's webhook configuration. You can use this object to check if a webhook is set up, see how many updates are pending, and inspect recent delivery errors.Properties available on the
WebhookInfoobject:url: The Webhook URL (may be empty if no webhook is set up).hasCustomCertificate: Boolean indicating if a custom certificate was provided for webhook certificate checks.pendingUpdateCount: The number of updates currently awaiting delivery.lastErrorDate(Optional): Unix time for the most recent error during update delivery.lastErrorMessage(Optional): Human-readable error message for the most recent error.maxConnections(Optional): Maximum allowed number of simultaneous HTTPS connections to the webhook.allowedUpdates(Optional): A list of update types the bot is subscribed to.