babenkoivan/telegram-notifications

Telegram notifications for Laravel

v1.1.0 2021-11-10 08:29 UTC

This package is auto-updated.

Last update: 2024-07-10 14:41:28 UTC


README

Packagist Packagist license

The package provides easy way to send Telegram notifications to any notifiable entity in your project. It uses official Telegram Bot API to deliver your message directly to a user. You can send any information you want: text, media, location or contact.

Contents

Requirements

The package has been tested on following configuration:

  • PHP version >= 7.3
  • Laravel Framework version >= 5.5

Installation

To install the package you can use composer:

composer require babenkoivan/telegram-notifications

If the package discovery is disabled, you need to register the service provider in config/app.php file:

'providers' => [
    TelegramNotifications\TelegramServiceProvider::class    
]

To copy the package settings to config directory run:

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

Now you're ready to set up a bot token for your application. If you haven't created a bot you can make new one using BotFather. For more information, visit Bots: An introduction for developers page.

Let's move on and assume you have a token. You can configure the token either in .env file:

TELEGRAM_BOT_TOKEN=335237666:FFF45pYTYm9HkKWByaepSpcKAUWMo2uMF_9

or in config/telegram.php file:

<?php

return [
    'bot_token' => '335237666:FFF45pYTYm9HkKWByaepSpcKAUWMo2uMF_9',
];

Of course, the token above is just an example, you have to specify your own token.

Set up your model

To notify user or any other notifiable entity you need to use Notifiable trait with your model and define routeNotificationForTelegram method, which will return a chat_id:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    // ...

    public function routeNotificationForTelegram()
    {
        return 993344556;
    }
}

At this point, you may wonder where to get a chat_id. The answer is it's up to you! You can create a webhook to receive updates for your bot and collect chat ids, or you can specify ids manually for certain users.

To get started, you can send Hello! message to your bot and then get message details by requesting API method:

curl https://api.telegram.org/bot<your_token_here>/getUpdates

You will receive a JSON in return:

{
    "ok": true,
    "result": [
        {
            "message": {
                "chat": {
                    "id": 993344556 // this is what we were looking for 
                    // ...
                }
            }
        }
    ]
}

Usage example

if you installed the package and configured a model you're ready to make your first Telegram notification. You can create a new notification using artisan command:

php artisan make:notification TelegramNotification

And again, TelegramNotification here is just an example, you can specify any name you want.

Now, you can go to app/Notifications folder and you'll see TelegramNotification.php file. In via method specify TelegramChannel::class and initialize a new TelegramMessage instance in toTelegram method:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

use TelegramNotifications\TelegramChannel;
use TelegramNotifications\Messages\TelegramMessage;

class TelegramNotification extends Notification
{
    use Queueable;

    public function via()
    {
        return [TelegramChannel::class];
    }

    public function toTelegram()
    {
        return (new TelegramMessage())->text('Hello, world!');
    }
}

To send the notification use notify method with notifiable entity.

Let's say we have an authenticated user and we want to send a message from a route callback. We can do it like this:

<?php

use \App\Notifications\TelegramNotification;

Route::post('/', function () {
    Auth::user()->notify(new TelegramNotification());
});

Advanced Usage

You can send either a single message or a message collection at once.

Single Message

Each message class represents certain type of information you can deliver to a user. To send a message return a new instance of necessary type from toTelegram method:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

use TelegramNotifications\TelegramChannel;
use TelegramNotifications\Messages\TelegramMessage;

class TelegramNotification extends Notification
{
    use Queueable;

    public function via()
    {
        return [TelegramChannel::class];
    }

    public function toTelegram()
    {
        // to set any required or optional field use
        // setter, which name is field name in camelCase
        return (new TelegramMessage())
            ->text('Hello, world!')
            ->disableNotification(true);
    }
}

You can also pass parameters to the constructor, to be more explicit:

<?php

new TelegramMessage([
    'text' => 'Hello, world!',
    'disable_notification' => true
]);

Available message types are listed below.

TelegramMessage

TelegramNotifications\Messages\TelegramMessage

TelegramPhoto

TelegramNotifications\Messages\TelegramPhoto

TelegramAudio

TelegramNotifications\Messages\TelegramAudio

TelegramDocument

TelegramNotifications\Messages\TelegramDocument

TelegramSticker

TelegramNotifications\Messages\TelegramSticker

TelegramVideo

TelegramNotifications\Messages\TelegramVideo

TelegramVoice

TelegramNotifications\Messages\TelegramVoice

TelegramLocation

TelegramNotifications\Messages\TelegramLocation

TelegramVenue

TelegramNotifications\Messages\TelegramVenue

TelegramContact

TelegramNotifications\Messages\TelegramContact

Message Collection

Instead of sending one message at once you can send bunch of messages using TelegramCollection:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

use TelegramNotifications\TelegramChannel;
use TelegramNotifications\Messages\TelegramCollection;

class TelegramNotification extends Notification
{
    use Queueable;

    public function via()
    {
        return [TelegramChannel::class];
    }

    public function toTelegram()
    {
        return (new TelegramCollection())
            ->message(['text' => 'Hello, world!'])
            ->location(['latitude' => 55.755768, 'longitude' => 37.617671])
            // ...
            ->sticker(['sticker' => 'CAADBQADJwEAAl7ylwK4Q0M5P7UxhQI']);
    }
}

Each method of the collection creates corresponding message instance and puts it in the collection. Available methods are listed below: