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.

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

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Bluesky notification channel for Laravel image

Bluesky notification channel for Laravel

Read article
Sprout Multitenancy Package for Laravel image

Sprout Multitenancy Package for Laravel

Read article
Creating a CLI Application With Laravel and Docker image

Creating a CLI Application With Laravel and Docker

Read article
Laravel Herd Adds Native MongoDB Support image

Laravel Herd Adds Native MongoDB Support

Read article
How to Create Tech Videos for YouTube with Josh Cirre image

How to Create Tech Videos for YouTube with Josh Cirre

Read article
Integrate Unsplash in Your Laravel Application image

Integrate Unsplash in Your Laravel Application

Read article