Telegraph Documentation

repository·main·Indexed 21 days ago

https://github.com/defstudio/telegraph

A Laravel package providing an abstraction layer over the Telegram Bot API. Telegraph simplifies building Telegram bots with features for fluent message construction, interactive keyboards, automated command routing via WebhookHandlers, and integration with Laravel's notification system. It includes tools for bot registration, webhook management, and chat association.

Tokens
53.3K
Snippets
197
Records
240
Agent score
71%

What's inside Telegraph

  1. Introduction to Telegraph

    main

    Telegraph is a Laravel package designed for fluent interaction with Telegram Bots. It provides a high-level API to send messages, manage keyboards, and integrate Telegram with Laravel's notification system.

    Key capabilities include:

    • Fluent message construction.
    • Interactive keyboards with buttons (action-based or URL-based).
    • Integration with Laravel's Notification system to send production alerts via Telegram.
  2. Understand the TelegraphResponse object

    main
    Every request made via the Telegraph facade returns a TelegraphResponse object. This object extends the standard Laravel Illuminate\/Http\/Client\/Response, meaning you can use all native Laravel HTTP client methods (like successful(), json(), or body()) while also gaining access to specialized Telegram-specific helper methods.
  3. Access incoming Telegram data via DTOs

    main

    Data received from manual polling or webhooks is structured into Data Transfer Objects (DTOs) located in the DefStudio\Telegraph\DTO\ namespace. These DTOs provide a type-safe way to access incoming updates from Telegram.

    Key DTOs include:

    • TelegramUpdate: The root object containing the update payload.
    • Message: Details about a text or media message.
    • Chat: Information about the chat (private, group, etc.) where the event occurred.
    • User: Information about a Telegram user.
    • CallbackQuery: Data from inline button interactions.

    To process an update, you typically check which property of the TelegramUpdate is populated (e.g., ->message() or ->callbackQuery()) and then access the nested DTOs.

    use DefStudio\Telegraph\DTO\TelegramUpdate;
    
    /** @var TelegramUpdate $update */
    if ($update->message()) {
        $text = $update->message()->text();
        $chatId = $update->message()->chat()->id();
    }
  4. Understand the RichMessage and RichBlock abstractions

    main

    Rich messages are composed of a RichMessage object containing an array of RichBlock objects.

    • RichMessage: The top-level container. It holds the message content via ->blocks() (an array of RichBlock) and can optionally be set to right-to-left orientation via ->isRtl(true).
    • RichBlock: A single unit of structured content. Each block has a specific ->type() that determines how Telegram renders it (e.g., paragraph, heading, list, table, video).

    When building a rich message, you compose it by nesting blocks or adding them to the RichMessage block array.

  5. Understand the RichText object and its types

    main

    The RichText object represents formatted text in a Telegram message. It can be a collection of RichTextItem objects or one of several specific types. Each type is identified by a ->type() method and contains the actual text via ->text() (which is itself an instance of RichText), allowing for nested formatting.

    Common RichText types include:

    • Basic Formatting: bold, italic, underline, strikethrough, spoiler, subscript, superscript, marked, code.
    • Links & Mentions: url, text_mention (requires a User object), mention (requires a username), anchor, anchor_link, reference, reference_link.
    • Entities: date_time (requires unixTime and dateTimeFormat), custom_emoji (requires customEmojiId and alternativeText), mathematical_expression (requires a LaTeX expression).
    • Contact Info: email_address, phone_number, bank_card_number.
    • Social/Bot: hashtag, cashtag, bot_command.
  6. How Telegraph Entities Storage works

    main

    Telegraph provides a multi-driver storage solution to save and retrieve metadata associated with Bots, Chats, and User DTOs. This storage is contextual, meaning data is scoped to the specific entity instance.

    By default, Telegraph implements storage for:

    • Bots (TelegraphBot models)
    • Chats (TelegraphChat models)
    • User DTOs (User DTOs)

    You can also add storage capabilities to any custom class by implementing the \DefStudio\Telegraph\Contracts\Storable contract and using the \DefStudio\Telegraph\Concerns\HasStorage trait. You must define a storageKey() method to provide a unique identifier for the storage bag.

    class MyCustomClass implements \DefStudio\Telegraph\Contracts\Storable
    {
        use \DefStudio\Telegraph\Concerns\HasStorage;
    
        public function storageKey(): string|int
        {
            return "MyCustomClass instance unique ID";
        }
    }
  7. How Telegram payments work in Telegraph

    main

    Telegram payments follow a specific lifecycle involving invoices, pre-checkout verification, and final confirmation.

    1. Sending Invoices: Use the Invoice method to send a message describing goods/services, the amount, and required shipping info.
    2. Pre-Checkout Verification: When a user attempts to pay, Telegram sends a preCheckoutQuery update. Your bot must respond using answerPrecheckoutQuery via the handlePreCheckoutQuery() method in your WebhookHandler within 10 seconds, or the transaction is canceled. You can return a human-readable error message (e.g., "Out of stock!") which Telegram will display to the user.
    3. Successful Payment: If the transaction completes, Telegram sends a successful_payment update, which is handled by the handleSuccessfulPayment() method in your WebhookHandler.
  8. Configure bot privacy settings

    main

    You can control the scope of messages your bot can access by adjusting its privacy settings via @BotFather using the /setprivacy command.

    There are two modes:

    • enable: The bot will only see messages that start with a / (commands). This is the standard privacy mode.
    • disable: The bot will be able to read all messages sent to the chat, allowing for more complex interaction logic.