forked from Seldaek/monolog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTelegramBotHandler.php
99 lines (87 loc) · 2.71 KB
/
TelegramBotHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use RuntimeException;
use Monolog\Logger;
/**
* Handler send logs to Telegram using Telegram Bot API.
*
* How to use:
* 1) Create telegram bot with https://telegram.me/BotFather
* 2) Create a telegram channel where logs will be recorded.
* 3) Add created bot from step 1 to the created channel from step 2.
*
* Use telegram bot API key from step 1 and channel name with '@' prefix from step 2 to create instance of TelegramBotHandler
*
* @link https://core.telegram.org/bots/api
*
* @author Mazur Alexandr <[email protected]>
*/
class TelegramBotHandler extends AbstractProcessingHandler
{
private const BOT_API = 'https://api.telegram.org/bot';
/**
* Telegram bot access token provided by BotFather.
* Create telegram bot with https://telegram.me/BotFather and use access token from it.
* @var string
*/
private $apiKey;
/**
* Telegram channel name.
* Since to start with '@' symbol as prefix.
* @var string
*/
private $channel;
/**
* @param string $apiKey Telegram bot access token provided by BotFather
* @param string $channel Telegram channel name
* @inheritDoc
*/
public function __construct(
string $apiKey,
string $channel,
$level = Logger::DEBUG,
bool $bubble = true
) {
parent::__construct($level, $bubble);
$this->apiKey = $apiKey;
$this->channel = $channel;
$this->level = $level;
$this->bubble = $bubble;
}
/**
* @inheritDoc
*/
protected function write(array $record): void
{
$this->send($record['formatted']);
}
/**
* Send request to @link https://api.telegram.org/bot on SendMessage action.
* @param string $message
*/
protected function send(string $message): void
{
$ch = curl_init();
$url = self::BOT_API . $this->apiKey . '/SendMessage';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'text' => $message,
'chat_id' => $this->channel,
]));
$result = Curl\Util::execute($ch);
$result = json_decode($result, true);
if ($result['ok'] === false) {
throw new RuntimeException('Telegram API error. Description: ' . $result['description']);
}
}
}