Page MenuHomeGitPull.it

TelegramStupidSDK.php
No OneTemporary

Authored By
Unknown
Size
2 KB
Referenced Files
None
Subscribers
None

TelegramStupidSDK.php

<?php
/**
* Yet another stupid Telegram SDK.
*/
class TelegramStupidSDK {
private $botToken;
/**
* Constructor from the bot token.
*/
public function __construct(string $bot_token = null) {
// Have a sane default from the environment.
if ($bot_token === null) {
$bot_token = require_env('TELEGRAM_BOT_TOKEN');
}
$this->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);
// Crash violently on Telegram error.
$response_data = json_decode($response, false, 512, JSON_THROW_ON_ERROR);
$response_body_error_code = $response_data->error_code ?? null;
if ($response_data->ok === false) {
throw new Exception("Telegram failed with error_code='{$response_body_error_code}' and message='{$response_data->description}'");
}
// 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);
}
}

File Metadata

Mime Type
text/x-php
Expires
Thu, Aug 27, 14:44 (15 h, 29 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2083593
Default Alt Text
TelegramStupidSDK.php (2 KB)

Event Timeline