php-telegram-bot/core

repository·develop·Indexed 26 days ago

https://github.com/php-telegram-bot/core

A pure PHP implementation of the Telegram Bot API designed for extensibility via plugins. It supports handling messages, inline queries, and channels using either Webhook or getUpdates methods. The library includes features for MySQL storage, PSR-3 compatible logging, custom command registration, and administrative tools for managing chats and channels.

Tokens
9.2K
Snippets
22
Records
59
Agent score
38%

What's inside php-telegram-bot-core

  1. Choose a Telegram Update Retrieval Method

    develop

    You can retrieve updates from Telegram using two different methods. Choose based on your server capabilities and requirements:

    MethodDescriptionHTTPS RequiredMySQL Required
    WebhookTelegram sends updates directly to your host URL.YesNo
    getUpdatesYou manually fetch updates from Telegram.NoYes (if using database)

    Note: If using getUpdates without a database, you must manage update state manually.

  2. Install a Webhook

    develop

    To set up a Webhook, you need a server with HTTPS. You must first run a script to register the webhook with Telegram, and then create a handler script to process incoming requests.

    <?php
    // set.php - Run this once to register the webhook
    require __DIR__ . '/vendor/autoload.php';
    
    $bot_api_key  = 'your:bot_api_key';
    $bot_username = 'username_bot';
    $hook_url     = 'https://your-domain/path/to/hook.php';
    
    try {
        $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
        $result = $telegram->setWebhook($hook_url);
        if ($result->isOk()) {
            echo $result->getDescription();
        }
    } catch (Longman\TelegramBot\Exception\TelegramException $e) {
        // log telegram errors
    }
    <?php
    // hook.php - This is your endpoint that Telegram calls
    require __DIR__ . '/vendor/autoload.php';
    
    $bot_api_key  = 'your:bot_api_key';
    $bot_username = 'username_bot';
    
    try {
        $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
        $telegram->handle();
    } catch (Longman\TelegramBot\Exception\TelegramException $e) {
        // Silence is golden!
    }
  3. Create a Telegram Bot via @BotFather

    develop

    Before using the library, you must create a bot on Telegram to obtain an API token:

    1. Message @BotFather and send /newbot.
    2. Follow the prompts to choose a name for your bot.
    3. Choose a username for your bot (must end in bot, e.g., my_example_bot).
    4. Save the API token provided by @BotFather. This token is required to authenticate your bot.

    Optional: Bot Privacy Settings To allow your bot to receive all messages in a group (not just commands or mentions), send /setprivacy to @BotFather, select your bot, and choose Disable.

  4. Enable Admin commands and Channel administration

    develop

    Admin commands allow you to manage chats, clean up the database, and broadcast messages. To use these, you must first enable admin status for your user ID(s).

    To manage channels, add your bot as a channel administrator, enable the admin interface for your user, and configure the allowed channels via setCommandConfig for the sendtochannel command.

    // Enable single admin
    $telegram->enableAdmin(your_telegram_user_id);
    
    // Enable multiple admins
    $telegram->enableAdmins([
        your_telegram_user_id,
        other_telegram_user_id,
    ]);
    
    // Configure channels for the /sendtochannel command
    $telegram->setCommandConfig('sendtochannel', [
        'your_channel' => [
            '@type_here_your_channel',
            '@type_here_another_channel',
        ]
    ]);
  5. Recover data from raw update logs

    develop

    If the Telegram API introduces new entities or features that your current database schema does not support, you can log the raw JSON updates to a file. You can later use the importFromLog.php utility script to import these raw updates into your database once your schema is updated.

    Warning: Always backup your database before running import scripts.

  6. Install and run getUpdates via CLI

    develop

    To use the getUpdates method for retrieving Telegram updates, create a PHP script (e.g., getUpdatesCLI.php) that initializes the Telegram object, enables MySQL for performance, and calls handleGetUpdates().

    For best performance, use a MySQL database. If you cannot use a database, call $telegram->useGetUpdatesWithoutDatabase(); instead.

    #!/usr/bin/env php
    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    $bot_api_key  = 'your:bot_api_key';
    $bot_username = 'username_bot';
    
    $mysql_credentials = [
       'host'     => '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();
    }

    Then, make the file executable and run it:

    $ chmod +x getUpdatesCLI.php
    $ ./getUpdatesCLI.php
  7. Configure PSR-3 logging

    develop

    The library uses PSR-3 compatible logging. Logs are categorized into three streams:

    • error: Captures exceptions thrown by the library.
    • debug: Stores requests made to the Telegram API.
    • update: Stores incoming raw updates (JSON strings from Webhooks or getUpdates).

    To initialize logging, use the TelegramLog::initialize method. The first argument is the main logger (handling debug and error), and the second argument is the logger specifically for raw updates.

    use Longman	elegramBot	elegram	elegramLog; // Note: Ensure correct namespace casing based on your installation
    use Monologormatter\lineFormatter;
    use Monolog\
    handler\streamHandler;
    use Monolog\
    logger;
    
    TelegramLog::initialize(
        // Main logger for '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)),
        ])
    );
  8. Configure MySQL storage

    develop

    To save messages, users, and chats, create a database with utf8mb4_unicode_520_ci encoding, import structure.sql, and enable MySQL in your bot setup. You can optionally provide a custom table prefix.

    You can also provide an existing external MySQL PDO connection using enableExternalMySql().

  9. Log all request and response data

    develop

    By default, the library may only log specific events. To ensure that all request and response data is always recorded in the debug log (including successful requests), set the $always_log_request_and_response property to true.

    \Longman\TelegramBot\TelegramLog::$always_log_request_and_response = true;
  10. Show API token in logs

    develop

    To prevent accidental leakage, the library removes the bot API token from logs by default. If you need to see the token in your logs for debugging purposes, set the $remove_bot_token property to false.

    \Longman\TelegramBot\TelegramLog::$remove_bot_token = false;
  11. Use the /sendtochannel command

    develop

    The /sendtochannel command allows an administrator to forward a message (text, photo, audio, video, etc.) to a specific Telegram channel.

    Usage: /sendtochannel <message to send>

    Workflow:

    1. Select Channel: The bot will ask you to provide a channel name (e.g., @yourchannel) or a channel ID (e.g., -12345). If you have pre-configured channels in your bot configuration, you can select one from a keyboard.
    2. Provide Content: Send the content you wish to share (text, photo, audio, etc.).
    3. Caption (Optional): If the content is a media type (like a photo or video), the bot will ask if you want to add a caption.
    4. Preview & Confirm: The bot will show a preview of the message and ask if you want to post it. Type Yes or No to confirm or abort.
    /sendtochannel <message to send>