Simple Tutorial How to Create a Telegram Bot with Commands using the Telegram Bot API and the PHP programming language (part 1)

Smple Tutorial How to Create a Telegram Bot with Commands using the Telegram Bot API and the PHP programming language

Okay, before going into the discussion about Telegram bots, it's a good idea to briefly review Telegram first.

 



Telegram at a glance: What is Telegram and Why use Telegram?

Maybe those of you who have been lost looking for this, most likely already know what Telegram is. Just a review, yes, for some who may not know what Telegram is and why we should use / move to Telegram. Telegram is an instant messaging application (apps similar to WhatsApp, LINE, KakaoTalk) which is still less popular in Indonesia. Even though there are so many advantages to using Telegram when compared to other applications. This is an illustration of some of the advantages of Telegram.

From the picture above, you can see the advantages that exist in Telegram:

 



1. Private, in Telegram there is a feature where people can send messages to other people where the message will disappear in a few seconds (you can set the length). This feature is suitable for sending messages with a high level of confidentiality.
2. Cloud-based, the data is stored in the cloud so it can be accessed from various devices (tablets, smartphones, computers), not like WA which cannot be accessed from a computer. In addition, if there are friends who want to see history chat (perhaps to remember the romance of the era before breaking up with your ex), you can see everything as long as it hasn't been deleted. It's different from LINE, which if you scroll up, you'll get stuck to a certain part and some photos that have been around for a long time can't be opened anymore.
3. Message size on Telegram is smaller, so it doesn't consume a lot of bandwidth and arrives faster (it's really good if you get lost in the interior, you only get 1 signal and the internet connection from your cellphone can only EDGE or even GPRS.___.).

4. The servers are distributed, so the servers are located in several places, so it's safer (not across multiple devices) and faster (if the servers are close, it will automatically access them faster).

5. The API is open, which is very useful for developers . There are 2 types of APIs in Telegram, the regular Telegram API and the Bot API that we just want to discuss.
6. Free tis :D (he said forever). You don't have to pay annually after using WA for a year and there are no ads, what makes Telegram a non-profit organization, aka not looking for profit (he said...) .
7. More secure.
8. The size of the file that can be sent is bigger. Unlike WA, where the limit is only around 16-30 MB, in Telegram you don't need to worry because the maximum limit of files that can be sent is up to 1.5 GB. :D. No need to bother looking for a way to root the WA application, just to send large files.

What is Telegram Bot?

As previously explained, there are 2 APIs in Telegram, the regular Telegram API and the Telegram Bot API. This Telegram Bot API uses a bot, a Telegram account that is run using software and has AI features. Bot can ngelakuin many things - rich ' to teach something, toys, nyari something, broadcast , remind about something (reminders), ngehubungin with other services, even until sent me a command / command to the device internet of things . For those who don't know what the internet of things is, the simple illustration is like a application smarthome . For example, when we send a command to the telegram bot, then the air conditioner in our house can automatically turn off by itself (perfect if we often forget to turn off the air conditioner at home). Another example is if we want to send an order to the bot so that our rice cooker will automatically cook the rice itself, so when we go home we can immediately eat rice *gayal*. That's cool, I can't wait for IoT to be a trend in Indonesia, as it is now happening in developed countries :D.

For those who want to try a kind of prototype or an example of a bot that has been made by someone else, here is an example of a bot that has been made and can be tried to find out more about bots. Yes, I'm just trying to get an idea of ​​how the bot implementation actually looks like. How to use an existing bot, just log in to Telegram, then add the name of the bot in the "search username" section.

  • @ImageBot – type the image you want to search for and the bot will send the image you are looking for
  • @TriviaBot – kind of like a quiz bot. can be used as a quiz game with friends.
  • @PollBot – this bot can be added to groups for polling or voting.
  • @AlertBot – create a reminder, just set the reminder time.
  • @HotOrBot – similar to matchmaking app, Tinder :D.
  • @GithubBot – can track updates on GitHub
  • @StoreBot -find new bots and rate the bots

Okay, maybe a quick review of Telegram, its advantages, and bot features is enough. Now getting to the bottom line: creating a usable Telegram bot. Here are the steps.
Make a Bot
1. Add a Telegram account with the name @BotFather
2. Type the command /newbot. Enter the desired bot name (which appears on the screen) and the username bot's (this one must be unique and end in "bot").
3. After that, we will get a token, similar to: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. This token cannot be distributed so that no one else takes over the bot that has been created. 

 4. After the bot is created, we can add the bot to the friends list 

5. When starting a chat, there will be a /start command. The bot won't respond to anything because we haven't written any code about what the bot will do when we type a certain command. To let the bot know what to do when we type a certain command, we need to code the program.

Receiving Orders
Bots can receive commands that we send in two ways, namely getUpdates and webHook.


For the first method (getUpdates):
Every few seconds, our program will ask the bot that we created "is there a user command or not?". If a user command is received by the bot, the command is immediately processed by the program and the program will answer the user's command (via the bot). Meanwhile, if there is no command, the program will not run anything.

As for the second way (webHook):
Every time the bot receives a command from the user, the bot will call our program (by calling the URL containing our program) and our program will answer the user's command (via the bot).

Oh yes, as additional information, Telegram only wants to receive messages via one of the methods above (webHook/getUpdates), so you can't use both at the same time.

When should we use one of these getUpdates/webHook methods?
The first method (getUpdates) is suitable if we don't have a server with a public IP, domain, and HTTPS. Unfortunately, in this way, commands can only be fetched every certain time interval on the computer/server where the program is stored (depending on what the user has specified) and can't really be realtime. Another effect, the computer/server where the program has to fetch updates every certain time interval and relatively larger resources computational and bandwidth required (but don't worry, the JSON file is really small in size). The plus point is that getUpdates is suitable for small-scale use that doesn't really require a fast response time or for those who want to try it first (it's perfect for newbies).
The second method (webHook) is suitable if we need a realtime one where each user enters a command, the program immediately answers the user's command. To use the webHook method, we need hosting, domain, and HTTPS with a public IP so that Telegram can call programs on that domain if our bot gets an order.
Additional tips: for the second method (webHook) so that it doesn't get hacked and spammed by other people, it's better if our program is stored in a very deep directory, if possible, the directory can be used with our token (or if you want to add it, you can) <- that this is a suggestion from his direct Telegram.

How to receive commands via getUpdates
Here I will explain about how our program retrieves commands sent to bots via getUpdates. We will discuss the first method first because it is more practical than the second. We can see the message the bot received by typing this URL into the browser:

where <bot token> is the token we got when creating the bot. So that the JSON file from the URL we typed can contain something, we can first send a message to the bot that we have created. After that, type the URL to receive commands via getUpdates. An example URL and the results are as follows: 

 



As shown in the image above, the return from telegram is a JSON file where each message has several attributes such as update_id, message_id, sender id, sender name, message body, etc. There are some extra parameters that we can add after getUpdates, including:
- timeout : long time to wait until there is a message (for polling)
- limit: the maximum number of messages you want to receive
- offset: the most important thing , to notify telegram that the message has been read by our program, so it doesn't need to be displayed again when we take updates at a later time. If we don't set the offset, our orders that have already been processed will be processed again. So if we type a command again, the program will run the previous command and the command we typed. The offset setting is done by looking at the update_id as shown in Figure 1 above, where the update_id is 947959739. To indicate that the command has been read by our program and doesn't need to be displayed again, we can add the offset=update_id+ parameter. 1 (in this case, update_id=947959739 so offset=947959740). An example of using offsets is shown in the image below. 

 



As shown in Figure 2 above, the message with update_id 947959739 has been marked as read so it is no longer displayed. So by adding ?offset=<update_id>+<certain number>, we can mark if the message/command with update_id and <specific number> the message after that has been read and no longer needs to be displayed again.

How to send a message via the sendMessage command
After the bot retrieves the command typed by the user, the bot can return an answer by sending a message back to the user. The way the bot sends a message back to this user is with the command sendMessage. Try typing in the browser (using the bot token we created) a URL like this:

https://api.telegram.org/bot<token bot>/sendMessage?chat_id=<chat id kita>&text=hello
where <token bot> is the token that has been obtained and <chat id we> is the chat_id of the user who will receive the message we send. To find out our chat_id, we can see from the JSON file above in the section

"chat":{"id":

Here, my chat_id is 135388637. You can match the chat_id with the chat_id of your own Telegram account.

Source Code for Sending Messages Via Telegram
Once we know how the Telegram bot sends messages to us, we can start creating a simple script to send messages to our Telegram account. The script to do this in the PHP programming language is as follows:

 

<?php
$token_bot="<token_bot>";
$data['chat_id']=<ID_penerima>;
$data['text']="<isi teks>";
function sendcommand($command,$token_bot,array $description=null)
{
$url="https://api.telegram.org/bot".$token_bot."/";
$url.=$perintah."?";
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$keterangan);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
kirimperintah("sendMessage",$token_bot,$data);
echo 'done';
?>

where <token_bot> is the token you get when creating the bot, <ID_Recipient> is your own ID and <text_text> is the message you want to send. As for Windows, I've tried it but the CURL error even though it's been installed. The solution is to replace curl with file_get_contents, so the script becomes:

 

<?php
$token_bot="<token_bot>";
$data['chat_id']=<ID_penerima>;
$data['text']="<isi teks>";
function sendcommand($command,$token_bot,array $description=null)
{
$url="https://api.telegram.org/bot".$token_bot."/";
$url.=$perintah."?";
foreach ($keterangan as $k => $v) {
    $url.=$k."=".$v."&";
}
$url=rtrim($url,"&");
$result=file_get_contents($url);
return $output;
}
kirimperintah("sendMessage",$token_bot,$data);
echo 'done';
?>

 

Unfortunately, I've tried with file_get_contents, it can be tried at home but can't be tried on a server connected to a Cisco Catalyst security device, so those who use Windows might be able to start watching Linux ;).


That's a simple tutorial from me, for tutorials with commands I will update next. Finally, thank you for reading :D. Feel free to comment , especially if you have a problem or want to ask something, I'm available here to help :)! Those who want to comment are really welcome xD.

Related Posts

Previous
Next Post »
close