A Telegram Echo Bot built with a single PHP line
Some weeks ago i've written a brief tutorial focused on building a simple Echo BOT on Telegram using Python.
Today i want to share a very small snippet that implements the same Bot using PHP as responder for the Telegram's WebHook.
For Bot registration please refer to my previous article, section "1. Create a Telegram Bot".
When your Telegram Bot has been created, simply create on your webserver this file (named, e.g, webhook.php
):
<?php call_user_func(function($hookObj){file_get_contents("https://api.telegram.org/bot<YOURTOKEN>/sendMessage?chat_id=" .$hookObj["message"]["chat"]["id"] . "&text=" . urlencode($hookObj['message']['text']));},json_decode(file_get_contents("php://input"), true)); ?>
Obviously, replace YOURTOKEN
with the token released by BotFather.
The code is pretty simple: the script get the POST data reading php://input
(a read-only stream that allows you to read raw data from the request body) and converts it into a JSON object.
The JSON object is passed (using call_user_function
) to an anonymous function that reads ChatID and Message and calls (using the file_get_contents
function) the Telegram's API in order to send a response to the user.
Finally, connect the Bot with the PHP page, with your browser:
https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://<YOURSERVER>/webhook.php
(for more details, please refers to my article, section "3. Connect the Bot with the Microservice")
That's it!
References
- https://www.andreafortuna.org/programming/how-to-build-a-simple-echo-bot-on-telegram-using-hook-io-and-python/
- http://php.net/manual/en/wrappers.php.php
- http://php.net/manual/en/function.call-user-func.php
- http://php.net/manual/en/functions.anonymous.php
- https://core.telegram.org/bots/webhooks
- https://gist.github.com/andreafortuna/47e1c33a121bb3997aa66c868511f767