Telegram Bot API – Send message in PHP

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);

2 Comments

  1. 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.

Leave a Reply to Afam Cancel reply

Your email address will not be published. Required fields are marked *