Core: access to user_id and chat_id in a only triggerable command in php-telegram-bot

Created on 22 Jan 2018  路  14Comments  路  Source: php-telegram-bot/core

I'm using php-telegram-bot/core in a laravel project.

There is a cart command that only triggered by other normal command :

public function execute ()
        {
            $chat_id = $this->getMessage()->getChat()->getId();
            $user_id = $this->getMessage()->getFrom()->getId();

            $cartProducts = Cart::with('product')->where(['user_id' => $user_id])->get();

            if (!is_null($cartProducts)) {
                $result   = view('show-cart', compact('cartProducts'))->render();
                $keyboard = KeyboardController::showCartKeyboard($cartProducts);

                Request::sendMessage([
                    'chat_id'      => $chat_id,
                    'text'         => $result,
                    'parse_mode'   => 'HTML',
                    'reply_markup' => $keyboard
                ]);

            }
            else {
                Request::sendMessage([
                    'chat_id' => $chat_id,
                    'text'    => 'your cart is Empty'
                ]);
            }
        }

And in the another command I call it like this :

return $this->telegram->executeCommand('cart');

cart command is triggered but I can not access to $chat_id and $user_id variables and got this error :

Call to a member function getChat() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function getChat() on null at D:\\wamp\\www\\barlly\\app\\Commands\\CartCommand.php:44)
question

All 14 comments

Best would be to extract the cart functionality and make it executable from any other command directly.

If that's not easily possible though, you can take the solution from #485

$update = json_decode($this->update->toJson(), true);
$update['message']['text'] = '/cart';
return (new CartCommand($this->telegram, new Update($update)))->preExecute();

Note: This is not a very wonderful solution, but it works for now.

Thanks @noplanman, I will test it as soon as possible, but another question : is there any way to send extra parameter to execute function of cart command?

@noplanman , I tried your solution but now I got this error :
Call to a member function getId() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function getId() on null at D:\\wamp\\www\\barlly\\app\\Commands\\CartCommand.php:46)

Also when I get log inCartCommand like this :

public function execute ()
        {

            Log::info( $this->getMessage());
            $chat_id = $this->getMessage()->getChat()->getId();
            $user_id = $this->getMessage()->getFrom()->getId();

            $cartProducts = Cart::with('product')->where(['user_id' => $user_id])->get();

it just return /cart string.

As mentioned before, the best is to extract the method, which you can easily use to pass extra data.

As for the command you're using now, you can set the text to /cart extra params and then extract those values using $this->getMessage()->getText(true);. Be aware though, that anybody who sends that command can add those parameters, which might not be what you want.

Apart from that there is no easy clean way at the moment. It would be possible to add this feature and allow passing variables, will need to see about this.

Regarding your latest error, what line is the problem?
Depending on the info you need, you can just check for null and ignore if you don't need it.

@ahmadbadpey Have you managed to fix this now?

@ahmadbadpey any update?

$update = json_decode($this->update->toJson(), true);
$update['message']['text'] = '/cart';
return (new CartCommand($this->telegram, new Update($update)))->preExecute();

This does not work for me. I get the following error:

PHP Fatal error:  Uncaught Error: Call to a member function isPrivateChat() on null in /path_to_bot/vendor/longman/telegram-bot/src/Commands/Command.php:376
Stack trace:
#0 /path_to_bot/vendor/longman/telegram-bot/src/Commands/Command.php(155): Longman\TelegramBot\Commands\Command->removeNonPrivateMessage()
#1 /path_to_bot/Commands/CallbackqueryCommand.php(77): Longman\TelegramBot\Commands\Command->preExecute()
#2 /path_to_bot/vendor/longman/telegram-bot/src/Commands/Command.php(173): Longman\TelegramBot\Commands\SystemCommands\CallbackqueryCommand->execute()
#3 /path_to_bot/vendor/longman/telegram-bot/src/Telegram.php(514): Longman\TelegramBot\Commands\Command->preExecute()
#4 /path_to_bot/vendor in /path_to_bot/vendor/longman/telegram-bot/src/Commands/Command.php on line 376

@ttvd94 What does your CartCommand.php look like?

@noplanman It looks like this:

namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

class CartCommand extends UserCommand
{
    protected $name = 'cart';
    protected $description = 'Cart command';
    protected $usage = '/cart';
    protected $version = '1.1.0';
    protected $private_only = true;

    public function execute()
    {
        $message = $this->getMessage() ? $this->getMessage() : $this->getCallbackQuery()->getMessage();
        $chat_id = $message->getChat()->getId();
        $user_id = $message->getFrom()->getId();
        $text    = 'Some text';

        $data = [
            'chat_id' => $chat_id,
            'text'    => $text,
            'parse_mode' => 'MARKDOWN'
        ];

        return Request::sendMessage($data);
    }
}

@ttvd94 Where are you calling this code from? Is it via a callback query?

$update = json_decode($this->update->toJson(), true);
$update['message']['text'] = '/cart';
return (new CartCommand($this->telegram, new Update($update)))->preExecute();

@noplanman Yes it's in CallbackqueryCommand.php

@ttvd94 I trust you've managed to solve this? Can I close off here?

Yep @noplanman , finished the project a time ago. Thanks for following up on that.

Albeit a year later 馃槄

Was this page helpful?
0 / 5 - 0 ratings