等待 botman 对话结束并继续

时间:2021-05-26 17:55:57

标签: php laravel facebook bots botman

您好,我正在尝试编写 Facebook 机器人,但挑战在于即使对话尚未结束,控制器中的代码也会执行。我怎样才能使这个同步?

这是我的控制器

class GetStartedController extends Controller
{
    public function index($bot)
    {
        $user = $bot->getUser();
        $ps_id = $user->getId();
        $bot_user = FacebookUser::where('ps_id',$ps_id)->first();
        if($bot_user == null){
            $bot->startConversation(new AskDemographics($bot));
            // $this->saveNewUser($user);
            $bot->reply("User saved");
        }else {
            $bot->reply("Display menu");
        }
    }

    public function saveNewUser($user){
        $_user = new User;
        $fb_user = new FacebookUser;

        $_user->name = $user->getFirstName() ." ". $user->getLastName();
        $_user->save();

        $fb_user->user_id = $_user->id;
        $fb_user->ps_id = $user->getId();
        $fb_user->save();
    }
}

在我的 AskDemoGraphics 对话中

<?php

namespace App\Conversations;

use BotMan\BotMan\BotMan;
use BotMan\BotMan\Messages\Incoming\Answer;
use BotMan\BotMan\Messages\Conversations\Conversation;


class AskDemographics extends Conversation
{
    public $bot;
    protected $year_of_birth;
    protected $firstname;

    public function __construct(BotMan $bot){
        $this->bot = $bot;
    }

    public function askYearOfBirth()
    {
        $msg = 'Please put your year of birth e.g 1997';
        $error_msg_age = 'Enter a valid age';
        $this->bot->typesAndWaits(1);

        $this->ask($msg , function ($answer, $conversation ) use ($error_msg_age) {
            $reply = $answer->getText();
            if (preg_match('/^\d{4}$/',$reply)){
                $this->say('Ask another question');
            }else{
                $conversation->say($error_msg_age);
                $this->askYearOfBirth();
            }

        });

    }

    /**
     * Start the conversation.
     *
     * @return mixed
     */

    public function run()
    {
        $this->askYearOfBirth();
    }
}

挑战在于,即使在用户输入年龄或任何内容之前,对话后调用的回复“用户已保存”已被回复。

0 个答案:

没有答案