Telegram Bot: Using json_decode()

PHP + Webhook + JSON

If you’re using pure PHP and Webhook to create your Telegram bot, hopefully these can be useful tips on how to process JSON data.

Here’s what to remember. When you send and receive JSON data, they will be in the forms of array at your end. The webhook data is in the forms of string = value. For example like this URL:

http://domain.com/?string=value

You see this a lot right? So when the server responds to you, the data you receive must be decoded into array(s).

Sample API

To make your bot interesting, we need to find some APIs to use. APIs are interfaces you interact with to obtain useful data in simpler terms. You can read about API in general here. The one we’re using for bots like this is usually a Web API.

We’re going to use this Web API provided by ratesapi.io. This API provides you with currency exchange rates. The default values (when no extra parameters are presented) will give you EUR as the base currency against all major currencies. The default call of this API as designed by ratesapi.io is like this:

https://api.ratesapi.io/api/latest?

There’s no string=value at the end right? Right, so in their documentation it says, put base= and symbols= strings to get specific conversion rates. It also requires the given values to be the international currency codes in ALL CAPITAL LETTERS. Let’s try U.S and A’s currency against Great Brit’s Pounds. So the URL will look like this:

https://api.ratesapi.io/api/latest?base=USD&symbols=GBP

Copy paste the URL above and run in a new tab. In your results you will see something like this:

This is called an XML data. You will see strings (in blue) and values (in purple and green). The blue ones are the strings of an array. In this case, you have three different arrays. So these strings actually look like this in PHP when decoded:

$base = array("USD);
$rates = array("GBP" => 0.8072950291);
$date = array("2020-05-08");

Importing the Data

So how do we put this data in a Telegram bot?

Let’s make this bot utilize this XML data when the /fx command is sent by a user. First, the sample result below:

Now the full code is as below.

// These variables are pre-defined for the whole bot file.
$path = "https://api.telegram.org/bot<YOUR_TOKEN_HERE>";
$message = $update["message"]["text"];
$chatId = $update["message"]["chat"]["id"];

if(strpos($message, "/fx") === 0){
    
$conv = "https://api.ratesapi.io/api/latest?";
$base = strtoupper(substr($message, 4, 3));
$symbol = strtoupper(substr($message, 8));

$getBase = json_decode(file_get_contents("https://api.ratesapi.io/api/latest?base=".$base."&symbols=".$symbol), TRUE)["base"];

$getSymbols = json_decode(file_get_contents("https://api.ratesapi.io/api/latest?base=".$base."&symbols=".$symbol), TRUE)["rates"];
    
file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>Foreign Exchange</b>");

file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>Base:</b> ".$getBase." 1");

file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>Current Rate(s):</b>");

foreach($getSymbols as $gsK => $gsV){
file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>".$gsK."</b> ".$gsV);
}
file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=Need to convert specific amount? Use /math amount*rate to multiply.");
    
}

The Variables

Line 1 encapsulates the whole code with the if(){] block. In it we use strpos() to check the first occurrence of /fx in $message. Let’s understand the basic variables first:

$conv = "https://api.ratesapi.io/api/latest?";
$base = strtoupper(substr($message, 4, 3));
$symbol = strtoupper(substr($message, 8));

$getBase = json_decode(file_get_contents("https://api.ratesapi.io/api/latest?base=".$base."&symbols=".$symbol), TRUE)["base"];

$getSymbols = json_decode(file_get_contents("https://api.ratesapi.io/api/latest?base=".$base."&symbols=".$symbol), TRUE)["rates"];
  1. $conv = The URL to retrieve latest fx rates provided by the site.
  2. $base = method used to extract the BASE data (base=).
  3. $symbol = method used to extract the SYMBOLS data (symbols=).
  4. $getBase = we combined the extracted BASE data with the main URL ($conv) and decode it.
  5. $getSymbols = we combined the extracted SYMBOLS data with the main URL ($conv) and decode it.

$getBase and $getSymbols look identical except at the end of the value, you will see [“base”] and [“rates”]. Remember this?

This means we are telling json_decode() to specifically extract the base array and rates array. It’s important to examine the XML file’s data structure. In some XML files, the authors will use automatically defined keys and you may get something like this [0] -> [“base”] -> [“whatever”]. Be sure to know where the root is and where each root leads you.

Wait, Functions in those Strings

There are some functions that enhance the strings defined. They are:

  1. strtoupper() = This function converts all results from substr() below to CAPITAL LETTERS. So if someone inputs usd, it will be turned into USD.
  2. substr() = This function extracts the start and end point of a data piece. For example when someone inputs /fx usd gbp, substr($message, 4, 3) means, go to the 4th point of a string and highlight until the next 3 points, hence extracting “usd”. For the second data we simply use substr($message, 8), meaning go to point 8 and select everything else after it. Why select everything else after? Because ratesapi.io allow you to put multiple values in the SYMBOLS string. See the picture below this list.
  3. json_decode() = As the name says, decode the data given and turn them into arrays.

Putting it All Together

The last parts are quite straightforward. Here are the codes to remind you:

file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>Foreign Exchange</b>");

file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>Base:</b> ".$getBase." 1");

file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>Current Rate(s):</b>");

foreach($getSymbols as $gsK => $gsV){
file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=<b>".$gsK."</b> ".$gsV);
}
file_get_contents($path."/sendMessage?parse_mode=HTML&chat_id=".$chatId."&text=Need to convert specific amount? Use /math amount*rate to multiply.");
  1. file_get_contents() = PHP’s built-in function to read a file (the decoded file we receive).
  2. sendMessage? = Telegram’s command to process given strings: parse_mode=, chat_id= & text=
  3. foreach() = PHP’s foreach() loop is useful here in case multiple SYMBOLS are provided by the user. You can’t use multiple BASES using the URL provided. There may be a URL given by the authors, so check their documentation. Because SYMBOLS may appear in multiple values (separated by commas), we are ready to process that array by asking foreach() to check each value if present. To learn about foreach() read the manual.
  4. The last file_get_contents() I added is just a notice to point users to another command called /math. That’s a whole other story which I’m struggling to understand. The basic implementation is easy to implement except there are many input scenario to deal with if you want to make it complete (read: I’m LAZY). Read about Math.js API.

Conclusion

I hope that works. This is probably my longest tutorial yet, hope it works at your end.

Leave a Reply

Your email address will not be published. Required fields are marked *

© botdroid.me since 1998. Engine by Wordpress. Custom theme. Privacy Policy. Browse comfortably please. Borrowed media credits.