defstudio / telegraph

Telegraph is a Laravel package for fluently interacting with Telegram Bots
MIT License
675 stars 116 forks source link

Can't find how to ask a question. #512

Closed RudIhor closed 7 months ago

RudIhor commented 7 months ago

Hello, guys. I didn't find info in docs about how can I ask a user a question. I mean I want to ask user for example "Enter your age:" then he enters his age, after that I'll validate it. How can I do this? Thank you in advance!

m-petrosyan commented 7 months ago

@RivGames Hi, I'm not sure if this is the best solution, but something like this


    /**
     * @throws StorageException
     */
    protected function handleChatMessage(Stringable $text): void
    {
        if ($text->value() >= 18) {
            $this->questionSteps();
        } else {
            $this->reply('Access closed');
        }
    }

    /**
     * @throws StorageException
     */
    public function questionSteps(): void
    {
        if ($this->chat->storage()->get('question_step') === 1) {
            $this->sedondQuestion();
        } elseif ($this->chat->storage()->get('question_step') === 2) {
            $this->thirdQuestion();
        }
    }

    /**
     * @throws StorageException
     */
    public function sedondQuestion(): void
    {
        $this->reply('second question');

        $this->chat->storage()->set('question_step', 2);
    }

    public function thirdQuestion(): void
    {
        $this->reply('third question');
    }
RudIhor commented 7 months ago

I'm not sure about this solution. I want to have a telegram command like /createPost for example then I ask a user "How would you name your post?" he enters a title of post then I retrieve data and validate it and tell him is it correct or not.

m-petrosyan commented 7 months ago

@RivGames like this?


 public function createPost(): void
    {
        $this->chat->message("How would you name your post?")->send();

        $this->chat->storage()->set('create_post', true);
    }

    /**
     * @throws StorageException
     */
    protected function handleChatMessage(Stringable $text): void
    {
        if ($this->chat->storage()->get('create_post')) {
            $validator = Validator::make(['value' => $text->value()], [
                'value' => 'required|string|min:2',
            ]);
            if ($validator->valid()) {
                $this->chat->message('correct')->send();
                $this->chat->storage()->forget('create_post');
            } else {
                $msg = $validator->messages()->all();
                $messages = '';

                foreach ($msg as $error) {
                    $messages .= $error.' 
';
                }
                $this->chat->message($messages)->send();
            }
        }
    }
RudIhor commented 7 months ago

Exactly. Thanks a lot!