DEV Community

Cover image for How to Send Telegram Messages in Laravel
Ash Allen
Ash Allen

Posted on • Originally published at ashallendesign.co.uk

How to Send Telegram Messages in Laravel

Introduction

When you're building a Laravel application, you might want to send notifications to users via Telegram. This is useful for things like sending updates and alerts. For example, I'm subscribed to Telegram notifications on sites like Oh Dear to notify me of any downtime or issues with my sites. This means if any of my sites or my clients' sites go down, I get an instant notification via Telegram so I can quickly investigate and resolve the issue.

In this article, we're going to take a quick look at how to send Telegram messages from your Laravel application.

Related Articles

Before we get stuck in, you might also be interested in some of my other notification-related articles:

Setting Up Your Telegram Bot

In order to send messages via Telegram, you'll first need to create a bot in the Telegram app. This bot will be responsible for sending messages to users on your behalf.

The Telegram documentation provides a nice guide on creating a bot. The basics are that you need to start a chat with the "BotFather" user in Telegram. This will launch a conversation where you can create and manage your bots.

Telegram bots are incredibly powerful and are packed with features. So I recommend spending some time exploring the different options available when setting up your bot so it best suits your needs.

Installation

To send the Telegram notifications, we'll use the laravel-notification-channels/telegram package. The package provides a new notification channel that taps into Laravel's existing notification system, making it super easy to send Telegram messages. At the time of writing this article, the package has 3.1 million installs and 1.1k stars on GitHub.

You can find the GitHub repo for the package here: https://github.com/laravel-notification-channels/telegram

To install the package, you can run the following command in your project root:

composer require laravel-notification-channels/telegram
Enter fullscreen mode Exit fullscreen mode

The package should now be installed and ready to use.

Getting the Chat ID

In order to send a message from your Telegram bot to a user, you first need to know the user's chat ID. A bot cannot initiate a conversation with a user. This means the user must have first interacted with the bot (for example, by sending it a message or clicking the "Start" button within Telegram) to start the chat.

Once the user has interacted with your bot and started a chat, you can retrieve the chat ID so it can be used to send messages. There are multiple approaches to getting the chat ID. For example, you could use the notification channel package's built-in class to fetch channel updates. Then you can search through the updates to find the chat ID of the user you want to send a message to. The package's documentation shows how you can do this.

Another approach is to configure your Telegram bot to send a webhook to your Laravel application when a conversation starts. From there, you can store the chat ID (sent in the webhook) in your database against the user.

However, I'm not going to cover this in detail here, as it's beyond the scope of this article, and you'll use a different approach depending on your use case.

But please remember, whichever approach you use, keep security in mind. You don't want to add any vulnerabilities that allow someone to send messages to arbitrary chat IDs.

Sending Notifications

For Laravel's notification system to know where to send Telegram notifications, we need to define a new routeNotificationForTelegram method on the notifiable model (usually App\Models\User). In this case, we'll assume that we're storing the user's Telegram chat ID in a telegram_chat_id column on the users table. We can then return this value from the routeNotificationForTelegram method like so:

declare(strict_types=1);

namespace App\Models;

use App\Casts\NotificationPreferences;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

final class User extends Authenticatable
{
    use Notifiable;

    // ...

    public function routeNotificationForTelegram(): int
    {
        return $this->telegram_chat_id;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now let's create our notification. For the purposes of this article, we'll create a simple notification class that can notify a user when the status of their order in our online store is updated. We'll include a button in the Telegram message that directs the user to our web application to view their order.

We can create the notification by running the following Artisan command:

php artisan make:notification OrderUpdated
Enter fullscreen mode Exit fullscreen mode

We should now have a new notification class at app/Notifications/OrderUpdated.php. Let's update this class to send a Telegram message, and then we'll discuss what's being done:

declare(strict_types=1);

namespace App\Notifications;

use App\Models\Order;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use NotificationChannels\Telegram\TelegramMessage;

final class OrderUpdated extends Notification
{
    use Queueable;

    public function __construct(private Order $order)
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(): array
    {
        return ['mail', 'telegram'];
    }

    // ...

    public function toTelegram($notifiable): TelegramMessage
    {
        return TelegramMessage::create()
            ->line('Hello there!')
            ->line("Your order status has been updated")
            ->button('View Order', route('order.show', $this->order));
    }

}
Enter fullscreen mode Exit fullscreen mode

In the code example above, we can see that we're starting by passing in an App\Models\Order instance to the notification's constructor. We haven't included the code for this model for brevity, but we can assume it holds information about a user's order.

We're then using the via method to specify that we want to send the notification via both email and Telegram. In this case, we're only focusing on the Telegram part, so I've left out the email-specific code.

Next, we have the toTelegram method. This method builds and returns the actual Telegram message to be sent to the user. We're using the NotificationChannels\Telegram\TelegramMessage class provided by the notification channel package to create a new message. We're defining that the message should include two lines of text, followed by a button that the user can click to view their order.

Now that we've defined our notification, we should be able to send it to our user. Let's take this super simple code snippet, which finds a user and an order, then sends the notification to the user:

use App\Models\Order;
use App\Models\User;
use App\Notifications\OrderUpdated;

$user = User::find(1);
$order = Order::find(1);

$user->notify(new OrderUpdated($order));
Enter fullscreen mode Exit fullscreen mode

If everything is configured correctly, the user should receive a Telegram message from your bot notifying them that their order status has been updated.

Sending a Location

The package also allows us to send different types of messages. For example, you can send a location message, which will display a location pin on a map in the Telegram app. You can do this by passing the latitude and longitude to the NotificationChannels\Telegram\TelegramLocation class like so:

declare(strict_types=1);

namespace App\Notifications;

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

final class OrderUpdated extends Notification
{
    // ...

    public function toTelegram($notifiable): TelegramLocation
    {
        return TelegramLocation::create()
            ->latitude('51.5072')
            ->longitude('0.1276');
    }
}
Enter fullscreen mode Exit fullscreen mode

Sending Images

You can also send images to users via Telegram. You can do this by using the NotificationChannels\Telegram\TelegramFile class and specifying the file URL or path along with the type of file (in this case, a photo) like so:

declare(strict_types=1);

namespace App\Notifications;

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

final class OrderUpdated extends Notification
{
    // ...

    public function toTelegram($notifiable): TelegramFile
    {
        return TelegramFile::create()
            ->content('Here is an image:')
            ->file(file: 'https://example.com/image.png', type: 'photo');
    }
}
Enter fullscreen mode Exit fullscreen mode

Other Messages Types

The package also provides other message types that you can send, such as:

  • Audio
  • Document
  • Polls
  • Stickers
  • GIFs
  • Venues

I think the documentation already does a pretty great job of explaining how to send these different message types, along with examples of what the message will look like in Telegram to the user. So if you're interested in sending any of these other message types, I recommend checking out the package's documentation.

On-Demand Notifications

There may also be times when you want to send a notification to a Telegram chat ID that isn't associated with a user in your application. You can do this by sending an on-demand notification using the Illuminate\Support\Facades\Notification::route method like so:

use App\Models\Order;
use App\Notifications\OrderUpdated;
use Illuminate\Support\Facades\Notification;

$order = Order::find(1);

Notification::route('telegram', '123456789')
    ->notify(new OrderUpdated($order));
Enter fullscreen mode Exit fullscreen mode

In the example above, we've specified that we should send the App\Notifications\OrderUpdated notification to the Telegram chat ID 123456789. This allows you to send notifications to arbitrary chat IDs without needing to have a user model associated with them, which can be pretty handy.

Conclusion

Hopefully, this article has given you a quick overview of the basics of sending Telegram messages in Laravel using the laravel-notification-channels/telegram package. The package makes it super easy to integrate Telegram notifications into your Laravel application by leveraging Laravel's existing notification system.

If you enjoyed reading this post, you might be interested in checking out my 220+ page ebook "Battle Ready Laravel" which covers similar topics in more depth.

Or, you might want to check out my other 440+ page ebook "Consuming APIs in Laravel" which teaches you how to use Laravel to consume APIs from other services.

If you're interested in getting updated each time I publish a new post, feel free to sign up for my newsletter.

Keep on building awesome stuff! 🚀

Top comments (0)