telegrambot-api

repository·master·Indexed 22 days ago

https://github.com/telegrambot/api

A native PHP wrapper for the Telegram Bot API that supports all methods and response types without external requirements. It provides a BotApi class for direct method calls and a Client class for high-level handling of updates, commands, and bot loops. The library supports webhooks, long polling, custom local Bot API servers, and integration with Symfony's HttpClient.

Tokens
7.9K
Snippets
26
Records
30
Agent score
79%

What's inside telegrambot-api

  1. Build a bot using the Client class

    master

    The Client class provides a high-level interface for handling updates, commands, and running the bot loop. You can register command handlers with $bot->command() and general update handlers with $bot->on().

    require_once "vendor/autoload.php";
    
    try {
        $bot = new \TelegramBot\Api\Client('YOUR_BOT_API_TOKEN');
    
        // Handle /ping command
        $bot->command('ping', function ($message) use ($bot) {
            $bot->sendMessage($message->getChat()->getId(), 'pong!');
        });
        
        // Handle all text messages
        $bot->on(function (\TelegramBot\Api\Types\Update $update) use ($bot) {
            $message = $update->getMessage();
            $id = $message->getChat()->getId();
            $bot->sendMessage($id, 'Your message: ' . $message->getText());
        }, function () {
            return true;
        });
        
        $bot->run();
    
    } catch (\TelegramBot\Api\Exception $e) {
        $e->getMessage();
    }
  2. Initialize the Client

    master

    To interact with the Telegram Bot API, instantiate the TelegramBot\Api\Client class. You must provide your Telegram Bot API token. Optionally, you can provide a custom HttpClientInterface implementation or a specific API endpoint.

    use TelegramBot\Api\Client;
    
    $client = new Client('YOUR_BOT_TOKEN');
    $client = new Client('YOUR_BOT_TOKEN');
  3. Process Webhook Updates

    master

    If you are using webhooks, call the run() method. This method reads the raw request body from php://input, validates the JSON, and processes the resulting Update through the registered event handlers.

    // In your webhook entrypoint script
    $client->run();
    $client->run();
  4. Send messages with keyboards

    master

    You can attach different types of keyboards to messages using ReplyKeyboardMarkup for standard button layouts or InlineKeyboardMarkup for buttons attached directly to the message.

    $bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
    
    // Reply Keyboard (standard buttons)
    $keyboard = new \TelegramBot\Api\Types\ReplyKeyboardMarkup(array(array("one", "two", "three")), true); // true for one-time keyboard
    $bot->sendMessage($chatId, $messageText, null, false, null, $keyboard);
    
    // Inline Keyboard (buttons with URLs/callbacks)
    $keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup([
        [
            ['text' => 'link', 'url' => 'https://core.telegram.org']
        ]
    ]);
    $bot->sendMessage($chatId, $messageText, null, false, null, $keyboard);
  5. Send media groups

    master

    To send multiple photos or videos together, use ArrayOfInputMedia and add items using InputMediaPhoto or InputMediaVideo.

    $bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
    $media = new \TelegramBot\Api\Types\InputMedia\ArrayOfInputMedia();
    $media->addItem(new \TelegramBot\Api\Types\InputMedia\InputMediaPhoto('https://avatars3.githubusercontent.com/u/9335727'));
    $media->addItem(new \TelegramBot\Api\Types\InputMedia\InputMediaPhoto('https://avatars3.githubusercontent.com/u/9335727'));
    
    $bot->sendMediaGroup($chatId, $media);
  6. Use a third-party HTTP client

    master

    You can inject a custom HTTP client into the Client by using the SymfonyHttpClient wrapper. This is useful if you want to use Symfony's HttpClient instead of the default implementation.

    use Symfony\Component\HttpClient\HttpClient;
    use TelegramBot\Api\Client;
    use TelegramBot\Api\Http\SymfonyHttpClient;
    
    $token = 'YOUR_BOT_API_TOKEN';
    $bot = new Client($token, null, new SymfonyHttpClient(HttpClient::create()));
  7. Use the BotApi wrapper for direct method calls

    master

    The BotApi class provides a direct wrapper for Telegram Bot API methods. You can use it to send messages, documents, or media groups by providing your bot token and the target chatId.

    $bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
    
    // Send a simple text message
    $bot->sendMessage($chatId, $messageText);
    
    // Send a document using CURLFile
    $document = new \CURLFile('document.txt');
    $bot->sendDocument($chatId, $document);
  8. Register Event Handlers

    master

    The Client allows you to listen for various Telegram update types using specific helper methods. Each method accepts a Closure that will be executed when the event occurs.

    Available event helpers:

    • editedMessage(Closure $action): Triggered when a message is edited.
    • callbackQuery(Closure $action): Triggered when a user interacts with an inline keyboard.
    • channelPost(Closure $action): Triggered when a new post is made in a channel.
    • editedChannelPost(Closure $action): Triggered when a channel post is edited.
    • inlineQuery(Closure $action): Triggered when an inline query is sent.
    • chosenInlineResult(Closure $action): Triggered when an inline result is chosen.
    • shippingQuery(Closure $action): Triggered when a shipping query is received.
    • preCheckoutQuery(Closure $action): Triggered when a pre-checkout query is received.

    Each closure receives the relevant object (e.g., Message, CallbackQuery, etc.) as its argument.

    $client->callbackQuery(function (\TelegramBot\Api\Types\Inline\CallbackQuery $callbackQuery) {
        // Handle callback query
    });
  9. Use the GiveawayWinners type

    master

    The GiveawayWinners class represents a Telegram message notifying about the completion of a giveaway and listing the public winners. It is used to access details such as the chat where the giveaway occurred, the winners selected, and metadata about the giveaway prizes or status.

    Required Fields

    When constructing or receiving this type, the following fields are mandatory:

    • chat: The Chat object that created the giveaway.
    • giveaway_message_id: The integer ID of the original giveaway message.
    • winners_selection_date: Unix timestamp of when winners were selected.
    • winner_count: Total number of winners.
    • winners: An ArrayOfUser containing the list of winners (up to 100).

    Optional Fields

    • additional_chat_count: Number of other chats the user had to join to be eligible.
    • premium_subscription_month_count: Duration (in months) of a won Telegram Premium subscription.
    • unclaimed_prize_count: Number of prizes that were not distributed.
    • only_new_members: Boolean indicating if only users who joined after the giveaway started were eligible.
    • was_refunded: Boolean indicating if the giveaway was canceled due to a refund.
    • prize_description: A string describing the additional giveaway prize.
  10. Handle Bot Commands

    master

    Use the command() method to register a handler for a specific bot command (e.g., /start). The command name is the string following the slash.

    When a command is triggered, the provided Closure is executed. The Client automatically parses the command and passes the following arguments to your closure based on the number of required parameters:

    1. The Message object representing the command message.
    2. Any additional parameters passed in the command text (space-separated).
    $client->command('start', function (\TelegramBot\Api\Types\Message $message) {
        // Handle /start command
        $message->reply('Hello!');
    });
    $client->command('start', function (\TelegramBot\Api\Types\Message $message) {
        $message->reply('Hello!');
    });