loading...
Cover image for Telegram Bot with Laravel Framework Tutorial

Telegram Bot with Laravel Framework Tutorial

yongkylie profile image Yongky Ali ・5 min read

Chat bot’s popularity has been growing these past years because of it’s great functionality and reliability to handle some cases in business. And also, Bot has been supported by lots of instant messaging service provider such as Telegram, Line, Facebook, etc. On the other side, Laravel is one of the most popular framework to build web applications written in PHP.

In this article we will try to make a simple chat bot for Telegram messaging platform. This tutorial will cover some topics such as:

  1. Creating new Laravel project.
  2. Creating Telegram bot.
  3. Integrating your Telegram bot to Laravel.
  4. Handling Telegram bot updates.
  5. Sending messages.
  6. What's next?

Getting Started

Here are some requirements before getting started:

  1. Make sure you have Composer installed in your working machine. If you haven’t, go to the official Composer website and follow the instructions to install it.
  2. Basic knowledge of PHP programming language.
  3. Telegram account, and Telegram app installed in your device.

Completed code example of this tutorial is available on this GitHub repository.

GitHub logo yongkyali / telegram-laravel-tutorial

Telegram Bot tutorial with Laravel Framework

Create a new Laravel Project

You may start a new Laravel project in any directory in your machine as you like. For further and more detailed information about creating new Laravel project, check out instructions in the official documentation.

Let’s get started!

Open your terminal and in your local directory simply run:

composer create-project --prefer-dist laravel/laravel blog

Now, your should have blog folder containing Laravel project. Go to that directory by running cd blog.

To make sure everything is going as planned, go inside blog directory and run php artisan serve to start the web server we just created. Your application should run at localhost:8000.

localhost:8000 preview

Create a Telegram Bot

Great! Now we have our Laravel project ready to roll. Next, let’s create our Telegram Bot! If you want to learn more about Telegram bot, I prefer you to explore about it here.

First, open your Telegram app, and go find @botfather . BotFather is a bot created by Telegram to manage and rule all other bots (imagine BotFather is a GodFather of all bots).

BotFather in Telegram

Start a conversation with BotFather, by tapping Start. After that, type /newbot and follow all of the instruction provided. By the end of the interaction, you will get some of confirmation like this:

Done! Congratulations on your new bot. You will find it at t.me/YOUR_BOT_USERNAME. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

In the message sent by BotFather, you will get your bot’s access token. We will be using this token to identify your bot and work as your bot’s secret signature key. Make sure you keep the token private! If someone else got your token, they could access and do commands on your bot’s behalf.

Okay! Now we have our Bot, our BOT_TOKEN and our Laravel project ready to go!

Integrating Telegram Bot to Laravel

In this tutorial, we will use telegram-bot-sdk. This SDK helps us to do any methods or operations easily from our Laravel project. This time, we will use dev-develop version (the stable version is quite out-dated; this article will be updated after the v3.0 became stable version).

Go to our Laravel project directory and run composer require irazasyed/telegram-bot-sdk dev-develop. Then after the installation completed, run php artisan vendor:publish to publish telegram configuration file. The configuration file should be located now in config/telegram.php.

Now, let’s connect everything we’ve done so far! Inside telegram.php you should see lots of config regarding to the bot. Let’s take a look at "bots" key. Here inside mybotkey, change username value to your Telegram bot username and change token value to your access token given by BotFather.

config/telegram.php configuration file

Handling Telegram Updates

Now, we got our Bot access token linked with our project. Next, let’s handle Telegram Updates.

What is Telegram Update? According to official docs,

Every interaction user made with your bot will be called as Update. Every Update will be formatted as JSON-serialized objects.

So by that, Updates are an Object containing every interaction made to our bots. For example when someone initiate a chat with our bot, an update will be made. Or when our bot added to a chat group / super group, an update will be made.

To access Telegram Updates, we will make a new API route to test it out. Inside routes/api.php, let’s make a new API route to get telegram updates as shown below.

<?php
use Illuminate\Http\Request;
use Telegram;
...
Route::post('/bot/getupdates', function() {
    $updates = Telegram::getUpdates();
    return (json_encode($updates));
});

Alright! We got API route called /bot/getupdates to receive updates from Telegram server. And also, don’t forget to use Telegram class. By successfully getting Updates, we could choose how to act accordingly to every action user did with our bot including inviting to chat group, processing commands, or just simply replying to a chat.

This method of getting updates is using long polling to fetch updates. For advanced usage, you can set up webhook for better user experience.

Sending Messages

The real fun, sending messages.

In this section, we will try to send a message to group, super group, channel or simply to individual user. We will use sendMessage method to send a message. Inside routes/api.php, let’s make a new API route as shown below:

<?php
...
Route::post('bot/sendmessage', function() {
    Telegram::sendMessage([
        'chat_id' => 'RECIPIENT_CHAT_ID',
        'text' => 'Hello world!'
    ]);
    return;
});
...

Let’s get through the details of code we just wrote. As we can see, sendMessage receive few parameters such as :

  1. chat_id: This is your recipient’s chat ID. Every user, channel, group, or super group has it’s own unique chat ID. To get the chat_id, the easiest way is try to chat with our bot and get the chat_id via getUpdates method. For group, super group or channel, we need to invite the bot first as member to get the chat_id.
  2. text : String or integer to be sent as a message.

Note: You could only send a message to user using this method if the specific user ever started a conversation with the bot. For group, supergroup or channel, the bot need to be set as Admin to be able to send messages.

Now, What's Next?

Other methods such as sending photos, showing keyboards, sending emojis or GIF are supported by the SDK. Check out all methods available Telegram API official documentation for more information.

If you have any questions or help, feel free to hit me up at twitter.

Cheers!

Posted on by:

yongkylie profile

Yongky Ali

@yongkylie

If you keep trying, you will get there eventually.

Discussion

markdown guide