gpt4 book ai didi

PHP MySQL 对话流

转载 作者:行者123 更新时间:2023-11-29 17:50:47 25 4
gpt4 key购买 nike

我正在使用 PHP webhook 设置聊天机器人 (dialogflow)

我想要做的是获取用户输入来查询 MySQL 表并将结果传递回对话流 API

到目前为止,我成功地将文本字符串传递回 API,但我不明白如何查询数据库并将结果传递回对话流 API

我将感谢您对此的帮助
我使用了对话流文档 here 中的 API 格式

这就是我所拥有的

<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters->cities;
$conn = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$sql = "SELECT * FROM exampletable LIKE '%".$_POST["cities"]."%'";
$result = mysqli_query($conn, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
$speech = $emparray;
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode(array($response,$emparray));
else
{
echo "Method not allowed";
}
?>


谢谢

最佳答案

每当 webhook 被触发时,您都需要监听 JSON 响应中的 actions,从 action 生成 actions

的 switch case

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);
}
}
?>

因此,当操作被捕获时,它将被执行并进入 getNews($param); 函数,我收到 year 作为用户的响应我的情况是,我正在数据库中执行查询并从数据库返回响应。

关于PHP MySQL 对话流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49363518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com