Blog Detail

10

Dec
Send Notifications to Telegram with Laravel Notifications cover image

arrow_back Send Notifications to Telegram with Laravel Notifications

Telegram Notifications Channel for Laravel is that package makes it easy to send Telegram notifications using Telegram Bot API with Laravel. You can send any type of notification to Telegram with this package like video, audio, photo, poll, location, contacts, documents, etc.

Installation

You can install the package via composer:

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:

# config/services.php

'telegram-bot-api' => [
    'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE')
],

Retrieving Chat ID

For us to send notifications to your Telegram Bot user/channel or group, we need to know their Chat ID. This can be done by fetching the updates for your Bot using the getUpdates method as per Telegram Bot API docs.

An update is an object containing relevant fields based on the type of update it represents, some examples of an update object are message, callback_query, and poll. For a complete list of fields, see Telegram Bot API docs.

To make things easier, the library comes with a handy method that can be used to get the updates from which you can parse the relevant Chat ID.

Please keep in mind the user has to first interact with your bot for you to be able to obtain their Chat ID which you can then store in your database for future interactions or notifications.

Here’s an example of fetching an update:

use NotificationChannels\Telegram\TelegramUpdates;

// Response is an array of updates.
$updates = TelegramUpdates::create()
    // (Optional). Get's the latest update. NOTE: All previous updates will be forgotten using this method.
    // ->latest()
    
    // (Optional). Limit to 2 updates (By default, updates starting with the earliest unconfirmed update are returned).
    ->limit(2)
    
    // (Optional). Add more params to the request.
    ->options([
        'timeout' => 0,
    ])
    ->get();

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

Note: This method will not work if an outgoing webhook is set up.

For a complete list of available parameters for the options, see Telegram Bot API docs.

Usage

You can now use the channel in your via() method inside the Notification class.

Text Notification

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/' . $this->invoice->id);

        return TelegramMessage::create()
            // Optional recipient user id.
            ->to($notifiable->telegram_user_id)
            // Markdown supported.
            ->content("Hello there!\nYour invoice has been *PAID*")

            // (Optional) Blade template for the content.
            // ->view('notification', ['url' => $url])

            // (Optional) Inline Buttons
            ->button('View Invoice', $url)
            ->button('Download Invoice', $url)
            // (Optional) Inline Button with callback. You can handle callback in your bot instance
            ->buttonWithCallback('Confirm', 'confirm_invoice ' . $this->invoice->id);
    }
}

Attach a Contact

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

Attach an Audio

public function toTelegram($notifiable)
{
    return TelegramFile::create()
            ->to($notifiable->telegram_user_id) // Optional
            ->content('Audio') // Optional Caption
            ->audio('/path/to/audio.mp3');
}

Attach a Photo

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

        // OR using a helper method with or without a remote file.
        // ->photo('https://file-examples-com.github.io/uploads/2017/10/file_example_JPG_1MB.jpg');
}

Attach a Document

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->content('Did you know we can set a custom filename too?')
        ->document('https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf', 'sample.pdf');
}

Attach a Location

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

Attach a Video

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->content('Sample *video* notification!')
        ->video('https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4');
}

There are many different methods available with code examples for sending different types of notifications in Laravel. If you want to explore them you can visit its documentation & source code on Github.

Published at : 10-12-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project