Home > OS >  PHP Telegram send message example
PHP Telegram send message example

Time:11-05

How optimal is this code for sending a letter to my bot in telegram? Is it possible to make the code more optimal?

!How to get a chat ID: https://api.telegram.org/bot/getUpdates

Send to the browser address bar: https://api.telegram.org/bot470129572:HFApoAHFVN37852983HDFON385cNOhvs/getUpdates

@return {"ok":true,"result":[{"update_id":653246792, "message":{"message_id":1,"from":{"id":023752053 !It is chatID: 023752053

<?php

$chatID = '023752053';
$token = '470129572:HFApoAHFVN37852983HDFON385cNOhvs';

/**
  * Formatting options https://core.telegram.org/bots/api#formatting-options
  */
$message = '';
foreach(json_decode($fd) as $key => $value) {
  $message .= '<b>' . $key . '</b>: ' . $value;
  $message .= '
';
}

$data = [
  'text' => $message,
  'chat_id'=>$chatID,
  'parse_mode' => 'HTML',
];

/**
  * sendMessage https://core.telegram.org/bots/api#sendmessage
  */
$url = "https://api.telegram.org/bot" . $token . "/sendMessage";
$url .= '?'.http_build_query($data);
$ch = curl_init();
$optArray = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
curl_close($ch);

$result = json_decode($result, JSON_PRETTY_PRINT);

if ($result['ok']) {
  $result = json_encode(array('success'=>$result['ok']));
}
else {
  $result = json_encode(array('error'=>$result));
}

return $result;

I do not know if it is possible to improve this code for sending a message to telegram bot via php?

CodePudding user response:

Your code looks good! I can't find any error.

But you can try some small changes for better practice:

Instead of using data to the query string in the URL, use CURLOPT_POSTFIELDS to send data as a POST request. Is more secure and I thing it is the preferred method for the Telegram API.

Other good Idea is create error handling for cURL to catch connection issues or HTTP errors.

Another thing is, I can see that your function does more than just send a message, right? It is formatting messages and handles the response. It might be more maintainable to separate these concerns into individual functions.

I think thats it.

Oh! you must be careful with how you manage your bot token.

I can give you an example:

    <?php

function YourTelegramMessageFunction($chatID, $message, $token) {
    $url = "https://api.telegram.org/bot" . $token . "/sendMessage";
    $data = ['chat_id' => $chatID, 'text' => $message, 'parse_mode' => 'HTML'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);


    // here you can Handle cURL error
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return json_encode(array('error' => $error_msg));
    }

    $http_code_message = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code_message >= 200 && $http_code_message < 300) {
        $result = json_decode($response, true);
        if ($result['ok']) {
            $result = json_encode(array('success' => $result['ok']));
        } else {
            $result = json_encode(array('error' => $result));
        }
    } else {
        // And here you can Handle HTTP error
        $result = json_encode(array('error' => 'HTTP error ' . $http_code_message));
    }

    curl_close($ch);
    return $result;
}

$chatID = 'the id'; // change for a correct ID
$token  = 'the toke,'; // change for a correct Token
$message = 'the message'; // change with the current message formatting logic

echo YourTelegramMessageFunction($chatID, $message, $token);

CodePudding user response:

$message string could have malformed message if you get unsanitized HTML special characters. Escaping is a way to avoid injections.

$message .= '<b>' . htmlspecialchars($key) . '</b>: ' . htmlspecialchars($value);
$message .= "\n"; 

When you use cUrl you want to ensure success and if not error handling by checking the HTTP status code or cUrl errors.

  • Related