diff --git a/include/TelegramStupidSDK.php b/include/TelegramStupidSDK.php index 61ca06c..e6ad16e 100644 --- a/include/TelegramStupidSDK.php +++ b/include/TelegramStupidSDK.php @@ -1,106 +1,105 @@ botToken = $bot_token; } /** * Get an action URL. */ private function getActionURL(string $action): string { return "https://api.telegram.org/bot{$this->botToken}/{$action}"; } /** * Get the default chat ID from the environment variable. */ private function getDefaultChatID(): int { return require_env('TELEGRAM_CHAT_ID'); } /** * Send a Telegram message to a Chat ID. */ public function sendMessage(string $message, int $chatId = null) { // Assume a sane default. if ($chatId === null) { $chatId = $this->getDefaultChatID(); } // Prepare the URL for the Telegram API. // Initialize cURL. $url = $this->getActionURL('sendMessage'); $ch = curl_init($url); // Prepare the data to be sent. // Note that you should escape some things by yourself, e.g. the text in the links, like: // [Download asd\\.apk](https://duck.ai/asd.apk/) $data = [ 'parse_mode' => 'MarkdownV2', 'chat_id' => $chatId, 'text' => $message, ]; // Set cURL options curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request $response = curl_exec($ch); // Check for errors if (curl_errno($ch)) { throw new Exception(sprintf( "Error running cURL: %s", curl_error($ch) )); } // Close cURL session curl_close($ch); // TODO: crash on server error asd. - print_r($response); // Return the response return $response; } /** * Escape a Telegram message body for MarkdownV2. * In MarkdownV2, these characters must be escaped: _*[]()~`>#+-=|{}.! * but only if these are parts of a "normal" text body (not in links, etc.) * https://core.telegram.org/bots/api#markdownv2-style */ public static function escapeMarkdownV2(string $input): string { // Characters that need to be escaped in MarkdownV2 $specialChars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']; // Create a search and replace array $search = []; $replace = []; foreach ($specialChars as $char) { $search[] = $char; $replace[] = '\\' . $char; } // Replace all special characters with their escaped versions return str_replace($search, $replace, $input); } }