PHP MySQL Dialogflow

后端 未结 1 347
名媛妹妹
名媛妹妹 2021-01-17 05:00

I\'m setting up a chatbot (dialogflow) with a PHP webhook

What I want to do is to take the user input to query a MySQL table and pass the result back to the dialogf

相关标签:
1条回答
  • 2021-01-17 05:48

    whenever the webhook gets triggered you need to listen to actions from JSON responses, from the action made the switch case of actions

    index.php

    <?php
    require 'get_enews.php';
    
    function processMessage($input) {
        $action = $input["result"]["action"];
        switch($action){
    
            case 'getNews':
                $param = $input["result"]["parameters"]["number"];
                getNews($param);
                break;
    
            default :
                sendMessage(array(
                    "source" => "RMC",
                    "speech" => "I am not able to understand. what do you want ?",
                    "displayText" => "I am not able to understand. what do you want ?",
                    "contextOut" => array()
                ));
        }
    }
    function sendMessage($parameters) {
        header('Content-Type: application/json');
        $data = str_replace('\/','/',json_encode($parameters));
        echo $data;
    }
    $input = json_decode(file_get_contents('php://input'), true);
    if (isset($input["result"]["action"])) {
        processMessage($input);
    }
    ?>
    

    get_enews.php

    <?php
    function getNews($param){
        require 'config.php';
        $getNews="";
        $Query="SELECT link FROM public.news WHERE year='$param'";
        $Result=pg_query($con,$Query);
        if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
        $row=pg_fetch_assoc($Result);
        $getNews= "Here is details that you require - Link: " . $row["link"];
            $arr=array(
                "source" => "RMC",
                "speech" => $getNews,
                "displayText" => $getNews,
            );
            sendMessage($arr);
        }else{
            $arr=array(
                "source" => "RMC",
                "speech" => "No year matched in database.",
                "displayText" => "No year matched in database.",
            );
            sendMessage($arr);
        }
    }
    ?>
    

    So when the action gets caught it will get executed and goes in the getNews($param); function here I am getting year as a response from the user in my case and I am executing the query in the database and giving back a response from the database.

    0 讨论(0)
提交回复
热议问题