.Maui Blog

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);
Exit mobile version