Using Telegram Messenger for Laravel application notifications

Telegram is new messenger similar to Viber, WhatsApp and FB messenger in terms of features, but superior when it comes to security. It is using many security mechanisms including strong encryption and it is extremely fast.

It is built for all platforms, Android, iPhone/iPad, Windows, PC/Mac/Linux, and recently they revealed Bots support.

Basically our apps can send messages to group or single chats on Telegram over bot accounts.

This could be useful for app monitoring, sign-up notifications, new payments, critical errors, I tried in on couple of production systems and it is working great.

The best part, it's completely free for now.

In this tutorial I will connect simple Laravel app with Telegram API and enable notifications on click of a button.

You can find entire code used in this tutorial on Github.

You can test Live Demo here.

First I will create new Laravel application with Laravel installer.

laravel new telegram

After this I need to create .env file, and generate application key with php artisan key:generate.

Telegram Bot API Laravel Package

Telegram API posses PHP SDK but recently I discovered Laravel based package developed by Syed Irfaq R. and published on Github so I will use it. You can find more info about this package at https://github.com/irazasyed/telegram-bot-sdk .

I will pull this Laravel package into composer with composer require irazasyed/telegram-bot-sdk

After this I need to add TelegramServiceProvider to app.php and add facade.

Telegram\Bot\Laravel\TelegramServiceProvider::class
'Telegram'  => Telegram\Bot\Laravel\Facades\Telegram::class

Now everything that is left is to publish telegram configuration with:

php artisan vendor:publish --provider="Telegram\Bot\Laravel\TelegramServiceProvider"

Configuration file is named telegram.php and there I need to add bot token, which means I need to create bot first.

Creating Bot

Someone at telegram posses good sense of humor cause in order to create new bot you need to talk to BotFather from Telegram Messenger. Once when you install Telegram you can find BotFather by visiting this link https://telegram.me/botfather .

Communication with BotFather is performed over chat commands. To create new bot I will type /newbot into thread with BotFather. He will ask for new bot name, I will name mine Codingo, after this he asks for bot username (CodingoBot).

Success! BotFather will response with status message which contains needed token.

Creating CodingoBot with BotFather

Creating CodingoBot with BotFather.

Now I have bot token, and I will insert it into .env file under key TELEGRAM_BOT_TOKEN.

Bot can send messages to any number of users, for this one I want it to send notifications to group of users.

Creating Telegram Group for receiving notifications

Creating basic group in Telegram is pretty easy, click on Search icon will open popup for group creation. CodingoBot is not visible so I need to search for it, after that I will select my personal account and that's it. I will name this group Codingo.

Codingo Telegram Group

Codingo Telegram Group

As you can see my CodingoBot is having nice profile picture, I accomplished that using /setuserpic command in BotFather thread. Telegram will ask which bot needs new picture and after all you need to do is drag-n-drop wanted image.

Obtaining group CHAT_ID

To send messages to anyone on Telegram or any group I need CHAT_ID, that is integer which identifies certain message thread in Telegram.

There is no easy way to see group chat_id as far as I know. For this I will create method which will print CodingoBot updates. When system calls getUpdates method, Telegram will return all new activity for that bot. From there I will be able to see in which groups this bot belongs and to see related chat_id numbers.

I will create Telegram controller and route get-updates which points to getUpdates method of new controller.

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Telegram\Bot\Laravel\Facades\Telegram;

class TelegramController extends Controller
{

    public function getHome()
    {
        return view('home');
    }

    public function getUpdates()
    {
        $updates = Telegram::getUpdates();
        dd($updates);
    }
}

As you can see I am injecting Telegram instance into constructor and in getUpdates method I am just printing raw response from same Telegram API method.

Get updates response

Get updates response

Each update posses message object with chat array inside. I need the one with title Codingo and it has id of -253307. With this information CodingoBot can send messages to Codingo group.

It may happen that there are no updates for this bot, then you can provoke few actions related to bot. Easiest idea is to kick that bot from group conversation and add it back. After that when you visit get-updates link you will see 2 new actions.

In real application I would obtain this chat id in programmatic way, but for this tutorial I am using the simplest way.

Sending message

For sending I will have simple form with one textarea field and submit button. On server side I will check is message field valid and if it is fine I will pass that message to sendMessage API method.

    public function getSendMessage()
    {
        return view('send-message');
    }

    public function postSendMessage(Request $request)
    {
        $rules = [
            'message' => 'required'
        ];

        $validator = Validator::make($request->all(), $rules);

        if($validator->fails())
        {
            return redirect()->back()
                ->with('status', 'danger')
                ->with('message', 'Message is required');
        }

        Telegram::sendMessage([
            'chat_id' => env('GROUP_ID'),
            'text' => $request->get('message')
        ]);

        return redirect()->back()
            ->with('status', 'success')
            ->with('message', 'Message sent');
    }

For frontend I am using basic Bootstrap layout, from one of their examples.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="Laravel Telegram Chat Bot Tutorial and Live Demo. Send messages from browser to Telegram group.">

    <meta property="fb:app_id" content="356607781215457" />
    <meta property="og:locale" content="en_US" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Laravel Telegram Chat Bot Live Demo | Codingo Tuts">
    <meta property="og:description" content="Laravel Telegram Chat Bot Tutorial and Live Demo. Send messages from browser to Telegram group.">
    <meta property="og:url" content="https://demo2.codingo.me/">
    <meta property="og:image" content="https://tuts.codingo.me/wp-content/uploads/2015/07/telegram-messenger-800x405.jpg">
    <meta property="og:site_name" content="Codingo Demo">
    <meta property="og:image:type" content="image/png">
    <meta property="article:author" content="https://www.facebook.com/ivanradunovic" />

    <link rel="shortcut icon" href="https://codingo.me/assets/img/box.png">

    <title>Laravel Telegram Chat Bot Live Demo - Codingo Tuts</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/css/style.css">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>

<div class="container">
    <div class="header clearfix">
        <nav>
            <ul class="nav nav-pills pull-right">
                <li role="presentation" class="{{ request()->path() == '/' ? 'active' : '' }}"><a href="/"><i class="fa fa-home"></i> Home</a></li>
                <li role="presentation" class="{{ request()->path() == 'send' ? 'active' : '' }}"><a href="/send"><i class="fa fa-send"></i> Send</a></li>
                <li role="presentation"><a href="https://tuts.codingo.me/using-telegram-messenger-for-laravel-application-notifications" title="External link to Tuts"><i class="fa fa-book"></i> Tutorial</a></li>
                <li role="presentation"><a href="https://github.com/codingo-me/telegram-laravel"><i class="fa fa-github"></i> GitHub</a></li>
            </ul>
        </nav>
        <h3 class="text-muted">Laravel & Telegram</h3>
    </div>

    @yield('content')





    <footer class="footer">
        <p>&copy; 2016 Codingo LTD</p>
    </footer>

</div> <!-- /container -->


<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script>
    (function () {
        'use strict';

        if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
            var msViewportStyle = document.createElement('style')
            msViewportStyle.appendChild(
                    document.createTextNode(
                            '@-ms-viewport{width:auto!important}'
                    )
            )
            document.querySelector('head').appendChild(msViewportStyle)
        }

    })();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

And page with message form looks like this:

@extends('layout')

@section('content')

        <div class="row">
            <div class="col-md-12">
                <form action="/send" class="form-signin" method="post">
                    {{ csrf_field() }}
                    <h2 class="form-signin-heading">Send Message as Telegram Bot</h2>
                    <label for="inputText" class="sr-only">Message</label>
                    <textarea name="message" type="text" id="inputText" class="form-control" placeholder="Message" required autofocus></textarea>
                    <br />
                    <button class="btn btn-lg btn-primary btn-block" type="submit">Send Message</button>
                </form>
                <br />
                @if(Session::has('message'))
                    <div class="alert alert-{{ Session::get('status') }} status-box">
                        <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        {{ Session::get('message') }}
                    </div>
                @endif
            </div>
        </div>


@stop

There are 4 routes in web.php file:

<?php

Route::get('/', [email protected]');
Route::get('get-updates',   [email protected]');
Route::get('send',  [email protected]');
Route::post('send', [email protected]');

Now everything works fine, when I submit message it is sent almost instantly. In real applications I would use queues for sending these kind of notifications, cause I don't want for end users to wait for that.

Telegram Bot is the simplest way for sending notifications related to admin stuff. I don't need to take care of any infrastructure, pay bills, or loose time to learn how to use it. It is working on all my devices and I am informed in same moment when action occurs.

You can find entire code used in this tutorial on Github if you are curious to see how it works checkout Live Demo.
Online computer science courses to jumpstart your future.
WP Engine Managed WordPress Hosting

Trending

Newsletter

Subscribe to our newsletter for good news, sent out every month.

Tags