PHP code example of laravel-notification-channels / telegram

1. Go to this page and download the library: Download laravel-notification-channels/telegram library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laravel-notification-channels / telegram example snippets


# 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'),
    // ],
],

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'];
}

use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification
{
    public function via($notifiable)
    {
        return ['telegram'];
    }

    public function toTelegram($notifiable)
    {
        $url = url('/invoice/' . $notifiable->invoice->id);
        $user = $notifiable->name;

        return TelegramMessage::create()
            ->to($notifiable->telegram_user_id)
            ->content('Hello there!')
            ->line('Your invoice has been *PAID*')
            ->lineIf($notifiable->amount > 0, "Amount paid: {$notifiable->amount}")
            ->escapedLine("Thank you, {$user}!")
            // ->view('notification', ['url' => $url])
            ->button('View Invoice', $url)
            ->button('Download Invoice', $url);

        // Other fluent helpers are also available:
        // ->businessConnectionId('business-connection-id')
        // ->messageThreadId(42)
        // ->protectContent()
        // ->directMessagesTopicId(1001)
        // ->allowPaidBroadcast()
        // ->messageEffectId('5104841245755180586')
        // ->replyParameters(['message_id' => 123])
        // ->suggestedPostParameters(['price' => ['amount' => 10, 'currency' => 'XTR']])
        // ->entities([...])
        // ->linkPreviewOptions(['is_disabled' => true])
        // ->sendWhen($notifiable->amount > 0)
        // ->buttonWithWebApp('Open Web App', $url)
        // ->buttonWithCallback('Confirm', 'confirm_invoice '.$this->invoice->id)
        // ->buttonWithCallback('Delete', 'delete', style: 'danger')
        // ->buttonWithCallback('Approve', 'approve', style: 'success')
        // ->button('Details', $url, iconCustomEmojiId: '5368324170671202286')
        // ->disabledButton('Expired')
        // ->forceReply()
        // ->receiverUserId($notifiable->telegram_user_id)
        // ->callbackQueryId($callbackQueryId)
        // ->replaceCallbackQueryMessage()
        // ->ephemeralMessageParameters(['receiver_user_id' => $notifiable->telegram_user_id])
    }
}

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

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

use NotificationChannels\Telegram\TelegramDice;

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

public function toTelegram($notifiable)
{
    return TelegramPoll::create()
        ->to($notifiable->telegram_user_id)
        ->question('Which is your favorite Laravel Notification Channel?')
        ->choices(['Telegram', 'Facebook', 'Slack']);

    // Other fluent helpers are also available:
    // ->description('Voting closes in an hour')
    // ->quiz(0)
    // ->explanation('Telegram, of course!')
    // ->isAnonymous(false)
    // ->allowsMultipleAnswers()
    // ->allowsRevoting()
    // ->shuffleOptions()
    // ->allowAddingOptions()
    // ->hideResultsUntilCloses()
    // ->membersOnly()
    // ->countryCodes(['US', 'GB'])
    // ->openPeriod(600)
    // ->closeDate(now()->addHour()->getTimestamp())
    // ->media(['type' => 'photo', 'media' => $url])
}

use NotificationChannels\Telegram\TelegramRichMessage;

public function toTelegram($notifiable)
{
    return TelegramRichMessage::create()
        ->to($notifiable->telegram_user_id)
        ->markdown(<<<'MD'
            # Invoice #1234 Paid

            Thanks for your payment, we've credited your account.

            [](tg://photo?id=receipt)
            MD)
        ->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])
}

public function toTelegram($notifiable)
{
    return TelegramRichMessage::create()
        ->to($notifiable->telegram_user_id)
        ->heading('Invoice #1234 Paid')
        ->paragraph(['Thanks for your payment, ', ['type' => 'bold', 'text' => $notifiable->name], '!'])
        ->photoBlock(
            ['type' => 'photo', 'media' => 'https://example.com/receipt.jpg'],
            ['text' => 'Your receipt', 'credit' => 'Billing']
        )
        ->listBlock(['Plan: Pro', 'Amount: $49.00', 'Next renewal: in 30 days'])
        ->table(
            cells: [
                [['blocks' => [['type' => 'paragraph', 'text' => 'Item']]], ['blocks' => [['type' => 'paragraph', 'text' => 'Total']]]],
                [['blocks' => [['type' => 'paragraph', 'text' => 'Pro plan']]], ['blocks' => [['type' => 'paragraph', 'text' => '$49.00']]]],
            ],
            bordered: true,
            striped: true,
            caption: 'Invoice summary'
        )
        ->expandableBlockquote('The full terms of the plan...')
        ->divider()
        ->footer('Questions? Just reply to this message.')
        ->buttons([
            ['text' => 'Download Invoice', 'url' => url('/invoice/1234/download')],
            ['text' => 'View Receipt', 'callback_data' => 'receipt 1234', 'style' => 'primary'],
        ], align: 'center');
}

use NotificationChannels\Telegram\TelegramRichMessageDraft;

$draft = TelegramRichMessageDraft::create()
    ->to($chatId)
    ->draftId($chatId) // Any non-zero integer, stable for this stream.
    ->canStop() // Optional: show a button that stops the generation.
    ->keepOnStop(); // Optional: keep the partial draft around when it's stopped.

$buffer = '';

foreach ($stream as $chunk) {
    $buffer .= $chunk;

    // Replaces the content of the draft with the answer so far.
    $draft->markdown($buffer)->send();
}

// Turns the draft into a permanent message via `sendRichMessage`.
$draft->markdown($buffer)->finalize();

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

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');
}

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
}

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

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);

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');
}

$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');

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

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

public function toTelegram($notifiable)
{
    return TelegramLocation::create()
        ->to($notifiable->telegram_user_id)
        ->latitude('40.6892494')
        ->longitude('-74.0466891')
        ->horizontalAccuracy(25)
        ->livePeriod(300)
        ->heading(180)
        ->proximityAlertRadius(50);
}

public function toTelegram($notifiable)
{
    return TelegramVenue::create()
        ->to($notifiable->telegram_user_id)
        ->latitude('38.8951')
        ->longitude('-77.0364')
        ->title('Grand Palace')
        ->address('Bangkok, Thailand');
}

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id)
        ->content('Sample *video* notification!')
        ->video('https://samples-files.com/samples/video/mp4/sample2-720x480.mp4');
}

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id)
        ->content('Woot! We can send animated gif notifications too!')
        ->animation('https://disk.sample.cat/samples/gif/sample-2.gif');
}

TelegramFile::create()
    ->animation('/path/to/some/animated.gif');

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id)
        ->sticker(storage_path('telegram/AnimatedSticker.tgs'));
}

use NotificationChannels\Telegram\TelegramMediaGroup;

public function toTelegram($notifiable)
{
    return TelegramMediaGroup::create()
        ->to($notifiable->telegram_user_id)
        ->photo('https://example.com/one.jpg', 'First image')
        ->photo('https://example.com/two.jpg');
}

TelegramMediaGroup::create()
    ->photo(storage_path('app/telegram/one.jpg'), 'First image')
    ->video(storage_path('app/telegram/video.mp4'), 'Release demo');

TelegramMediaGroup::create()
    ->document('Monthly report content on-the-fly', 'Monthly report caption', 'monthly.txt')
    ->document('/path/to/local/file.pdf', 'pdf file caption', 'annual-report.pdf');

/**
 * Route notifications for the Telegram channel.
 *
 * @return int
 */
public function routeNotificationForTelegram()
{
    return $this->telegram_user_id;
}

use Illuminate\Notifications\Events\NotificationFailed;

class HandleNotificationFailure
{
    public function handle(NotificationFailed $event)
    {
        // $event->notification: The notification instance.
        // $event->notifiable: The notifiable entity who received the notification.
        // $event->channel: The channel name.
        // $event->data: The data needed to process this failure.

        if ($event->channel !== 'telegram') {
            return;
        }

        // Log the error / notify administrator or disable notification channel for the user, etc.
        \Log::error('Telegram notification failed', [
            'chat_id' => $event->data['to'],
            'error' => $event->data['exception']->getMessage(),
            'request' => $event->data['request']
        ]);
    }
}

public function toTelegram($notifiable)
{
    return TelegramMessage::create()
        ->content('Hello!')
        ->onError(function ($data) {
            \Log::error('Failed to send Telegram notification', [
                'chat_id' => $data['to'],
                'error' => $data['exception']->getMessage()
            ]);
        });
}

use Illuminate\Support\Facades\Notification;

Notification::route('telegram', 'TELEGRAM_CHAT_ID')
            ->notify(new InvoicePaid($invoice));

use Illuminate\Support\Facades\Notification;

// Recipients can be an array of chat IDs or collection of notifiable entities.
Notification::send($recipients, new InvoicePaid());

use NotificationChannels\Telegram\Facades\Telegram;

Telegram::sendChatAction([
    'chat_id' => $chatId,
    'action' => 'typing',
]);

use NotificationChannels\Telegram\Telegram;

$telegram = app(Telegram::class);

$telegram->sendChatAction([
    'chat_id' => $chatId,
    'action' => 'typing',
]);

$telegram->editMessageText([
    'chat_id' => $chatId,
    'message_id' => $messageId,
    'text' => 'Updated message text',
]);

$telegram->deleteMessage([
    'chat_id' => $chatId,
    'message_id' => $messageId,
]);

$telegram->sendMediaGroup([
    'chat_id' => $chatId,
    'media' => json_encode([
        ['type' => 'photo', 'media' => 'https://example.com/one.jpg', 'caption' => 'First'],
        ['type' => 'photo', 'media' => 'https://example.com/two.jpg'],
    ], JSON_THROW_ON_ERROR),
]);

$telegram->stopPoll([
    'chat_id' => $chatId,
    'message_id' => $pollMessageId,
]);