PHP Telegram bot: Using Cron jobs

It has been a long time since I posted a blog. But I have something a discoverd and maybe it will help you the reader.

Just like Marc Zuckerberg I want to create a sort of personal assistant. Yes you have Cortana, Google now and Siri but I want to make one that is mine. It’s also a cool coding exercise.

The name of my bot is Parker. If you ever watched the series Thunderbirds you will recognize the name. Indeed it’s the name of the butler of lady Penelope. More Parker in another blog.

If you wanna know how to set up the webhook I suggest that you follow the instructions on the api site of Telegram. What I can tell you is that a bought license is easier to set up then a self signed one. I just bought a SSL license at my webhost. Cost me around 12 euro’s. The price for conveyance you could say.

The first part of the code I got from this blog. Just a basic piece of code. I suggest that you grab his code. I did and it helped me massively to get things started. For the people that are lazy, here is the code.

<?php 
define('BOT_TOKEN', 'YOURBOT:TOKEN');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
	
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
		
// compose reply
$reply =  sendMessage();
		
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);

function sendMessage(){
$message = "I am a baby bot.";
return $message;
}

Now this code works nice. It gets the message and send as a reply ‘I’m a baby bot’ to every message it receives. This is nice and I expanded the sendMessage() function to give some different answers depending on what you send the bot. Very nice but I have a problem with it.

The bot will only answer if I send a message to it. This is quite logic since the script is triggered when the message is received by Telegram and they send it to your script. Then the script is started. It runs and then it sends the return message to Telegram. I however want the bot to message me without messaging him first. For instance I want him to send me a message with all my appointments of that day and maybe even the weather. Well that is where the Cron job comes in.
A Cronjob is a commando available on Linux. Most webservers run on Linux so you can use it. A Cronjob is basicly a commando to tell the Linux machine to execute a command or program at a certain time of the day or every couple of minutes. There are lot of ways you can set it up. I set on Cronjob to execute every morning at 7 o’clock. To set it up I used cPanel. cPanel has a build in graphic interface that let’s you set up Cronjobs real easy. I suggest that you also do it via cPanel but if that is not available google what ever hosting software your host uses.
For more info about the Cronjobs, here is the wiki.

Now that we have done that we have to modify the PHP script a little bit. What I did is use a GET. Why a GET? Well this way I can give the info to the script via the URL. This way I can set the webhook with in the url at the end ?source=telegram. I set up the Cron job with a link linking to index.php?source=morningCron. This way the script knows where from the script is activated and what it should do. Pretty cool.

And now for the code:

define('BOT_TOKEN', '207872399:AAHDMeGTVW9BCESCi-nihUtDeckW-3lvb8s');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
	
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
// the json object containing the message, chat id and some other stuff
$update = json_decode($content, true);
// this stores the chat id of the person who send the message
$chatID = $update["message"]["chat"]["id"];

// My part
//====================================================
// the GET in which the origin of the call is stored
$source = $_GET["source"];

//creates the reply var
$reply;

if(!is_null($source)){
    
    if($source == "telegram"){
        $reply = "This call was made from the telegram server";
    }
    elseif($source == "morningCron"){
        $reply = "This call was made from the morning Cron job";
    }
    else{
        $reply = "I'm sorry master but it appears that the source for this call was not correct.";
    }
    
}
else{
    $reply = "I'm sorry Master but there is an error. I could not determen the source of the call.";
}
//====================================================

$sendto =API_URL."sendmessage?chat_id=".$chatID."&amp;text=".$reply;
file_get_contents($sendto);
?&gt;

Now let me explain my bit of the code a bit more.
The if statement first checks if $source isn’t empty. If it isn’t it will continue, else the reply will be an error message. This way you know that something went wrong. Sorta debugging.
Okay, the source isn’t empty and now we enter yet another if else statement. This is where I check what is in the $source variable. If it’s something I made code for then there is an if statement or an elseif statement. (you could also use a switch. In the future I will probably do something like that). The else is there again to send an error message back to Telegram.

If you set up the webhook for Telegram you just put in “https://yoururl.com/YOURBOTTOKEN/index.php?source=telegram”. This way the script knows that the source of the activation is Telegram. If you set up the Cronjob for you put in the url: “https://yoururl.com/YOURBOTTOKEN/index.php?source=morningCron”. In this case the script knows that the source of the activation is from the morning Cronjob in my case.

Now I know this code isn’t really advanced but it works. Any further things I discover I will post here on my blog. Also if you have any suggestion feel free to shoot me an email at info@area36.nl