简体   繁体   English

本地主机上的 ChatScript Bot

[英]ChatScript Bot on Localhost

I have created a chatbot using chatscript.我使用 chatscript 创建了一个聊天机器人。 It works perfectly in .cmd when I execute a chatscript.exe program.当我执行 chatscript.exe 程序时,它在 .cmd 中完美运行。 Now I am trying to run the chatbot the browser using xampp.现在我正在尝试使用 xampp 在浏览器中运行聊天机器人。 I have done the following steps:我已经完成了以下步骤:

  1. I have installed XAMPP on C drive.我已经在 C 盘上安装了 XAMPP。
  2. In XAMPP > HTDOCS folder I have added the Chatscript folder in it.在 XAMPP > HTDOCS 文件夹中,我在其中添加了 Chatscript 文件夹。
  3. I am using Better web interface provided by chatscript.我正在使用 chatscript 提供的更好的网络界面。
  4. When I try to run the index.php file, the bot doesn't reply.当我尝试运行 index.php 文件时,机器人不回复。

Please find below code used in the web interface.请找到以下 Web 界面中使用的代码。 Index.php索引.php

<!DOCTYPE HTML>
<html>
  <head>
    <title> CHATSCRIPT SERVER
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
      #responseHolder {
        min-width: 600px;
        min-height: 300px;
        width: 80%;
        height: 300px;
        overflow: auto;
        margin: 10px auto;
        background-color: pink;

      }
      </style>
  </head>
  <body class="bgimg">
    <div id="responseHolder"></div>
    <form id="frmChat" action="#">
    <p>
      Enter your message below:
    </p>
    <table>
      <tr>
        <td>Name:</td>
        <td>
          <input type="text" id="txtUser" name="user" size="20" value="" />
          <input type="hidden" name="send" />
        </td>
      </tr>
      <tr>
        <td>Message:</td>
        <td><input type="text" name="message" id="txtMessage" size="70" /></td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" name="send" value="Send Value" /></td>
      </tr>
    </table>
    </form>

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">

var botName = 'rose';       // change this to your bot name

// declare timer variables
var alarm = null;
var callback = null;
var loopback = null;

$(function(){
    $('#frmChat').submit(function(e){
    // this function overrides the form's submit() method, allowing us to use AJAX calls to communicate with the ChatScript server
    e.preventDefault();  // Prevent the default submit() method
    var name = $('#txtUser').val();
    if (name == '') {
        alert('Please provide your name.');
        document.getElementById('txtUser').focus();
    }
    var chatLog = $('#responseHolder').html();
    var youSaid = '<strong>' + name + ':</strong> ' + $('#txtMessage').val() + "<br>\n";
    update(youSaid);
    var data = $(this).serialize();
    sendMessage(data);
    $('#txtMessage').val('').focus();
    });

    // any user typing cancels loopback or callback for this round 
    $('#txtMessage').keypress(function(){
          window.clearInterval(loopback);
          window.clearTimeout(callback);
        });
});

function sendMessage(data){ //Sends inputs to the ChatScript server, and returns the response-  data - a JSON string of input information
$.ajax({
    url: 'ui.php',
    dataType: 'text',
    data: data,
    type: 'post',
    success: function(response){
        processResponse(parseCommands(response));
    },
    error: function(xhr, status, error){
        alert('oops? Status = ' + status + ', error message = ' + error + "\nResponse = " + xhr.responseText);
    }
  });
}

function parseCommands(response){ // Response is data from CS server. This processes OOB commands sent from the CS server returning the remaining response w/o oob commands

    var len  = response.length;
    var i = -1;
    while (++i < len )
    {
        if (response.charAt(i) == ' ' || response.charAt(i) == '\t') continue; // starting whitespace
        if (response.charAt(i) == '[') break;   // we have an oob starter
        return response;                        // there is no oob data 
    }
    if ( i == len) return response; // no starter found
    var user = $('#txtUser').val();

    // walk string to find oob data and when ended return rest of string
    var start = 0;
    while (++i < len )
    {
        if (response.charAt(i) == ' ' || response.charAt(i) == ']') // separation
        {
            if (start != 0) // new oob chunk
            {
                var blob = response.slice(start,i);
                start = 0;

                var commandArr = blob.split('=');
                if (commandArr.length == 1) continue;   // failed to split left=right

                var command = commandArr[0]; // left side is command 
                var interval = (commandArr.length > 1) ? commandArr[1].trim() : -1; // right side is millisecond count
                if (interval == 0)  /* abort timeout item */
                {
                    switch (command){
                        case 'alarm':
                            window.clearTimeout(alarm);
                            alarm = null;
                            break;
                        case 'callback':
                            window.clearTimeout(callback);
                            callback = null;
                            break;
                        case 'loopback':
                            window.clearInterval(loopback);
                            loopback = null;
                            break;
                    }
                }
                else if (interval == -1) interval = -1; // do nothing
                else
                {
                    var timeoutmsg = {user: user, send: true, message: '[' + command + ' ]'}; // send naked command if timer goes off 
                    switch (command) {
                        case 'alarm':
                            alarm = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
                            break;
                        case 'callback':
                            callback = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
                            break;
                        case 'loopback':
                            loopback = setInterval(function(){sendMessage(timeoutmsg );}, interval);
                            break;
                    }
                }
            } // end new oob chunk
            if (response.charAt(i) == ']') return response.slice(i + 2); // return rest of string, skipping over space after ] 
        } // end if
        else if (start == 0) start = i; // begin new text blob
    } // end while
    return response;    // should never get here
 }

function update(text){ // text is  HTML code to append to the 'chat log' div. This appends the input text to the response div
    var chatLog = $('#responseHolder').html();
    $('#responseHolder').html(chatLog + text);
    var rhd = $('#responseHolder');
    var h = rhd.get(0).scrollHeight;
    rhd.scrollTop(h);
}

function processResponse(response) { // given the final CS text, converts the parsed response from the CS server into HTML code for adding to the response holder div
    var botSaid = '<strong>' + botName + ':</strong> ' + response + "<br>\n";
    update(botSaid);
}

</script>
</body>
</html>

ui.php用户界面.php

<?php

//  =============  user values ====
$host = "localhost";  //  <<<<<<<<<<<<<<<<< YOUR CHATSCRIPT SERVER IP ADDRESS OR HOST-NAME GOES HERE
$port = 8080;          // <<<<<<< your port number if different from 1024
$bot  = "rose";    
// <<<<<<< desired botname, or "" for default bot
//=========================

// Please do not change anything below this line.
$null = "\x00";
$postVars = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
extract($postVars);

if (isset($send))
{
     if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
       $userip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $userip = $_SERVER['REMOTE_ADDR'];
    }   
    $msg = $userip.$null.$bot.$null.$message.$null;

    if(!$fp=fsockopen($host,$port,$errstr,$errno,300))
    {
        trigger_error('Error opening socket',E_USER_ERROR);
    }    
    // write message to socket server
    fputs($fp,$msg);
    while (!feof($fp))
    {
        $ret .= fgets($fp, 512);
    }

    fclose($fp);
    exit($ret);
}

Please find below screenshot of the issue: Issue while accessing chatbot on localhost:8080请在下面找到问题的屏幕截图:在 localhost:8080 上访问聊天机器人时出现问题

I am having difficulty in connecting my chatscript server and localhost.我在连接我的聊天脚本服务器和本地主机时遇到了困难。 Please let me know what should I change in UI.php so that bot will send the reply.请让我知道我应该在 UI.php 中更改什么,以便机器人发送回复。

Thanks in advance.提前致谢。

There is one error in the UI.php file. UI.php 文件中有一个错误。 The $ret variable breaks because it is not declared. $ret变量由于未声明而中断。 If you add $ret = '';如果添加$ret = ''; just above fputs the code should work:就在fputs上面,代码应该可以工作:

 // write message to socket server
    $ret = '';
    fputs($fp,$msg);
    while (!feof($fp))
    {
        $ret .= fgets($fp, 512);
    }

    fclose($fp);
    exit($ret);
}

Besides the $ret correction, upon running in XAMPP, as the web host is Apache, so client uses port 8080 or 8088, upon using CS over Web.除了 $ret 修正之外,在 XAMPP 中运行时,由于 Web 主机是 Apache,因此在使用 CS over Web 时,客户端使用端口 8080 或 8088。 ChatScript as server, start the ChatScript system with using port 1024 ( or user-defined) is needed. ChatScript 作为服务器,需要使用端口 1024(或用户定义)启动 ChatScript 系统。 Furthermore, Harry Bot is also called in index.php file, change to Rose as in ui.php file.此外,在 index.php 文件中也调用了 Harry Bot,在 ui.php 文件中更改为 Rose。 I have CS responses after doing these.完成这些后,我有 CS 响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM