1

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

有什么建议么?

4

1 回答 1

2

我假设您使用 botman/studio(请参阅此处的文档),并且您希望将用户的答案保存在扩展该类的类的框架中(为此示例目的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; 
    } 
}
于 2020-07-02T13:44:57.593 回答