TelegramBotHandler.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use RuntimeException;
  12. use Monolog\Level;
  13. use Monolog\Utils;
  14. use Monolog\LogRecord;
  15. /**
  16. * Handler send logs to Telegram using Telegram Bot API.
  17. *
  18. * How to use:
  19. * 1) Create telegram bot with https://telegram.me/BotFather
  20. * 2) Create a telegram channel where logs will be recorded.
  21. * 3) Add created bot from step 1 to the created channel from step 2.
  22. *
  23. * Use telegram bot API key from step 1 and channel name with '@' prefix from step 2 to create instance of TelegramBotHandler
  24. *
  25. * @link https://core.telegram.org/bots/api
  26. *
  27. * @author Mazur Alexandr <alexandrmazur96@gmail.com>
  28. */
  29. class TelegramBotHandler extends AbstractProcessingHandler
  30. {
  31. private const BOT_API = 'https://api.telegram.org/bot';
  32. /**
  33. * The available values of parseMode according to the Telegram api documentation
  34. */
  35. private const AVAILABLE_PARSE_MODES = [
  36. 'HTML',
  37. 'MarkdownV2',
  38. 'Markdown', // legacy mode without underline and strikethrough, use MarkdownV2 instead
  39. ];
  40. /**
  41. * The maximum number of characters allowed in a message according to the Telegram api documentation
  42. */
  43. private const MAX_MESSAGE_LENGTH = 4096;
  44. /**
  45. * Telegram bot access token provided by BotFather.
  46. * Create telegram bot with https://telegram.me/BotFather and use access token from it.
  47. */
  48. private string $apiKey;
  49. /**
  50. * Telegram channel name.
  51. * Since to start with '@' symbol as prefix.
  52. */
  53. private string $channel;
  54. /**
  55. * The kind of formatting that is used for the message.
  56. * See available options at https://core.telegram.org/bots/api#formatting-options
  57. * or in AVAILABLE_PARSE_MODES
  58. */
  59. private string|null $parseMode;
  60. /**
  61. * Disables link previews for links in the message.
  62. */
  63. private bool|null $disableWebPagePreview;
  64. /**
  65. * Sends the message silently. Users will receive a notification with no sound.
  66. */
  67. private bool|null $disableNotification;
  68. /**
  69. * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages.
  70. * False - truncates a message that is too long.
  71. */
  72. private bool $splitLongMessages;
  73. /**
  74. * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests).
  75. */
  76. private bool $delayBetweenMessages;
  77. /**
  78. * Telegram message thread id, unique identifier for the target message thread (topic) of the forum; for forum supergroups only
  79. * See how to get the `message_thread_id` https://stackoverflow.com/a/75178418
  80. */
  81. private int|null $topic;
  82. /**
  83. * @param string $apiKey Telegram bot access token provided by BotFather
  84. * @param string $channel Telegram channel name
  85. * @param bool $splitLongMessages Split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages
  86. * @param bool $delayBetweenMessages Adds delay between sending a split message according to Telegram API
  87. * @param int $topic Telegram message thread id, unique identifier for the target message thread (topic) of the forum
  88. * @throws MissingExtensionException If the curl extension is missing
  89. */
  90. public function __construct(
  91. string $apiKey,
  92. string $channel,
  93. $level = Level::Debug,
  94. bool $bubble = true,
  95. string $parseMode = null,
  96. bool $disableWebPagePreview = null,
  97. bool $disableNotification = null,
  98. bool $splitLongMessages = false,
  99. bool $delayBetweenMessages = false,
  100. int $topic = null
  101. ) {
  102. if (!extension_loaded('curl')) {
  103. throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler');
  104. }
  105. parent::__construct($level, $bubble);
  106. $this->apiKey = $apiKey;
  107. $this->channel = $channel;
  108. $this->setParseMode($parseMode);
  109. $this->disableWebPagePreview($disableWebPagePreview);
  110. $this->disableNotification($disableNotification);
  111. $this->splitLongMessages($splitLongMessages);
  112. $this->delayBetweenMessages($delayBetweenMessages);
  113. $this->setTopic($topic);
  114. }
  115. public function setParseMode(string $parseMode = null): self
  116. {
  117. if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES, true)) {
  118. throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.');
  119. }
  120. $this->parseMode = $parseMode;
  121. return $this;
  122. }
  123. public function disableWebPagePreview(bool $disableWebPagePreview = null): self
  124. {
  125. $this->disableWebPagePreview = $disableWebPagePreview;
  126. return $this;
  127. }
  128. public function disableNotification(bool $disableNotification = null): self
  129. {
  130. $this->disableNotification = $disableNotification;
  131. return $this;
  132. }
  133. /**
  134. * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages.
  135. * False - truncates a message that is too long.
  136. * @return $this
  137. */
  138. public function splitLongMessages(bool $splitLongMessages = false): self
  139. {
  140. $this->splitLongMessages = $splitLongMessages;
  141. return $this;
  142. }
  143. /**
  144. * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests).
  145. * @return $this
  146. */
  147. public function delayBetweenMessages(bool $delayBetweenMessages = false): self
  148. {
  149. $this->delayBetweenMessages = $delayBetweenMessages;
  150. return $this;
  151. }
  152. public function setTopic(int $topic = null): self
  153. {
  154. $this->topic = $topic;
  155. return $this;
  156. }
  157. /**
  158. * @inheritDoc
  159. */
  160. public function handleBatch(array $records): void
  161. {
  162. $messages = [];
  163. foreach ($records as $record) {
  164. if (!$this->isHandling($record)) {
  165. continue;
  166. }
  167. if (\count($this->processors) > 0) {
  168. $record = $this->processRecord($record);
  169. }
  170. $messages[] = $record;
  171. }
  172. if (\count($messages) > 0) {
  173. $this->send((string) $this->getFormatter()->formatBatch($messages));
  174. }
  175. }
  176. /**
  177. * @inheritDoc
  178. */
  179. protected function write(LogRecord $record): void
  180. {
  181. $this->send($record->formatted);
  182. }
  183. /**
  184. * Send request to @link https://api.telegram.org/bot on SendMessage action.
  185. */
  186. protected function send(string $message): void
  187. {
  188. $messages = $this->handleMessageLength($message);
  189. foreach ($messages as $key => $msg) {
  190. if ($this->delayBetweenMessages && $key > 0) {
  191. sleep(1);
  192. }
  193. $this->sendCurl($msg);
  194. }
  195. }
  196. protected function sendCurl(string $message): void
  197. {
  198. $ch = curl_init();
  199. $url = self::BOT_API . $this->apiKey . '/SendMessage';
  200. curl_setopt($ch, CURLOPT_URL, $url);
  201. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  202. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  203. $params = [
  204. 'text' => $message,
  205. 'chat_id' => $this->channel,
  206. 'parse_mode' => $this->parseMode,
  207. 'disable_web_page_preview' => $this->disableWebPagePreview,
  208. 'disable_notification' => $this->disableNotification,
  209. ];
  210. if ($this->topic !== null) {
  211. $params['message_thread_id'] = $this->topic;
  212. }
  213. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  214. $result = Curl\Util::execute($ch);
  215. if (!is_string($result)) {
  216. throw new RuntimeException('Telegram API error. Description: No response');
  217. }
  218. $result = json_decode($result, true);
  219. if ($result['ok'] === false) {
  220. throw new RuntimeException('Telegram API error. Description: ' . $result['description']);
  221. }
  222. }
  223. /**
  224. * Handle a message that is too long: truncates or splits into several
  225. * @return string[]
  226. */
  227. private function handleMessageLength(string $message): array
  228. {
  229. $truncatedMarker = ' (...truncated)';
  230. if (!$this->splitLongMessages && strlen($message) > self::MAX_MESSAGE_LENGTH) {
  231. return [Utils::substr($message, 0, self::MAX_MESSAGE_LENGTH - strlen($truncatedMarker)) . $truncatedMarker];
  232. }
  233. return str_split($message, self::MAX_MESSAGE_LENGTH);
  234. }
  235. }