@@ -683,29 +683,50 @@ private static function ensureValidAction(string $action): void
683
683
}
684
684
685
685
/**
686
- * Use this method to send text messages. On success, the sent Message is returned
686
+ * Use this method to send text messages. On success, the last sent Message is returned
687
+ *
688
+ * 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
687
693
*
688
694
* @link https://core.telegram.org/bots/api#sendmessage
689
695
*
690
- * @param array $data
696
+ * @todo Splitting formatted text may break the message.
697
+ *
698
+ * @param array $data
699
+ * @param array|null $extras
691
700
*
692
701
* @return ServerResponse
693
702
* @throws TelegramException
694
703
*/
695
- public static function sendMessage (array $ data ): ServerResponse
704
+ public static function sendMessage (array $ data, ? array & $ extras = [] ): ServerResponse
696
705
{
697
- $ text = $ data ['text ' ];
706
+ $ extras = array_merge ([
707
+ 'split ' => 4096 ,
708
+ 'encoding ' => mb_internal_encoding (),
709
+ ], (array ) $ extras );
710
+
711
+ $ text = $ data ['text ' ];
712
+ $ encoding = $ extras ['encoding ' ];
713
+ $ max_length = $ extras ['split ' ] ?: mb_strlen ($ text , $ encoding );
714
+
715
+ $ responses = [];
698
716
699
717
do {
700
- //Chop off and send the first message
701
- $ data ['text ' ] = mb_substr ($ text , 0 , 4096 );
702
- $ response = self ::send ('sendMessage ' , $ data );
718
+ // Chop off and send the first message.
719
+ $ data ['text ' ] = mb_substr ($ text , 0 , $ max_length , $ encoding );
720
+ $ responses [] = self ::send ('sendMessage ' , $ data );
703
721
704
- //Prepare the next message
705
- $ text = mb_substr ($ text , 4096 );
706
- } while (mb_strlen ( $ text, ' UTF-8 ' ) > 0 );
722
+ // Prepare the next message.
723
+ $ text = mb_substr ($ text , $ max_length , null , $ encoding );
724
+ } while ($ text !== '' );
707
725
708
- return $ response ;
726
+ // Add all response objects to referenced variable.
727
+ $ extras ['responses ' ] = $ responses ;
728
+
729
+ return end ($ responses );
709
730
}
710
731
711
732
/**
@@ -717,7 +738,7 @@ public static function sendMessage(array $data): ServerResponse
717
738
* @return ServerResponse
718
739
* @throws TelegramException
719
740
*/
720
- public static function __callStatic (string $ action , array $ data )
741
+ public static function __callStatic (string $ action , array $ data ): ServerResponse
721
742
{
722
743
// Only argument should be the data array, ignore any others.
723
744
return static ::send ($ action , reset ($ data ) ?: []);
0 commit comments