@@ -683,29 +683,50 @@ private static function ensureValidAction(string $action): void
683683 }
684684
685685 /**
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
687693 *
688694 * @link https://core.telegram.org/bots/api#sendmessage
689695 *
690- * @param array $data
696+ * @todo Splitting formatted text may break the message.
697+ *
698+ * @param array $data
699+ * @param array|null $extras
691700 *
692701 * @return ServerResponse
693702 * @throws TelegramException
694703 */
695- public static function sendMessage (array $ data ): ServerResponse
704+ public static function sendMessage (array $ data, ? array & $ extras = [] ): ServerResponse
696705 {
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 = [];
698716
699717 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 );
703721
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 !== '' );
707725
708- return $ response ;
726+ // Add all response objects to referenced variable.
727+ $ extras ['responses ' ] = $ responses ;
728+
729+ return end ($ responses );
709730 }
710731
711732 /**
@@ -717,7 +738,7 @@ public static function sendMessage(array $data): ServerResponse
717738 * @return ServerResponse
718739 * @throws TelegramException
719740 */
720- public static function __callStatic (string $ action , array $ data )
741+ public static function __callStatic (string $ action , array $ data ): ServerResponse
721742 {
722743 // Only argument should be the data array, ignore any others.
723744 return static ::send ($ action , reset ($ data ) ?: []);
0 commit comments