Skip to content

Commit ffd0c07

Browse files
committed
Allow custom message splitting and defining the mb encoding.
1 parent b748699 commit ffd0c07

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Exclamation symbols (:exclamation:) note something of importance e.g. breaking c
77
### Notes
88
- [:ledger: View file changes][Unreleased]
99
### Added
10-
- Extra parameter for `Request::sendMessage()` to return all response objects for split messages.
10+
- Extra parameter for `Request::sendMessage()` to pass options and return all response objects for split messages.
1111
### Changed
1212
### Deprecated
1313
### Removed

src/Request.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,10 @@ private static function ensureValidAction(string $action): void
686686
* Use this method to send text messages. On success, the last sent Message is returned
687687
*
688688
* All message responses are saved in `$extras['responses']`.
689+
* Custom encoding can be defined in `$extras['encoding']` (default: `mb_internal_encoding()`)
690+
* Custom splitting can be defined in `$extras['split']` (default: 4096)
691+
* `$extras['split'] = null;` // force to not split message at all!
692+
* `$extras['split'] = 200;` // split message into 200 character chunks
689693
*
690694
* @link https://core.telegram.org/bots/api#sendmessage
691695
*
@@ -699,19 +703,24 @@ private static function ensureValidAction(string $action): void
699703
*/
700704
public static function sendMessage(array $data, ?array &$extras = []): ServerResponse
701705
{
706+
$extras = array_merge([
707+
'split' => 4096,
708+
'encoding' => mb_internal_encoding(),
709+
], (array) $extras);
710+
702711
$text = $data['text'];
703-
$max_length = 4096;
712+
$encoding = $extras['encoding'];
713+
$max_length = $extras['split'] ?: mb_strlen($text, $encoding);
704714

705-
$extras = (array) $extras;
706715
$responses = [];
707716

708717
do {
709718
// Chop off and send the first message.
710-
$data['text'] = mb_substr($text, 0, $max_length);
719+
$data['text'] = mb_substr($text, 0, $max_length, $encoding);
711720
$responses[] = self::send('sendMessage', $data);
712721

713722
// Prepare the next message.
714-
$text = mb_substr($text, $max_length);
723+
$text = mb_substr($text, $max_length, null, $encoding);
715724
} while ($text !== '');
716725

717726
// Add all response objects to referenced variable.

0 commit comments

Comments
 (0)