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:


(for more details, please refers to my article, section “3. Connect the Bot with the Microservice“)

That’s it!


Related posts

  1. Security analysis of Telegram Messenger
  2. Why WhatsApp (and Telegram) messages are not really private?
  3. Media File Jacking: WhatsApp and Telegram media files can be manipulated from attackers
  4. How to check Cloudflare cache status programmatically
  5. SimpleTwitter: small PHP class for search on Twitter