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:
- Creating new Laravel project.
- Creating Telegram bot.
- Integrating your Telegram bot to Laravel.
- Handling Telegram bot updates.
- Sending messages.
- What's next?
Getting Started
Here are some requirements before getting started:
- 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.
- Basic knowledge of PHP programming language.
- Telegram account, and Telegram app installed in your device.
Completed code example of this tutorial is available on this GitHub repository.
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
.
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).
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.
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 :
-
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 thechat_id
, the easiest way is try to chat with our bot and get the chat_id viagetUpdates
method. For group, super group or channel, we need to invite the bot first as member to get thechat_id
. -
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!
Top comments (0)