@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace Jakach\Logging\Notifier;
|
||||
|
||||
use Jakach\Logging\Model\Alert;
|
||||
use Jakach\Logging\Storage\Repository;
|
||||
|
||||
class TelegramNotifier
|
||||
{
|
||||
private ?string $botToken;
|
||||
private ?string $chatId;
|
||||
|
||||
public function __construct(
|
||||
private Repository $repo,
|
||||
) {
|
||||
$this->botToken = $this->repo->getConfig('telegram_bot_token');
|
||||
$this->chatId = $this->repo->getConfig('telegram_chat_id');
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return !empty($this->botToken) && !empty($this->chatId);
|
||||
}
|
||||
|
||||
public function send(Alert $alert): bool
|
||||
{
|
||||
if (!$this->isConfigured()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$emoji = match ($alert->severity->value) {
|
||||
'emergency', 'critical_high', 'critical' => "\xF0\x9F\x94\xA5",
|
||||
'critical_low', 'error' => "\xE2\x9D\x8C",
|
||||
'warning_high', 'warning' => "\xE2\x9A\xA0\xEF\xB8\x8F",
|
||||
'warning_low' => "\xF0\x9F\x93\xA2",
|
||||
default => "\xE2\x84\xB9\xEF\xB8\x8F",
|
||||
};
|
||||
|
||||
$text = sprintf(
|
||||
"%s *ALERT #%d* [%s]\n",
|
||||
$emoji,
|
||||
$alert->id,
|
||||
strtoupper($alert->severity->value)
|
||||
);
|
||||
$text .= sprintf("*Rule:* %s\n", $alert->ruleName);
|
||||
$text .= sprintf("*Source:* %s\n", $alert->sourceName ?? '—');
|
||||
$text .= sprintf("*Message:* ```\n%s\n```", mb_substr($alert->message, 0, 1000));
|
||||
|
||||
$url = 'https://api.telegram.org/bot' . $this->botToken . '/sendMessage';
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
|
||||
'chat_id' => $this->chatId,
|
||||
'text' => $text,
|
||||
'parse_mode' => 'Markdown',
|
||||
'disable_web_page_preview' => true,
|
||||
]));
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
fprintf(STDERR, "Telegram send failed (HTTP %d): %s\n", $httpCode, $response);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user