Home / API / Create a Telegram Bot API using Laravel

Create a Telegram Bot API using Laravel

In this article let us create a telegram bot API using laravel. Telegram and Facebook Bots are now implemented by various popular companies to increase their customer base and keep them engaged. You can learn more about the Telegram Bot here. It is very simple to understand how it works. A user sends a messages as a command that will be listed by you. You then read the command and respond with a meaningful information and that’s it!

Here is the official documentation for Telegram Bot. First grab a copy of the Telegram Bot PHP SDK for Laravel and the documentation can be found on the same link.

For the newbies check out the Getting started – Laravel. You can use composer to install laravel or simply download a copy of Laravel from github but you still require composer for scaffolding.

Requirements:

1. Composer

Assuming you have set up Laravel (in our case Laravel 5.2) lets get started by adding the Laravel SDK. Add the following code to composer.json file

Now run composer update. This will scaffold everything inside you composer.json file.

You need to encrypt your laravel application to make it secure. When composer finishes updating change the file .env.example to .env and run the following command

php artisan key:generate

COnfiguration

This will generate an API_KEY for your laravel application hence secure. Now add provider and facade in config/app.php for Telegram package

Provider
Telegram\Bot\Laravel\TelegramServiceProvider::class

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

publish a configuration file for Telegram package which will create config/telegram.php
php artisan vendor:publish

Guzzle is a client for sending HTTP requests. TIP: If you get CURL error while running the application set $conf[CURLOPT_SSL_VERIFYPEER] = false; in vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php

Now we have set up Laravel with required SDK. Lets get started with creation of Bots

Bot creation

Open Telegram and search for @botfather. Choose the chat and click start at the bottom of chat.

botfather-jqueryajaxphp

and then follow these steps,

Step 1: write the command /newbot and give it a name.
Step 2: Set a username for your bot. People will be able to find you with this name @mybot. Note that your username should end with ‘bot’
Step 3: Congratulations you have created your first bot! You should now see a token generated for you to use which is something like this 2995—–:AAGDJCKYq_UhkVu2rhmwh8jf4bqZsxxxxxx
Step 4: Set the description of your app using /setdescription Now you will be asked to choose the BOT. Click on your BOT name and set the description.

Now we need to configure the BOT API token in our Laravel application. There are many ways to configure the code I am going to use the easy way. Simply open the .env file and set the global environment variable TELEGRAM_BOT_TOKEN=2995—–:AAGDJCKYq_UhkVu2rhmwh8jf4bqZsxxxxxx

Test if the SDK is properly set up. Set a route and a controller to see if we are able to retrieve our own information using the getMe() methods

Controller

Create ApiController via command prompt

php artisan make:controller ApiController

app/http/routes.php

Route::get('me', 'ApiController@me');

app/http/controllers/ApiController.php

Now run the following URL
http://mydomain.com/me

Everything is fine if you see something like this

{"id":2995XXXXX,"first_name":"jQuery Ajax PHP","username":"jqueryajaxphpbot"}

Webhook

Now we can work on a real world use case. The BOT will present the user a list of commands. The user can choose any one to which the BOT will respond.

There are two methods to respond to user request.

1. Without SSL
2. With SSL (webhooks) – recommended

Method 1 (without SSL)

Polling – Here you need to manually trigger the URL or set an interval where the script executes

First search for your BOT in telegram like this @jqueryajaxphpbot. Select your bot and click the start button to initiate a chat. At this point the BOT will not respond to you because you have to read the user messages using getUpdates method Doc Link

Upon clicking the start button a command /start will sent to the BOT. We can now check the command sent to the BOT. Set a route and controller method to retrieve updates

Route::get('updates', 'ApiController@updates'

Now run the following URL
http://mydomain.com/updates

You should see an output like this

Now respond to the sender. For this we need to use the sendMessage method Doc link

Set a route and controller method

Route::get('respond', 'ApiController@respond');

Now run the following URL and witness the first response of your BOT!

http://mydomain.com/respond

That is awesome! Isn’t it? Now we can process the request and send appropriate response based on the command given by sender. Modify ApiController.php to the following

So our BOT will accept only /start, /menu, /website and /contact. Anything else will trigger the default method. Add the other three methods to ApiController

Now you should be able to see appropriate messages to the command the user sends.

Test case

1. Type the command /menu
2. Load the URL http://mydomain.com/respond. This should trigger the BOT to send a response
3. Repeat (1.) and (2.) with commands /menu, /website, /contact and SomeRandomText

You should be able to see the appropriate responses

You can choose to set POLLING for every 5 seconds so as to avoid refreshing the URL everytime you send command to your BOT. This is however not the recommended way as this would cause server performance issues and you may miss commands of certain users. So the better way is to use SSL and set webhook.

Method 2 (setting Webhook – SSL required)

Doc link

Webhook work only with HTTPS website. You can get a free SSL from Cloudflare. Assuming that you have set up SSL on your domain let’s get into work

The first step is to create a route and controller method. set up the webhook URL using the setWebhook method.

Route::get('setWebHook', 'ApiController@setWebHook);

Then create a POST url which you just hooked.

Route::post('my-bot-token/webhook', 'ApiController@setWebHook');

Laravel requires a token for POST request which will cause an error while setting up webhook and receiving updates. So disable token check for this route

app/Http/Middleware/VerifyCsrfToken.php

Now to set the webhook simply run following URL. If webhook is set you will see a success message.

http://mydomain.com/setWebHook

NOTE:

When webhook is set the getUpdates method will not work. To remove webhook you can use the removeWebHook method.

So you need to rewrite the ApiController’s respond method in webhook method

And that’s it. Every request from user will be hooked to the POST url you just set up. You can build a Database driver BOT with Artificial Intelligence here. Remind people of their appointments, notify them about news updates and much more! I will be writing more on BOTS here after so stay tuned!

Download Laravel 5.2 Base   Preview

About Ashik

I am a Full Stack Developer and love to work on APIs and Apps. Hardcore lover of Ionic and Laravel <3

Check Also

Private chatroom using socket.io, NodeJS and MySQL

As I promised to write a tutorial on Private chatroom with MySQL DB in the …

  • Pingback: Telegram Bot API – Keyboards and Callbacks – jQuery Ajax PHP()

  • Dan

    Nice guide) Have you got experience how to create multi bot with BotManager class? https://github.com/irazasyed/telegram-bot-sdk/blob/master/src/BotsManager.php

    • its quite easy. In the config/telegram.php file I manage my bots like this

      ‘bots’ => [
      ‘common’ => [
      ‘username’ => ‘citibankivrbot’,
      ‘token’ => env(‘TELEGRAM_BOT_TOKEN’),
      ‘commands’ => [
      // AcmeProjectCommandsMyTelegramBotBotCommand::class
      ],
      ],

      ‘bus’ => [
      ‘username’ => ‘ezinfotechbusbot’,
      ‘token’ => env(‘TELEGRAM_BOT_TOKEN_BUS’),
      ],

      ‘apt’ => [
      ‘username’ => ‘aptransportbot’,
      ‘token’ => env(‘TELEGRAM_BOT_TOKEN_APT’),
      ],

      ‘sat’ => [
      ‘username’ => ‘satbot’,
      ‘token’ => env(‘TELEGRAM_BOT_TOKEN_SAT’),
      ],
      ],

      and this is how you access the bot by name

      Telegram::Bot(‘apt’)->sendMessage([
      ‘chat_id’ => $chatid,
      ‘text’ => ‘mytext’,
      ‘reply_markup’ => $keyboard
      ]);

      • Dan

        big thanks.

Do you wan't to get notified?

I will not spam your inbox. I will only send email whenever I publish a new article or to share information about technology

You have Successfully Subscribed!