Skip to content

Commit cf20eb6

Browse files
authored
Merge pull request #5 from saMahmoudzadeh/master
Check Length of log message before send to telegram
2 parents e08255b + bc0ea08 commit cf20eb6

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
},
2929
"require": {
3030
"monolog/monolog": "^1.0|^2.0|^3.0",
31-
"ext-curl": "*"
31+
"ext-curl": "*",
32+
"ext-mbstring": "*"
3233
}
3334
}

src/TelegramBotHandler.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@
99

1010
class TelegramBotHandler extends AbstractProcessingHandler implements HandlerInterface
1111
{
12+
/**
13+
* text parameter in sendMessage method
14+
* @see https://core.telegram.org/bots/api#sendmessage
15+
*/
16+
private const TELEGRAM_MESSAGE_SIZE = 4096;
17+
1218
/**
1319
* bot api url
1420
* @var string
@@ -76,6 +82,15 @@ protected function write($record): void
7682
$this->send($record['formatted']);
7783
}
7884

85+
private function truncateTextToTelegramLimit(string $textMessage): string
86+
{
87+
if (mb_strlen($textMessage) <= self::TELEGRAM_MESSAGE_SIZE) {
88+
return $textMessage;
89+
}
90+
91+
return mb_substr($textMessage, 0, self::TELEGRAM_MESSAGE_SIZE,'UTF-8');
92+
}
93+
7994
/**
8095
* Send request to @link https://api.telegram.org/bot on SendMessage action.
8196
* @param string $message
@@ -99,6 +114,8 @@ protected function send(string $message, $option = []): void
99114
? $this->botApi
100115
: $this->botApi . $this->token . '/SendMessage';
101116

117+
$message = $this->truncateTextToTelegramLimit($message);
118+
102119
$params = [
103120
'text' => $message,
104121
'chat_id' => $this->chatId,

0 commit comments

Comments
 (0)