Auto Publishing to Telegram using Notification Channels

Published on by

Auto Publishing to Telegram using Notification Channels image

Laravel Notifications are great when you need to send notifications out through a variety of channels. Based on the documentation the original use case for these is to send quick information messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an “Invoice Paid” notification to your users via the email and SMS channels.

However, they don’t have to be restricted just those types of notifications. For example, on this site every time a new post is published I want it to go out to all the various social channels and the community has created a lot of drivers for various services.

One new area that I created a few months back, is a read-only Laravel News Telegram group, and in the past, I would manually add the day’s new posts into it. As you can imagine one day I forgot to do this, then the next, and so on. I knew I had to automate the sending of new posts and that is where the Telegram Notification package comes in, let’s take a look at how to get this setup and auto sending notifications to your Telegram room.

Creating a Telegram Bot

Before you can send messages to a room, you have to create a bot. To start, send a new message to @BotFather, and it goes like this:

You: /newbot
BotFather: Alright, a new bot. How are we going to call it? Please choose a name for your bot.
 
You: MyTestBot
BotFather: Good. Now let's choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.
 
You: MyNewBot
BotFather: Done! Congratulations on your new bot. ... Use this token: xxxxxx

Now you will need that token later to add to your .env file so just keep it handy for now.

Add the bot to your room

Open your Telegram room and go to the settings -> administrators and add the bot you just created to the channel. This gives it access to post new messages to the room.

Install Telegram Notifications

Installation is typical for any Laravel package. First require the package:

composer require laravel-notification-channels/telegram

Add it to the providers in app.php:

'providers' => [
...
NotificationChannels\Telegram\TelegramServiceProvider::class,
],

Add the config array:

// config/services.php
...
'telegram-bot-api' => [
'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE')
],

Finally, open .env and add your token:

TELEGRAM_BOT_TOKEN=1234:232jkl42l4j23kl

Create a new notification class

For my use case I am going to send a notification when a new post is published so I create a new PostPublished notification class through artisan:

php artisan make:notification PostPublished

Now open the file and adjust the via method to tell it to use the TelegramChannel:

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

Next, create a toTelegram method that will contain the details you want sent:

public function toTelegram($post)
{
return TelegramMessage::create()
->to('@laravelnews')
->content($post->title.' https://laravel-news.com/'. $post->uri);
}

In this case, it’s sending to the @laravelnews room with the content of the post title and a link to the post.

Add the notifiable trait

Notifications can be sent in one of two ways. Either through the Notification facade or by adding the Notifiable trait to a model. The facade is recommended when you need to send a notification to multiple notifiable entities such as a collection of users.

In this example, it’s only going out based on one item, so I added the trait to my Post model.

use Illuminate\Notifications\Notifiable;
class Post extends Model
{
use Notifiable;

Sending your first notification

Now, with everything setup and ready all that is left to do is send our first notification. Fetch a single item from the Model and then fire off the notification:

$post = \App\Post::find(1);
$post->notify(new \App\Notifications\PostPublished());

If all is correct, you’ll see it instantly in your Telegram channel.

With the setup of this site using WordPress as a backend when my syncing system runs and finds a creates a new Post it now automatically sends to Telegram and Twitter which I covered in a previous post.

If you are a Telegram user join the @laravelnews group and I’ve created a simple Laravel sticker pack. It’s only two stickers but, hopefully, one day I’ll get to add more to it.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Anonymous Event Broadcasting in Laravel 11.5 image

Anonymous Event Broadcasting in Laravel 11.5

Read article
Microsoft Clarity Integration for Laravel image

Microsoft Clarity Integration for Laravel

Read article
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Read article
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article