Small snippet of code in PHP to send a text reply to a Telegram user via a Bot.
To use this example you must have already created your Bot and set up the webhook.
<?php header("Content-Type: application/json"); $content = file_get_contents("php://input"); $update = json_decode($content, true); if(!$update) { exit; } $message = isset($update['message']) ? $update['message'] : ""; $messageId = isset($message['message_id']) ? $message['message_id'] : ""; $chatId = isset($message['chat']['id']) ? $message['chat']['id'] : ""; $firstname = isset($message['chat']['first_name']) ? $message['chat']['first_name'] : ""; $lastname = isset($message['chat']['last_name']) ? $message['chat']['last_name'] : ""; $username = isset($message['chat']['username']) ? $message['chat']['username'] : ""; $date = isset($message['date']) ? $message['date'] : ""; $text = isset($message['text']) ? $message['text'] : ""; $userId = isset($message['from']['id']) ? $message['from']['id'] : ""; $response = "Your text: " . $text; $parameters = array('chat_id' => $chatId, "text" => $response); $parameters["method"] = "sendMessage"; echo json_encode($parameters);
Works like magic! Thank you.
Is it possible to send a telegram user a message from a PHP web application without the user sending or initiating a message to the telegram bot?
I am working on a simple notification system that will inform users that are on telegram that their payments have been successfully processed.
Many thanks for your time.
We’re glad it worked and it came in handy.
To answer your question: without having started a conversation with the bot you cannot send messages through the BOT API, to do what you want you should use the Telegram API (TDLib https://core.telegram.org/#tdlib-build-your-own-telegram).
There are some libraries written in PHP such as MadelineProto, a PHP MTProto telegram client (https://github.com/danog/MadelineProto), that can help you build your own.