【问题标题】:How do I persist data collect from Botman to MySQL如何将从 Botman 收集的数据持久保存到 MySQL
【发布时间】:2020-10-20 12:43:08
【问题描述】:

我正在使用 laravel 和 botman 创建一个简单的问题跟踪聊天机器人。我正在努力将数据从 Botman 回复中持久化到 MySQL。

有什么建议吗?

【问题讨论】:

    标签: laravel botman


    【解决方案1】:

    我假设您使用 botman/studio(请参阅文档 here)并且您希望将用户的答案保存在扩展 BotMan\BotMan\Messages\Conversations\Conversation 类的类的框架中(在此示例中我们称其为 MainConversation目的)。

    原则上,步骤大致如下。

    首先,cd 到您的项目目录的根目录并打开 .env 并确保您的 MySQL 数据库已正确配置。它应该是这样的:

    DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=mybot DB_USERNAME=root DB_PASSWORD=
    

    然后运行以下命令:

    php artisan make:model blabla -m
    

    这将在您项目的database/migrations 目录中创建一个迁移。打开这个 php 文件并编辑 up() 函数并在新的数据库列中添加您想要的列:

    public function up() { 
        Schema::create('blabla', function (Blueprint $table) {
            $table->increments('id');
            $table->string('id_chat');
            $table->string('response');
            $table->timestamps(); 
        }); 
    }
    

    现在运行以下命令,将在您的数据库中创建新表:

    php artisan migrate
    

    现在是时候将您的模型连接到 MainConversation 类了。原理说明如下:

    namespace App\Conversations; 
    
    use app\blabla as database; // your model
    use BotMan\BotMan\Messages\Incoming\Answer as BotManAnswer;
    use BotMan\BotMan\Messages\Outgoing\OutgoingMessage; 
    use BotMan\BotMan\Messages\Outgoing\Question as BotManQuestion;
    use BotMan\BotMan\Messages\Conversations\Conversation; 
    
    class mainConversation extends conversation { 
        
        public $response;
    
        public function run () {
            $this->askResponse();
        }
    
        private function askResponse() { 
            $question = BotManQuestion::create("Blabla ?"); 
            $this->ask( $question, function ( BotManAnswer $answer ) { 
                if( $answer->getText () != '' ){ 
                    $this->response=$answer->getText()); 
                    $this->exit(); 
                } 
            }); 
        }
        // this function create the object that is linked to your db's table
        private function exit() { 
            $db = new database(); 
            $db->id_chat = $this->bot->getUser()->getId(); 
            $db->response = $this->response;
            $db->save();
            $message = OutgoingMessage::create('Bye!'); 
            return true; 
        } 
    }
    

    【讨论】:

    • 非常感谢。我会试试看,让你。
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    相关资源
    最近更新 更多