### Update Composer Dependencies Source: https://github.com/php-telegram-bot/core/wiki/Install-on-Laravel Demonstrates the Composer command to update all dependencies or specifically the 'longman/telegram-bot' package after modifying `composer.json`. ```bash composer update longman/telegram-bot ``` -------------------------------- ### Configure PSR-4 Autoloading for Telegram Bot Source: https://github.com/php-telegram-bot/core/wiki/Install-on-Laravel Illustrates how to update the 'autoload' section in `composer.json` to include the namespace for the Telegram Bot classes, enabling them to be autoloaded by Composer. ```json "autoload": { "psr-4": { "App\": "app/", "Longman\TelegramBot\": "vendor/longman/telegram-bot/src" } } ``` -------------------------------- ### Dump Autoload to Reflect Changes Source: https://github.com/php-telegram-bot/core/wiki/Install-on-Laravel This command is necessary after modifying the autoloading configuration in `composer.json` to ensure Composer recognizes the new class mappings. ```bash composer dump-autoload ``` -------------------------------- ### Function/Method Docblock Example (PHP) Source: https://github.com/php-telegram-bot/core/blob/develop/CONTRIBUTING.md Demonstrates the required documentation format for functions and methods within the project. This docblock includes a description, parameters, and return type. ```php /** * Get formatted date * * @param string $location * * @return string */ ``` -------------------------------- ### File Header Example (PHP) Source: https://github.com/php-telegram-bot/core/blob/develop/CONTRIBUTING.md Shows the mandatory header to be included at the beginning of each file. This header specifies the package, copyright holder, and license information. ```php /** * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ ``` -------------------------------- ### Install Telegram Webhook Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Sets up a webhook to receive updates from Telegram. Requires a server with HTTPS. This script initializes the Telegram bot and registers the provided webhook URL. ```php setWebhook($hook_url); if ($result->isOk()) { echo $result->getDescription(); } } catch (Longman\TelegramBot\Exception\TelegramException $e) { // log telegram errors // echo $e->getMessage(); } ``` -------------------------------- ### Install Dependencies and Check Code Standards (Bash) Source: https://github.com/php-telegram-bot/core/blob/develop/CONTRIBUTING.md Installs project dependencies using Composer and checks if the code conforms to PSR-12 coding standards. This command should produce no output if the code is compliant. ```bash cd php-telegram-bot composer install composer check-code ``` -------------------------------- ### Add Telegram Bot Package to Composer Source: https://github.com/php-telegram-bot/core/wiki/Install-on-Laravel This snippet shows how to add the 'longman/telegram-bot' package as a dependency in your Laravel project's `composer.json` file. ```json { "require": { "longman/telegram-bot": "*" } } ``` -------------------------------- ### Install PHP Telegram Bot via Composer Source: https://github.com/php-telegram-bot/core/blob/develop/README.md This snippet shows how to add the 'longman/telegram-bot' package to your PHP project using Composer. It includes examples for both modifying composer.json and using the command line. ```json { "name": "yourproject/yourproject", "type": "project", "require": { "php": "^8.1", "longman/telegram-bot": "*" } } ``` ```bash composer require longman/telegram-bot ``` -------------------------------- ### Install getUpdates using CLI with MySQL Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Sets up the getUpdates method for receiving updates via a command-line interface. It includes optional integration with a MySQL database for better performance. ```php #!/usr/bin/env php 'localhost', 'port' => 3306, // optional 'user' => 'dbuser', 'password' => 'dbpass', 'database' => 'dbname', ]; try { // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); // Enable MySQL $telegram->enableMySql($mysql_credentials); // Handle telegram getUpdates request $telegram->handleGetUpdates(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { // log telegram errors // echo $e->getMessage(); } ``` -------------------------------- ### Install getUpdates using CLI without Database Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Sets up the getUpdates method for receiving updates via a command-line interface without using a database. This is an alternative for environments where database integration is not feasible. ```php $telegram->useGetUpdatesWithoutDatabase(); ``` -------------------------------- ### Manage Conversation Flow using PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Shows how to manage multi-step conversations for interactive workflows using the `Conversation` class. This example implements a simple survey where the bot guides the user through a series of questions, storing responses in conversation notes. ```php getMessage(); $chat = $message->getChat(); $user = $message->getFrom(); $text = trim($message->getText(true)); $chat_id = $chat->getId(); $user_id = $user->getId(); $conversation = new Conversation($user_id, $chat_id, $this->getName()); $notes = &$conversation->notes; !is_array($notes) && $notes = []; $state = $notes['state'] ?? 0; switch ($state) { case 0: $notes['state'] = 1; $conversation->update(); return Request::sendMessage([ 'chat_id' => $chat_id, 'text' => 'What is your name?', ]); case 1: $notes['name'] = $text; $notes['state'] = 2; $conversation->update(); return Request::sendMessage([ 'chat_id' => $chat_id, 'text' => 'What is your favorite color?', ]); case 2: $notes['color'] = $text; $result = sprintf( "Thank you %s! Your favorite color is %s.", $notes['name'], $notes['color'] ); $conversation->stop(); return Request::sendMessage([ 'chat_id' => $chat_id, 'text' => $result, ]); } return Request::emptyResponse(); } } ``` -------------------------------- ### Initialize PSR-3 Logger with Monolog Source: https://github.com/php-telegram-bot/core/blob/develop/doc/01-utils.md Initializes the Telegram logging system using Monolog, a popular PSR-3 compatible logging library. It demonstrates setting up separate loggers for main bot logs (debug and error) and raw incoming updates. This setup requires Monolog to be installed and configured. ```php use Longman\TelegramBot\TelegramLog; use Monolog\Formatter\LineFormatter; use Monolog\Handler\StreamHandler; use Monolog\Logger; TelegramLog::initialize( // Main logger that handles all 'debug' and 'error' logs. new Logger('telegram_bot', [ (new StreamHandler('/path/to/debug_log_file', Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true)), (new StreamHandler('/path/to/error_log_file', Logger::ERROR))->setFormatter(new LineFormatter(null, null, true)), ]), // Updates logger for raw updates. new Logger('telegram_bot_updates', [ (new StreamHandler('/path/to/updates_log_file', Logger::INFO))->setFormatter(new LineFormatter('%message%' . PHP_EOL)), ]) ); ``` -------------------------------- ### Clone Telegram Bot Repository and Dump Autoload Source: https://github.com/php-telegram-bot/core/wiki/Composer-require-Troubleshooting This sequence of commands clones the php-telegram-bot repository directly from GitHub and then runs 'composer dump-autoload'. This method is an alternative to using Composer's require feature and is suitable when you want to work directly with the repository's source code. ```bash git clone https://github.com/akalongman/php-telegram-bot.git cd php-telegram-bot/ composer dump-autoload ``` -------------------------------- ### PHP: Initialize PSR-3 Logger with Monolog Source: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility Shows how to initialize the logging system for the Telegram Bot library using Monolog, a PSR-3 compliant logger. This replaces the older method of initializing separate debug, error, and update logs and requires manual installation of Monolog. ```php use Longman\TelegramBot\TelegramLog; use Monolog\Formatter\LineFormatter; use Monolog\Handler\StreamHandler; use Monolog\Logger; // Before: // TelegramLog::initDebugLog('/path/to/debug_log_file'); // TelegramLog::initErrorLog('/path/to/error_log_file'); // TelegramLog::initUpdateLog('/path/to/updates_log_file'); // Now: TelegramLog::initialize( // Main logger that handles all 'debug' and 'error' logs. new Logger('telegram_bot', [ (new StreamHandler('/path/to/debug_log_file', Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true)), (new StreamHandler('/path/to/error_log_file', Logger::ERROR))->setFormatter(new LineFormatter(null, null, true)), ]), // Updates logger for raw updates. new Logger('telegram_bot_updates', [ (new StreamHandler('path/to/updates_log_file', Logger::INFO))->setFormatter(new LineFormatter('%message%' . PHP_EOL)), ]) ); ``` -------------------------------- ### Update Specific Package with Composer Source: https://github.com/php-telegram-bot/core/wiki/Composer-require-Troubleshooting This command updates only the specified package, 'mboretto/php-telegram-bot', in your project's dependencies. This is a targeted update that avoids recompiling or updating other packages, saving time and resources. ```bash composer update mboretto/php-telegram-bot ``` -------------------------------- ### Apache: Allow access to Telegram API IPs Source: https://github.com/php-telegram-bot/core/wiki/Securing-&-Hardening-your-Telegram-Bot This Apache configuration snippet restricts access to a specific directory (`/mybot`) to only allow IP addresses originating from Telegram's API ranges. This enhances security by ensuring only Telegram servers can communicate with your bot's endpoint. ```apache Order Allow,Deny Allow from 149.154.160.0/20 Allow from 91.108.4.0/22 ``` -------------------------------- ### Static InlineKeyboard with Multiple Buttons in One Row (PHP) Source: https://github.com/php-telegram-bot/core/wiki/New-Keyboard-structure-and-how-to-pass-dynamic-arguments Demonstrates the static definition of an InlineKeyboard with multiple buttons arranged in a single row. This is the basic usage as explained in the php-telegram-bot example bot. ```php $inline_keyboard = new InlineKeyboard([ ['text' => 'inline', 'switch_inline_query' => 'true'], ['text' => 'callback', 'callback_data' => 'identifier'], ['text' => 'open url', 'url' => 'https://github.com/akalongman/php-telegram-bot'], ]); ``` -------------------------------- ### Nginx: Allow access to Telegram API IPs Source: https://github.com/php-telegram-bot/core/wiki/Securing-&-Hardening-your-Telegram-Bot This Nginx configuration snippet within a `location` block specifies that only requests from Telegram's API IP ranges are allowed to access the specified path (`/mybot`). All other IP addresses will be denied. ```nginx location /mybot { allow 149.154.160.0/20; allow 91.108.4.0/22; deny all; } ``` -------------------------------- ### Configure PSR-4 Autoloading for Telegram Bot Source: https://github.com/php-telegram-bot/core/wiki/Composer-require-Troubleshooting This snippet configures PSR-4 autoloading for the Longman\TelegramBot\ namespace in your composer.json. It maps the namespace to the 'vendor/mboretto/php-telegram-bot/src' directory, ensuring that Composer can find and load the bot's classes. This should be added under the 'autoload' section. ```json "autoload": { "psr-4": { "Longman\TelegramBot\": "vendor/mboretto/php-telegram-bot/src" } } ``` -------------------------------- ### Add Custom Git Repository to Composer Source: https://github.com/php-telegram-bot/core/wiki/Composer-require-Troubleshooting This snippet shows how to add a custom Git repository for the php-telegram-bot package to your project's composer.json file. It specifies the package name, version, and the Git repository URL and reference. This is useful for using a forked version or a specific branch. ```json { "repositories": [ { "type":"package", "package": { "name": "mboretto/php-telegram-bot", "version":"master", "source": { "url": "https://github.com/mboretto/php-telegram-bot.git", "type": "git", "reference":"master" } } } ] } ``` -------------------------------- ### Get and Download Telegram File Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Retrieves file information and allows downloading files from Telegram. Primarily used in conjunction with message attachments like photos or documents. The `getFile` method fetches file metadata, and `downloadFile` handles the download process. ```php // Example usage implicitly shown in descriptions for getFile and downloadFile ``` -------------------------------- ### Require php-telegram-bot Package in Composer Source: https://github.com/php-telegram-bot/core/wiki/Composer-require-Troubleshooting This snippet demonstrates how to add the php-telegram-bot package as a development dependency in your project's composer.json file. It specifies the package and the version constraint to be the development master branch. This line should be added under the 'require' section. ```json "mboretto/php-telegram-bot": "*@dev" ``` -------------------------------- ### PHP: Validate incoming request secret parameter Source: https://github.com/php-telegram-bot/core/wiki/Securing-&-Hardening-your-Telegram-Bot This code snippet validates a secret parameter in the GET request to ensure the request is coming from a legitimate source. It's used within `hook.php` to add an extra layer of security. ```php if (!isset($_GET['secret']) || $_GET['secret'] !== 'AihezooSahc0aiquu3aigai2Phee2ien') { die("I'm safe =)"); } ``` -------------------------------- ### PHP: Command Class Inheritance for StartCommand Source: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility Demonstrates a change in how the `/start` command is handled. It has transitioned from being a `SystemCommand` to a `UserCommand`. While both methods still function, it is recommended to adopt the `UserCommand` approach. ```php class StartCommand extends SystemCommand {} ``` ```php class StartCommand extends UserCommand {} ``` -------------------------------- ### Create Upstart Daemon Configuration for MyBot Source: https://github.com/php-telegram-bot/core/wiki/Нow-to-launch-getUpdatesCLI.php-script-in-background-(getUpdate-installation)? This script configures the 'MyBot' daemon to run as a service on Ubuntu using Upstart. It specifies the description, author, and the commands to run on startup and shutdown. The 'respawn' directive ensures the bot restarts if it crashes. The 'exec' line points to the main PHP script that will be executed. ```upstart description "MyBot Daemon" author "larknart" start on startup stop on shutdown respawn exec /usr/share/getUpdateCLI.php ``` -------------------------------- ### Initialize and Configure Telegram Bot Source: https://github.com/php-telegram-bot/core/wiki/Getting-started-with-php-telegram-bot-and-webhooks This snippet demonstrates the basic initialization of the Telegram bot client using API key and username. It shows how to add custom command paths, enable request limiting for security, and configure MySQL credentials for database integration, which is crucial for features like conversations. ```php $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); //#1- Our commands paths $telegram->addCommandsPaths([ __DIR__ . '/path/to/my/commands/directory/', ]); //#2- Enable requests limiter, to prevent attack like requests //This prevents library from processing repetitive requests $telegram->enableLimiter(); //#3- A database for the library $mysql_credentials = [ 'host' => 'localhost', 'user' => 'root', 'password' => '', 'database' => 'mybotdbname', ]; $telegram->enableMySql($mysql_credentials); //Then call handle and catch the errors and etc.. ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/php-telegram-bot/core/blob/develop/CONTRIBUTING.md Executes the project's unit tests using Composer. Ensure your test database is set up before running this command. Skipped tests can be ignored. ```bash composer test ``` -------------------------------- ### PHP: Restrict access to Telegram API IPs in hook.php Source: https://github.com/php-telegram-bot/core/wiki/Securing-&-Hardening-your-Telegram-Bot This PHP code snippet at the beginning of your `hook.php` file checks if the incoming request's IP address falls within the known ranges of Telegram's API servers. It prevents unauthorized access by only allowing requests from trusted IPs. ```php // Set the ranges of valid Telegram IPs. // https://core.telegram.org/bots/webhooks#the-short-version $telegram_ip_ranges = [ ['lower' => '149.154.160.0', 'upper' => '149.154.175.255'], // literally 149.154.160.0/20 ['lower' => '91.108.4.0', 'upper' => '91.108.7.255'], // literally 91.108.4.0/22 ]; $ip_dec = (float) sprintf("%u", ip2long($_SERVER['REMOTE_ADDR'])); $ok = false; foreach ($telegram_ip_ranges as $telegram_ip_range) { // Make sure the IP is valid. $lower_dec = (float) sprintf("%u", ip2long($telegram_ip_range['lower'])); $upper_dec = (float) sprintf("%u", ip2long($telegram_ip_range['upper'])); if ($ip_dec >= $lower_dec && $upper_dec >= $ip_dec) { $ok = true; break; } } if (!$ok) { die("Hmm, I don't trust you..."); } ``` -------------------------------- ### Set upload and download directories manually in PHP Source: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility The upload and download directories are no longer set by default. Developers must now manually configure these paths in their hook files using `setUploadPath()` and `setDownloadPath()`. ```php $telegram->setUploadPath('/path/to/uploads'); $telegram->setDownloadPath('/path/to/downloads'); ``` -------------------------------- ### Initialize Bot with Webhook - PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Configures a Telegram bot to use the webhook method for receiving updates directly from Telegram servers. Requires the bot's API key and username, and specifies the webhook URL. It uses the `Telegram` class and `setWebhook` method, throwing `TelegramException` on error. ```php setWebhook($hook_url); if ($result->isOk()) { echo $result->getDescription(); // Output: Webhook was set } } catch (TelegramException $e) { error_log('Webhook setup error: ' . $e->getMessage()); } ``` -------------------------------- ### Enable Admin Commands in PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Details on configuring administrative users for the Telegram bot. This includes enabling single or multiple admin user IDs and setting up configurations for specific admin commands like sending messages to channels. ```php enableAdmin(123456789); // Enable multiple admins $telegram->enableAdmins([ 123456789, // Admin 1 user ID 987654321, // Admin 2 user ID ]); // Admin commands are now available: // /chats - List all chats // /cleanup - Clean up old database entries // /debug - Show debug information // /sendtoall - Send message to all active chats // /sendtochannel - Post to channels // /whois - Inspect user or chat details // Configure channel administration $telegram->setCommandConfig('sendtochannel', [ 'your_channel' => [ '@my_channel', '@another_channel', ] ]); ``` -------------------------------- ### Define Namespace and Use Dependencies for UserCommand in PHP Source: https://github.com/php-telegram-bot/core/wiki/Create-your-own-commands Set up the namespace and import necessary classes for a custom user command. This ensures the command belongs to the correct hierarchy (`Longman\TelegramBot\Commands\UserCommands`) and can utilize library functionalities like `UserCommand` and `Request`. ```php namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Request; ``` -------------------------------- ### Configure Specific Command Parameters Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Sets configuration parameters for individual commands. This is used to provide API keys or other settings required by specific commands, such as the 'date' command needing a Google API key or the 'weather' command needing an OpenWeatherMap API key. ```php // Google geocode/timezone API key for /date command $telegram->setCommandConfig('date', [ 'google_api_key' => 'your_google_api_key_here', ]); // OpenWeatherMap API key for /weather command $telegram->setCommandConfig('weather', [ 'owm_api_key' => 'your_owm_api_key_here', ]); ``` -------------------------------- ### Create Custom User Command in PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Illustrates how to create a custom user command for the Telegram bot. This involves extending the `UserCommand` class, defining command properties, and implementing the `execute` method to handle user messages and send responses. ```php getMessage(); $chat_id = $message->getChat()->getId(); $user = $message->getFrom(); $response_text = sprintf( 'Hello %s! Your user ID is: %d', $user->getFirstName(), $user->getId() ); return Request::sendMessage([ 'chat_id' => $chat_id, 'text' => $response_text, ]); } } // Register custom command path in your bot $telegram->addCommandsPath('/path/to/Commands'); ``` -------------------------------- ### Dynamic InlineKeyboard with One Button Per Row (PHP < 5.6) Source: https://github.com/php-telegram-bot/core/wiki/New-Keyboard-structure-and-how-to-pass-dynamic-arguments Provides a method for dynamically creating an InlineKeyboard with one button per row for PHP versions prior to 5.6, utilizing the ReflectionClass to instantiate the class with arguments from an array. ```php $rows = []; foreach($categories as $category) { $rows[] = [ ['text' => $category["name"], 'callback_data' => $category["command"]] ]; } $class = new ReflectionClass("InlineKeyboard"); $inline_keyboard = $class->newInstanceArgs($rows); ``` -------------------------------- ### Static InlineKeyboard with Buttons in Separate Rows (PHP) Source: https://github.com/php-telegram-bot/core/wiki/New-Keyboard-structure-and-how-to-pass-dynamic-arguments Illustrates how to create an InlineKeyboard where buttons are placed in separate rows. This is achieved by passing multiple arrays as arguments to the InlineKeyboard constructor, with each array representing a row. ```php $inline_keyboard = new InlineKeyboard( [ ['text' => 'inline', 'switch_inline_query' => 'true'], ], [ ['text' => 'callback', 'callback_data' => 'identifier'], ['text' => 'open url', 'url' => 'https://github.com/akalongman/php-telegram-bot'], ] ); ``` -------------------------------- ### PHP: Get Command Parameter from Message Source: https://github.com/php-telegram-bot/core/wiki/Running-with-cron-(scheduled-commands) This code snippet shows how to extract parameters passed to a command within a Telegram bot message. It uses `$message->getText(true)` to retrieve the text content of the message, excluding the command itself, and `trim()` to remove any leading or trailing whitespace. This is a standard way to access arguments for bot commands. ```php $text = trim($message->getText(true)); ``` -------------------------------- ### Generate Self-Signed Certificate using OpenSSL Source: https://github.com/php-telegram-bot/core/wiki/Self-Signed-Certificate This command generates a self-signed SSL certificate and private key. It's crucial to replace 'YOURDOMAIN.EXAMPLE' with your actual domain name or server's IP address in the CN field. The generated files are YOURPRIVATE.key (private key) and YOURPUBLIC.pem (public certificate). ```bash openssl req -newkey rsa:2048 -sha256 -nodes -keyout YOURPRIVATE.key -x509 -days 365 -out YOURPUBLIC.pem -subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=YOURDOMAIN.EXAMPLE" ``` -------------------------------- ### Dynamic InlineKeyboard with One Button Per Row (PHP 5.6+) Source: https://github.com/php-telegram-bot/core/wiki/New-Keyboard-structure-and-how-to-pass-dynamic-arguments Shows how to dynamically generate an InlineKeyboard with one button per row using the splat operator (`...`). This method is suitable for scenarios where the number of buttons or their content is determined at runtime and requires PHP 5.6 or higher. ```php $rows = []; foreach($categories as $category) { $rows[] = [ ['text' => $category["name"], 'callback_data' => $category["command"]] ]; } $inline_keyboard = New InlineKeyboard(...$rows); ``` -------------------------------- ### Add Custom Command Paths Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Configures the bot to load custom commands from specified directories. You can add a single directory or an array of directories. This is a primary method for extending bot functionality. ```php // Add a folder that contains command files $telegram->addCommandsPath('/path/to/command/files'); //$telegram->addCommandsPaths(['/path/to/command/files', '/another/path']); ``` -------------------------------- ### Initialize Bot with getUpdates (Long Polling) - PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Sets up a Telegram bot to use the `getUpdates` method (long polling) for retrieving messages. This PHP code initializes the `Telegram` class, optionally enables MySQL, and defines which update types to receive. It then fetches and processes these updates. ```php enableMySql([ 'host' => 'localhost', 'port' => 3306, 'user' => 'dbuser', 'password' => 'dbpass', 'database' => 'telegram_bot', ]); // Define which update types to receive $allowed_updates = [ Update::TYPE_MESSAGE, Update::TYPE_CALLBACK_QUERY, Update::TYPE_INLINE_QUERY, ]; // Fetch and process updates $response = $telegram->handleGetUpdates([ 'limit' => 100, 'timeout' => 60, 'allowed_updates' => $allowed_updates, ]); if ($response->isOk()) { echo "Updates processed: " . count($response->getResult()) . "\n"; } } catch (TelegramException $e) { error_log('Error: ' . $e->getMessage()); } ``` -------------------------------- ### Integrate External PDO Database Connection with PHP Source: https://context7.com/php-telegram-bot/core/llms.txt This snippet demonstrates how to establish a PDO database connection and then enable the Telegram Bot library to use this external connection. It specifies a table prefix for bot-related tables, ensuring data separation within your existing database. Dependencies include the PDO extension and the LongmanTelegramBotTelegram class. ```php PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4', ] ); $telegram = new Telegram($bot_api_key, $bot_username); // Use external PDO connection with table prefix $telegram->enableExternalMySql($pdo, 'bot_'); // Now bot data will be stored in your database with prefixed tables: // bot_telegram_update, bot_message, bot_user, bot_chat, etc. ``` -------------------------------- ### Add Custom Command Paths in PHP Source: https://github.com/php-telegram-bot/core/wiki/Create-your-own-commands Configure the PHP Telegram Bot library to recognize custom command files by specifying their directory paths. This is done by adding an array of paths to the `$commands_paths` variable and passing it to the `addCommandsPaths` method in `hook.php` or within the `commands.paths` configuration in `manager.php`. ```php // hook.php ... // Define all paths for your custom commands in this array (leave as empty array if not used) $commands_paths = [ __DIR__ . '/Commands', ]; // Add this line inside the try{} $telegram->addCommandsPaths($commands_paths); ... ``` ```php // manager.php ... 'commands' => [ // Define all paths for your custom commands 'paths' => [ __DIR__ . '/Commands', ], ], ... ``` -------------------------------- ### Configure SendToChannel Command for a Single Channel Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Sets up the 'sendtochannel' command to target a specific channel. This involves providing the channel's username or ID as a parameter. The bot must be added as an administrator to the channel. ```php $telegram->setCommandConfig('sendtochannel', [ 'your_channel' => [ '@type_here_your_channel', ] ]); ``` -------------------------------- ### Handle Telegram Webhook Request Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Processes incoming webhook requests from Telegram. This script initializes the Telegram bot and handles the incoming update. ```php handle(); } catch (Longman\TelegramBot\Exception\TelegramException $e) { // Silence is golden! // log telegram errors // echo $e->getMessage(); } ``` -------------------------------- ### Set Upload Path Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Defines the directory where files uploaded by the bot will be stored. This path is used for managing outgoing files and media sent through the Telegram bot. ```php $telegram->setUploadPath('/your/path/Upload'); ``` -------------------------------- ### Send Photo using PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Demonstrates sending photos via Telegram using local file paths, remote URLs, or previously uploaded file IDs. It utilizes the `Request::sendPhoto` method and handles potential success or failure responses. ```php 123456789, 'photo' => Request::encodeFile('/path/to/photo.jpg'), 'caption' => 'Check out this image!', ]); // Send photo from URL $result = Request::sendPhoto([ 'chat_id' => 123456789, 'photo' => 'https://example.com/image.jpg', 'caption' => 'Photo from URL', ]); // Send photo using file_id from previous upload $result = Request::sendPhoto([ 'chat_id' => 123456789, 'photo' => 'AgACAgIAAxkBAAIC...', 'caption' => 'Reusing uploaded photo', ]); if ($result->isOk()) { $message = $result->getResult(); $photo = $message->getPhoto()[0]; echo "Photo sent, file_id: " . $photo->getFileId(); } ``` -------------------------------- ### Define Custom Command Properties in PHP Source: https://github.com/php-telegram-bot/core/wiki/Create-your-own-commands Specify essential properties for a custom Telegram bot command, including its name, description, usage syntax, and version. These properties are defined as protected members within the command class. ```php protected $name = 'test'; // Your command's name protected $description = 'A command for test'; // Your command description protected $usage = '/test'; // Usage of your command protected $version = '1.0.0'; // Version of your command ``` -------------------------------- ### Configure SendToChannel Command for Multiple Channels Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Configures the 'sendtochannel' command to manage multiple channels. This allows the bot to send messages to a list of specified channels, each identified by its username or ID. ```php $telegram->setCommandConfig('sendtochannel', [ 'your_channel' => [ '@type_here_your_channel', '@type_here_another_channel', '@and_so_on', ] ]); ``` -------------------------------- ### Handle Telegram Callback Queries with PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Processes button clicks from inline keyboards attached to Telegram messages. It parses callback data to determine user actions and responds by editing the message or showing an alert. Dependencies include the Telegram Bot library and its necessary components for handling requests. ```php getCallbackQuery(); $callback_data = $callback_query->getData(); $message = $callback_query->getMessage(); $chat_id = $message->getChat()->getId(); $user = $callback_query->getFrom(); // Parse callback data $response_text = "You clicked: " . $callback_data; if ($callback_data === 'button1') { $response_text = 'Button 1 was pressed!'; } elseif ($callback_data === 'button2') { $response_text = 'Button 2 was pressed!'; } // Answer callback query (removes loading state) Request::answerCallbackQuery([ 'callback_query_id' => $callback_query->getId(), 'text' => 'Processing...', 'show_alert' => false, ]); // Send or edit message return Request::editMessageText([ 'chat_id' => $chat_id, 'message_id' => $message->getMessageId(), 'text' => $response_text, ]); } } ``` -------------------------------- ### Simplify Request::setWebhook() in PHP Source: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility The `Request::setWebhook` method no longer requires special handling for the URL and data parameters. It now accepts only the `$data` array, simplifying its usage. ```php Request::setWebhook($url, $data = []); ``` ```php Request::setWebhook($data); ``` -------------------------------- ### Set Webhook with Certificate Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Extends the setWebhook functionality to include a certificate file for HTTPS communication, useful when using self-signed certificates. ```php $result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']); ``` -------------------------------- ### Enable External MySQL PDO Connection Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Allows the library to use an existing MySQL PDO connection. This is useful for integrating with existing database infrastructures. The optional second argument allows specifying a table prefix. ```php $telegram->enableExternalMySql($external_pdo_connection); //$telegram->enableExternalMySql($external_pdo_connection, $table_prefix) ``` -------------------------------- ### Handle Incoming Webhook Updates - PHP Source: https://context7.com/php-telegram-bot/core/llms.txt Processes incoming updates from Telegram when the bot is configured in webhook mode. It initializes the `Telegram` class with API credentials and optionally enables MySQL for data persistence. The `handle()` method is then called to process the update, with errors logged via `error_log`. ```php enableMySql([ 'host' => 'localhost', 'port' => 3306, 'user' => 'dbuser', 'password' => 'dbpass', 'database' => 'telegram_bot', ]); // Handle the incoming update $telegram->handle(); } catch (TelegramException $e) { // Silent error handling for webhook error_log('Bot error: ' . $e->getMessage()); } ``` -------------------------------- ### Implement Execute Method for Telegram Bot Command in PHP Source: https://github.com/php-telegram-bot/core/wiki/Create-your-own-commands Implement the `execute` method, which is the core logic for handling a command's execution. This method retrieves message details, extracts chat information, prepares response data, and sends a message back to the user using the `Request::sendMessage` function. ```php public function execute(): \Longman\TelegramBot\Entities\ServerResponse { $message = $this->getMessage(); // Get Message object $chat_id = $message->getChat()->getId(); // Get the current Chat ID $data = [ 'chat_id' => $chat_id, 'text' => 'This is just a Test...', // Set message to send ]; return Request::sendMessage($data); // Send message! ``` -------------------------------- ### Enable Multiple Admin Users Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Enables administrative privileges for multiple Telegram user IDs. This is a convenient way to grant admin access to several users simultaneously. ```php // Multiple admins $telegram->enableAdmins([ your_telegram_user_id, other_telegram_user_id, ]); ``` -------------------------------- ### Enable MySQL Storage for Telegram Bot Source: https://github.com/php-telegram-bot/core/blob/develop/README.md Configures the bot to use a MySQL database for storing messages, users, and chats. This is recommended for persistent data. Requires database credentials and optionally a table prefix. MySQL support must be enabled before calling the `handle()` method. ```php $mysql_credentials = [ 'host' => 'localhost', 'port' => 3306, // optional 'user' => 'dbuser', 'password' => 'dbpass', 'database' => 'dbname', ]; $telegram->enableMySql($mysql_credentials); ``` ```php $telegram->enableMySql($mysql_credentials, $bot_username . '_'); ```