php-telegram-bot / core

PHP Telegram Bot based on the official Telegram Bot API
MIT License
3.79k stars 949 forks source link

Creating a Dynamic Inline Keyboard: Argument #1 ($data) must be of type array, string given #1413

Closed iyamk closed 9 months ago

iyamk commented 9 months ago

This code throws an error

$btns = [];
for ($i = 0; $i <= 5; $i++)
    $btns[] = [ 'text' => 'button '.$i, 'url' => 'https://github.com' ];
$class = new \ReflectionClass('Longman\TelegramBot\Entities\InlineKeyboard');
$keyboard = $class->newInstanceArgs($btns);
return $this->replyToChat('test', [ 'reply_markup' => $keyboard ]);

Error

Uncaught TypeError: Longman\TelegramBot\Entities\InlineKeyboardButton::couldBe(): Argument #1 ($data) must be of type array, string given in /home/user/bot/vendor/longman/telegram-bot/src/Entities/InlineKeyboardButton.php:53
Stack trace:
#0 [internal function]: Longman\TelegramBot\Entities\InlineKeyboardButton::couldBe()
#1 /home/user/bot/vendor/longman/telegram-bot/src/Entities/Keyboard.php(176): call_user_func()
#2 /home/user/bot/vendor/longman/telegram-bot/src/Entities/Keyboard.php(153): Longman\TelegramBot\Entities\Keyboard->parseButton()
#3 /home/user/bot/vendor/longman/telegram-bot/src/Entities/Keyboard.php(106): Longman\TelegramBot\Entities\Keyboard->parseRow()
#4 /home/user/bot/vendor/longman/telegram-bot/src/Entities/Keyboard.php(39): Longman\TelegramBot\Entities\Keyboard->createFromParams()
#5 [internal function]: Longman\TelegramBot\Entities\Keyboard->__construct()
#6 /home/user/bot/Commands/Message/GenericmessageCommand.php(452): ReflectionClass->newInstanceArgs()
#7 /home/user/bot/vendor/longman/telegram-bot/src/Commands/Command.php(204): Longman\TelegramBot\Commands\SystemCommands\GenericmessageCommand->execute()
#8 /home/user/bot/vendor/longman/telegram-bot/src/Telegram.php(686): Longman\TelegramBot\Commands\Command->preExecute()
#9 /home/user/bot/vendor/longman/telegram-bot/src/Telegram.php(657): Longman\TelegramBot\Telegram->executeCommand()
#10 /home/user/bot/vendor/longman/telegram-bot/src/Telegram.php(568): Longman\TelegramBot\Telegram->processUpdate()
#11 /home/user/bot/hook.php(57): Longman\TelegramBot\Telegram->handle()
#12 {main}
  thrown

When using Longman\TelegramBot\Entities\Keyboard this error does not occur

iyamk commented 9 months ago

Problem solved, it was necessary to add a nested array

for ($i = 0; $i <= 5; $i++)
                $btns[] = [[ 'text' => 'button '.$i, 'url' => 'https://github.com' ]];