Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

telegram

> 后端框架
Open source

✈️ Telegram Notifications Channel for Laravel

1.1K stars0 likes3 views
WebsiteGitHub

About

✈️ Telegram Notifications Channel for Laravel

Telegram Notifications Channel for Laravel

[![Join PHP Chat][ico-phpchat]][link-phpchat] [![Chat on Telegram][ico-telegram]][link-telegram] [![Latest Version on Packagist][ico-version]][link-packagist] ![Software License][ico-license] [![Total Downloads][ico-downloads]][link-packagist]

This package makes it easy to send Telegram notifications from Laravel via the Telegram Bot API.

Contents

  • Installation
    • Setting up your Telegram Bot
    • Retrieving Chat ID
    • Proxy or Bridge Support
  • Usage
    • Text Notification
    • Send with Keyboard
    • Send a Dice
    • Send a Poll
    • Send a Rich Message
      • Streaming Drafts
    • Attach a Contact
    • Attach an Audio
    • Attach a Photo
    • Attach a Document
    • Attach a Location
    • Attach a Venue
    • Attach a Video
    • Attach a GIF File
    • Attach a Sticker
    • Send a Media Group
    • Routing a Message
    • Handling Response
    • Exception Handling
      • Using NotificationFailed Event
      • Using onError Callback
    • On-Demand Notifications
    • Sending to Multiple Recipients
    • Using the Telegram Client Directly
  • Available Methods
    • Common Methods
    • Telegram Message Methods
    • Telegram Location Methods
    • Telegram Venue Methods
    • Telegram File Methods
    • Telegram Media Group Methods
    • Telegram Contact Methods
    • Telegram Dice Methods
    • Telegram Poll Methods
    • Telegram Rich Message Methods
  • Alternatives
  • Changelog
  • Testing
  • Security
  • Contributing
  • Credits
  • License

Installation

You can install the package via composer:

bash
composer require laravel-notification-channels/telegram

Setting up your Telegram Bot

Talk to @BotFather and generate a Bot API token.

Then, configure your Telegram Bot API token:

php
# config/services.php

'telegram' => [
    'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE'),

    // Optional bridge / self-hosted Bot API server
    // 'base_uri' => env('TELEGRAM_API_BASE_URI'),

    // Optional Guzzle HTTP client options.
    // Defaults: 30s request timeout, 10s connection timeout.
    // 'http' => [
    //     'timeout' => 30,
    //     'connect_timeout' => 10,
    //     'proxy' => env('TELEGRAM_HTTP_PROXY'),
    // ],
],

[!NOTE] The package also supports the legacy services.telegram-bot-api.* config keys for backward compatibility, but services.telegram.* is the preferred configuration format.

Retrieving Chat ID

To send notifications to a Telegram user, channel, or group, you need its chat ID.

You can retrieve it by fetching your bot [updates][link-telegram-docs-update] with the getUpdates method described in the Telegram Bot API [docs][link-telegram-docs-getupdates].

An [update][link-telegram-docs-update] is an object whose shape depends on the event type, such as message, callback_query, or poll. For the full list of fields, see the [Telegram Bot API docs][link-telegram-docs-update].

To make this easier, the package ships with TelegramUpdates, which lets you fetch updates and inspect the chat IDs you need.

Keep in mind that the user must interact with your bot first before you can obtain their chat ID and store it for future notifications.

Here's an example of fetching an update:

php
use NotificationChannels\Telegram\TelegramUpdates;

// Response is an array of updates.
$updates = TelegramUpdates::create()

    // (Optional) Get the latest update.
    // NOTE: All previous updates will be forgotten using this method.
    // ->latest()

    // (Optional) Limit to 2 updates. By default, updates start with the earliest unconfirmed update.
    ->limit(2)

    // (Optional) Add more request parameters.
    ->options([
        'timeout' => 0,
    ])
    ->get();

if ($updates['ok']) {
    // Chat ID
    $chatId = $updates['result'][0]['message']['chat']['id'];
}

[!NOTE] This method will not work while an outgoing webhook is configured.

For the full list of supported options(), see the [Telegram Bot API docs][link-telegram-docs-getupdates].

Proxy or Bridge Support

You may not be able to send notifications directly if the Telegram Bot API is blocked in your region. In that case, you can either configure a proxy by following the Guzzle instructions here or point the package at a bridge or self-hosted Bot API server by setting the base_uri config shown above.

You can also set HTTPS_PROXY in your .env file, or set the proxy key (or any other Guzzle request option, such as timeout) in the services.telegram.http config array shown above.

Usage

You can now return the channel from your notification's via() method.

Text Notification

…

Here's a screenshot preview of the above notification on Telegram Messenger:

Send with Keyboard

php
public function toTelegram($notifiable)
{
    return TelegramMessage::create()
        ->to($notifiable->telegram_user_id)
        ->content('Choose an option:')
        ->keyboard('Button 1')
        ->keyboard('Button 2');
}

Preview:

You can also request structured input from the keyboard:

php
TelegramMessage::create()
    ->content('Please share your phone number or location')
    ->keyboard('Send your number', requestContact: true)
    ->keyboard('Send your location', requestLocation: true);

Preview:

Send a Dice

php
use NotificationChannels\Telegram\TelegramDice;

public function toTelegram($notifiable)
{
    return TelegramDice::create()
        ->to($notifiable->telegram_user_id)
        ->emoji('');
}

Preview:

Send a Poll

…

Preview:

Send a Rich Message

Rich messages (Bot API 10.1) let you send long-form, formatted posts built from blocks or from a single Markdown / HTML document.

The simplest way is to pass Markdown (or HTML) content, referencing any attached media with tg://photo?id=, tg://video?id= or tg://audio?id= links:

php
use NotificationChannels\Telegram\TelegramRichMessage;

public function toTelegram($notifiable)
{
    return TelegramRichMessage::create()
        ->to($notifiable->telegram_user_id)
        ->markdown(media('receipt', ['type' => 'photo', 'media' => 'https://example.com/receipt.jpg'])
        ->button('View Invoice', url('/invoice/1234'));

    // Or render a Blade view as the HTML content instead:
    // ->view('invoices.telegram', ['invoice' => $notifiable->invoice])
}

For full control over the layout, build the message out of blocks:

…

All the common methods (to(), button(), keyboard(), disableNotification(), replyParameters(), ...) work as usual and are sent alongside the encoded rich_message param.

[!NOTE] Block types without a dedicated builder (such as collage and slideshow) can be added with the block() escape hatch. Direct file uploads for rich message media are not supported: reference media by URL or file_id.

Streaming Drafts

Drafts (sendRichMessageDraft) are temporary messages shown to the user while they're still being written. Sending again with the same draftId() animates the replacement of the previous content, which makes TelegramRichMessageDraft a good fit for streaming an AI generated answer as it's produced:

…

Every content and block builder of TelegramRichMessage is available on the draft, so you can stream blocks instead of Markdown if you prefer.

[!IMPORTANT] Drafts can only be sent to private chats and the draft_id must be a non-zero integer. Batch your updates (roughly one send() every 0.5-1 seconds) instead of sending one per token, otherwise your bot will quickly hit the API rate limits. A draft that's never finalized simply disappears: only finalize() leaves a permanent message behind. The endpoint accepts chat_id, message_thread_id, draft_id, rich_message, can_stop and keep_on_stop only, so buttons and notification flags are applied when the draft is finalized.

Attach a Contact

php
public function toTelegram($notifiable)
{
    return TelegramContact::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->firstName('John')
        ->lastName('Doe') // Optional
        ->phoneNumber('00000000');
}

Preview:

Attach an Audio

php
public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->content('Audio') // Optional caption
        ->captionEntities([
            ['offset' => 0, 'length' => 5, 'type' => 'bold'],
        ])
        ->audio('/path/to/audio.mp3');
}

Preview:

Attach a Photo

php
public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->content('Awesome *bold* text and [inline URL](http://www.example.com/)')
        ->showCaptionAboveMedia()
        ->file('/storage/archive/6029014.jpg', 'photo'); // local photo
}

You can also use a helper method with a remote file or Telegram file ID:

php
TelegramFile::create()
    ->photo('https://samples-files.com/samples/images/jpg/1280-720-sample.jpg');

If you already know whether you're dealing with a URL or a Telegram file ID, use the explicit methods instead — they validate the input and skip the detection heuristics:

php
use NotificationChannels\Telegram\Enums\FileType;

TelegramFile::create()
    ->url('https://samples-files.com/samples/images/jpg/1280-720-sample.jpg', FileType::Photo);

TelegramFile::create()
    ->fileId('AgACAgQAAxkDAAIBLGV3', FileType::Photo);

Preview:

Attach a Document

php
public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->content('Here is your PDF document')
        ->document('https://samples-files.com/samples/documents/pdf/sample-1-small-size.pdf');
}

Preview:

If you want to control the filename, you need to upload the actual file contents instead of passing the remote URL directly:

php
$contents = file_get_contents('https://samples-files.com/samples/documents/pdf/sample-1-small-size.pdf');

TelegramFile::create()
    ->content('Did you know we can set a custom filename too?')
    ->document($contents, 'sample.pdf');

Preview:

Raw file contents are also supported when you provide a filename:

php
TelegramFile::create()
    ->document('Hello Text Document Content', 'hello.txt');

Preview:

Attach a Location

php
public function toTelegram($notifiable)
{
    return TelegramLocation::create()
        ->to($notifiable->telegram_user_id)
        ->latitude('40.6892494')
        ->longitude('-74.0466891');
}

Preview:

You can also sen

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPbot-apihacktoberfestlaravellaravel-12-package

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架