CakePHP 4 Telegram Notification
Asyraf Wahi Anuar - May 09, 2021Estimated reading time: 1 minute, 43 seconds

There are many methods of sending notifications to alert the web application administrator or moderator regarding some event in the web application that required attention from them. Technically, most of the notification is sent via email, however, Telegram has a bot that is free to generate and use. Taking the advantage of the bot, we can send a telegram notification message to alert the web application administrator.
Register Telegram Bot
Search BotFather and follow the following command to start the process.
/start
/newbot
(Follow Instruction in the BotFather. You need to set Bot name etc.)
Once completed, you'll receive a link to access the Bot and token. You can click on the link to access your bot. Below is the URL to test your bot.
Get Message Update and Chat_ID
https://api.telegram.org/bot<BotToken>/getUpdates
Test Send Message
https://api.telegram.org/bot<BotToken>/sendMessage?chat_id=<Chat_ID>&text=<YouMessage>
Integrating the Bot in CakePHP, it quite a straightforward process using PHP code. What you need is the Telegram Bot Token and the Chat ID. The Chat ID is available when you access the getUpdates link. Below is the sample code to send a notification if there is a new contact message received. The following code is executed after the save method.
$botToken = 'your_telegram_bot_token';
$chatId = 'your_bot_chat_id';
$website = "https://api.telegram.org/bot".$botToken;
$emoji = "\xF0\x9F\x93\xA7"; //Email Emoji
$params = [
'chat_id' => $chatId,
'parse_mode' => 'markdown', //parse_mode = markdown for telegram format, parse_mode = html for html format
'text' => $emoji . ' *NEW CONTACT INQUIRY*'.PHP_EOL.'Subject: ' . $subject . '',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
Now, you'll receive a notification if there is a new contact inquiry submitted.
That's all, Happy coding :)






