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?
2
Answers
$message
string could have malformed message if you get unsanitized HTML special characters. Escaping is a way to avoid injections.When you use
cUrl
you want to ensure success and if not error handling by checking the HTTP status code or cUrl errors.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: