Search

Sending Telegram Notifications in Laravel

post-title

Telegram is a highly customizable, cloud-based instant messaging service, and It boasts of having over 200+ million active users per month. Even though Telegram is not as widely used as its mammoth competitor WhatsApp, It still manages to provide significant advantages over WhatsApp. Today, I’m going to show you how you can quickly implement and send Telegram Notifications using Laravel.

In this tutorial, we will set up a new Laravel project and send a welcome message via Telegram to any newly registered users in our application.

Telegram Benefits

  • Unlimited Storage: Telegram provides unlimited storage for all your content, including messages, images, media files & documents that will be saved on their cloud without any compression or size limits. This perk comes in handy if your Laravel application needs to send documents or media to its users.
  • Group Member Capacity: Telegram supports groups of up to 5000 members!
  • Bots: Bots in Telegram are based on AI and machine learning. They can perform various tasks. For example, weather bot can fetch weather from your region.
  • Public API: Whatsapp has no open API; however, Telegram provides a free to use, easy to set up public API.

Telegram API Limitations

There is one major limitation to using Telegram’s API. That is to say, Telegram does not allow sending messages directly to the user’s phone numbers unless the user initiates the conversation first!. In short, this is essential for Telegram to prevent spam in the system, but I will show you a workaround to deal with this issue.

Telegram Bot Set-Up

We’ll begin by first creating a bot on Telegram. To do this, Telegram has an official bot called BotFather that can create new bots. Once a bot is created, you will receive an API token, which will be used later in our Laravel application.

Search for BotFather in Telegram application:

The BotFather bot should have a checkmark associated with it. Please refer to the image below and make sure you choose the right bot!

Create a new bot using BotFather :

To create a bot, you need to send the following message to the `BotFather` bot:

  1. /newbot : Initiate new bot creation with BotFather
  2. You will be asked to give a name for your bot. This is the public name that your users will see.
  3. You will then be asked to provide a username for your bot. This username has to be unique so make sure you give something uncommon and specific to your project.

Finally, you will receive an API token in this process, copy that in a safe location as we will be using it shortly.

Installation and Set-up

Install a new Laravel 7 project:

composer create-project --prefer-dist laravel/laravel laravel-telegram-notifications

Install Laravel’s UI package:

composer require laravel/ui

Generate Laravel’s authentication scaffolding and compile resources:

This will give us Laravel’s default authentication view and you can access user registration at http://your-app/register.

php artisan ui vue --auth
npm install
npm run dev

Also, make sure to run your migrations before you try to register any users.

Install the Telegram Notifications Package:

composer require babenkoivan/telegram-notifications

Register Service Provider:

Register the package’s service provider in config/app.php

// config/app.php
'providers' => [
    ...
    TelegramNotifications\TelegramServiceProvider::class    
]

Publish Package’s Configuration File:

This command will create a telegram.php file in the config directory. We can use this to configure the package.

php artisan vendor:publish --provider='TelegramNotifications\TelegramServiceProvider' 

Set your bot’s API token in .env the file:

TELEGRAM_BOT_TOKEN=your-telegram-api-token

Create a Custom Laravel Notification

Create a custom notification for Telegram messages:

php artisan make:notification LaravelTelegramNotification

The above artisan command creates a LaravelTelegramNotification file in app/Notifications path. Laravel supports sending various types of notifications such as email, SMS, and Slack. Each notification is represented as a Single PHP class located in app/Notifications directory.

Add the telegram message logic to LaravelTelegramNotification.php :

Every notification class must implement a via() method. The telegram package that we use also requires a toTelegram() method to be implemented.

// LaravelTelegramNotification.php
class LaravelTelegramNotification extends Notification
{
    use Queueable;

    protected $data;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(array $arr)
    {
        $this->data = $arr;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [TelegramChannel::class];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toTelegram() {
        return (new TelegramMessage())
            ->text($this->data['text']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

In the above class, we are creating a dynamic function that accepts a message parameter and sends that message to the user.

Prepare User Model and Registration View

In order to send notifications to Telegram, you need to have the user’s unique User ID. The user_id is a unique identifier of every telegram user and every user can get their user_id by following .

In this tutorial, we will get the Telegram user ID of a user during registration.

Let’s get started by adding user_id to $fillable array in User.php:

// User.php
protected $fillable = [
    'name', 'email', 'password', 'user_id'
];

Define a routeNotificationForTelegram() method in User.php which returns the user’s user_id.

// User.php
/**
 * Return Telegram user_id of the user
 * 
 * @return mixed
 */
public function routeNotificationForTelegram()
{
    return $this->user_id;
}

Add a user_id input field to the user registration form in register.blade.php

// register.blade.php
<div class="form-group row" style="background:lightgray">
    <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Telegram User Id') }}</label>

    <div class="col-md-6">
        <input id="user_id" class="form-control @error('user_id') is-invalid @enderror" name="user_id" value="{{ old('user_id') }}" required autocomplete="user_id">

        @error('user_id')
        <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

The output should look something like this:

Modify RegisterController.php to account for the new user_id field and we will also be adding the logic for sending the notification to the user in create() method.

// RegisterController.php
/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'user_id' => ['required', 'string', 'max:255'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'user_id' => $data['user_id'],
        'password' => Hash::make($data['password']),
    ]);

    $user->notify(new LaravelTelegramNotification([
        'text' => "Welcome to the application " . $user->name . "!"
    ]));

    return  $user;
}

Sending more than just a message:

You can also send other data using this package. For example, images, videos, documents, contacts, location and audio files. Modify the toTelegram() method to send a collection of messages and send the data during create() method of RegisterController.php.

// LaravelTelegramNotification.php
public function toTelegram() {
    return (new TelegramCollection())
        ->message(['text' => $this->data['text']])
        ->location(['latitude' => $this->data['latitude'], 'longitude' => $this->data['longitude']])
        ->photo(['photo' => $this->data['photo'], 'caption' => $this->data['photo_caption']]);
}
// RegisterController.php
protected function create(array $data)
{

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'user_id' => $data['user_id'],
        'password' => Hash::make($data['password']),
    ]);

    $user->notify(new LaravelTelegramNotification([
        'text' => "Welcome to the application " . $user->name . "!",
        'latitude' => '23.022505',
        'longitude' => '72.571365',
        'photo' => 'https://laravelcode.com/upload/logo.svg',
        'photo_caption' => 'Telegram Notifications in Laravel'
    ]));

    return  $user;
}

Now go ahead and try the user registration by heading to the registration page in a browser. Subsequently, the user should receive a message from your bot!

then you can see your both of messages ini the telegram bots:

That’s it, it’s quite easy to implement Telegram notifications and send Telegram notifications using Laravel! Also, If you have any questions or suggestions, please drop them in the comments section below The complete working Laravel project used for this tutorial can found in my GitHub repository. Feel free to use it for yourself.