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

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

# bootstrap/app.php

// Make sure to create a "config/services.php" file and add the config from the above step.
$app->configure('services');

# Register the notification service providers.
$app->register(Illuminate\Notifications\NotificationServiceProvider::class);
$app->register(NotificationChannels\Telegram\TelegramServiceProvider::class);

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}")
            ->line('Thank you, '.TelegramMessage::escapeMarkdown($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')
    }
}

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

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

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\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,
]);