Я работаю над чат-ботом с помощью службы помощника Watson js и php проект разделен на четыре файла следующим образом:
/ main. js
let submitButton = document.querySelector(".submit-button");
let inputField = document.getElementById("text-input");
let chatField = document.querySelector(".chatbot-window");
let sessionID;
let formData;
let easyLang = true;
let vh = window.innerHeight * 0.01;
document.querySelector("body").style.setProperty('--vh', `${vh}px`);
window.addEventListener('resize', () => {
let vh = window.innerHeight * 0.01;
document.querySelector("body").style.setProperty('--vh', `${vh}px`);
});
// document.querySelector(".toggle-lang-mode").addEventListener("click", toggleEasyLang);
function toggleEasyLang() {
easyLang = !easyLang;
log.warn("Easylang func")
}
window.onload = function() {
let request = new XMLHttpRequest();
request.open("POST", "session.php", true);
//request.open("POST", "requestscript.php", true);
request.send();
request.onreadystatechange = function() {
//
if(this.readyState == XMLHttpRequest.DONE) {
if(this.status === 200) {
console.log(this.responseText);
response = JSON.parse(this.responseText);
sessionID = response.session_id;
localStorage.setItem("session_id", sessionID)
console.log(sessionID);
chatField.innerHTML = this.responseText;
console.log("Window on load!");
} else {
console.log("Request failed!");
}
}
};
request.open("POST", "chatbot.php", true);
formData = new FormData();
sessionID = localStorage.getItem("session_id");
console.log("this is ::"+ sessionID);
formData.append("input", "hi");
formData.append("session_id", sessionID);
console.log(sessionID);
request.send(formData);
request.onreadystatechange = function() {
//
if(this.readyState == XMLHttpRequest.DONE) {
if(this.status === 200) {
console.log(this.responseText);
response = JSON.parse(this.responseText);
console.log(response);
createChatField(response.output.generic[0].text, "answer");
inputField.value = ""
} else {
console.log(this.response);
}
}
}
}
submitButton.addEventListener("click", function() {
if(inputField.value !== "" ) {
let request = new XMLHttpRequest();
let formData = new FormData();
sessionID = localStorage.getItem("session_id");
formData.append("input", inputField.value);
formData.append("session_id", sessionID);
formData.append("langmode", easyLang);
request.open("POST", "chatbot.php", true);
createChatField(inputField.value, "question");
request.send(formData);
request.onreadystatechange = function() {
//
if(this.readyState == XMLHttpRequest.DONE) {
if(this.status === 200) {
console.log(this.responseText);
response = JSON.parse(this.responseText);
console.log(response);
if(response.output.generic[0].response_type == "text") {
createChatField(response.output.generic[0].text, "answer");
}
if(response.output.generic[0].response_type == "suggestion") {
renderSuggestionField(response.output.generic[0].suggestions);
console.log("suggestion detected!")
}
if(response.output.generic[1] !== undefined) {
if(response.output.generic[1].hasOwnProperty("options")) {
renderSuggestionField(response.output.generic[1].options);
}
}
inputField.value = ""
} else {
console.log("Request failed!");
}
}
};
} else {
console.log()
}
});
function createChatField(input, chatbubbleType) {
let chatBubble = document.createElement("div");
if(chatbubbleType === "question") {
chatBubble.className = "chatbubble-question"
}
if(chatbubbleType === "answer") {
chatBubble.className = "chatbubble-answer"
}
chatBubble.setAttribute("lang", "en");
chatBubble.innerHTML = input
chatField.append(chatBubble);
}
function renderSuggestionField(suggestions) {
let suggestionRow = document.createElement("div");
chatField.append(suggestionRow);
suggestionRow.className = "suggestion-row";
suggestionRow.innerHTML = "<p class='suggestion-head'>Did you mean:</p><br></br>";
suggestions.forEach(function(element) {
let suggestionField = document.createElement("div");
suggestionField.className = "suggestion-field";
suggestionField.innerHTML = element.label
suggestionRow.append(suggestionField);
});
}
/ requestscript. php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$assistant_id = '3feb5ffa-19b7-4417-81d4-3a019d0f435a';
$baseUrl = "https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/1db0917d-f272-4cd1-b8c4-9f333d35a9a8/v2/assistants/$assistant_id";
$sessionId = $_POST['session_id'] != null ? $POST['session_id'] : null;
$requestUrl = $baseUrl."/sessions/$sessionId/message?version=2020-04-01";
$sessionUrl = $baseUrl."/sessions?version=2020-04-01";
header('Content-type: application/json');
if($sessionId != null && !empty($sessionId)) {
$config = array(
CURLOPT_URL => $requestUrl,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $_POST
);
echo makeRequest($config);
} else {
$params = $_POST;
$params['session_id'] = getsessionId()['session_id'];
$config = array(
CURLOPT_URL => $requestUrl,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params
);
echo makeRequest($config);
}
function makeRequest($config) {
$api_key = 'Iy978R_iNiCnx4hvvD9ZeibxW5LBcVAI-vK5PTfqim1e';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "apikey:" . $api_key);
curl_setopt_array($ch, $config);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function getsessionId() {
$assistant_id = '3feb5ffa-19b7-4417-81d4-3a019d0f435a';
$baseUrl = "https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/1db0917d-f272-4cd1-b8c4-9f333d35a9a8/v2/assistants/$assistant_id";
$sessionUrl = $baseUrl."/sessions?version=2020-04-01";
$config = array(
CURLOPT_URL => $sessionUrl,
CURLOPT_POST => true
);
return makeRequest($config);
}
?>
/ сеанс. php
<?php
$assistant_id = '3feb5ffa-19b7-4417-81d4-3a019d0f435a';
$baseURL = "https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/1db0917d-f272-4cd1-b8c4-9f333d35a9a8/v2/assistants/$assistant_id";
// API-Key
$api_key = "Iy978R_iNiCnx4hvvD9ZeibxW5LBcVAI-vK5PTfqim1e";
$sessionUrl = $baseURL."/sessions?version=2020-04-01";
$curl = curl_init($auth_aal);
<console class="log"> hi</console>
$config = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
//CURLOPT_USERPWD => "apikey:".$api_key,
CURLOPT_USERPWD => "apikey":"3feb5ffa-19b7-4417-81d4-3a019d0f435a",
CURLOPT_URL => $sessionUrl,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
);
curl_setopt_array($curl, $config);
$response = trim(curl_exec($curl));
//$responseArray = json_decode($response);
//$session_id = $responseArray["session_id"];
echo $response;
/ chatbot. php
<?php
$input = $_POST["input"];
$session_id = $_POST["session_id"];
$assistant_id = '3feb5ffa-19b7-4417-81d4-3a019d0f435a';
$baseURL = "https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/1db0917d-f272-4cd1-b8c4-9f333d35a9a8/v2/assistants/$assistant_id";
// API-Key
$api_key = "Iy978R_iNiCnx4hvvD9ZeibxW5LBcVAI-vK5PTfqim1e";
$requestURL = $baseURL."/sessions/$session_id/message?version=2020-04-01";
$payload = json_encode(array(
"input" => [
"message_type" => "text",
"text" => $input,
"options" => [
"alternate_intents" => false,
"debug" => true
]
],
));
$config = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => "apikey:".$api_key,
CURLOPT_POST => true,
CURLOPT_URL => $requestURL,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => $payload
);
$curl = curl_init();
curl_setopt_array($curl, $config);
$response = trim(curl_exec($curl));
echo $response;
Во время работы он дает мне две ошибки Uncaught TypeError: Невозможно прочитать свойство 'generi c' неопределенного значения в XMLHttpRequest.request.onreadystatechange И «ошибка»: «Параметр URL sessionid 'null' не является допустимым GUID.», «code»: 400 }
У кого-нибудь есть идеи, как это исправить?!