在chatbot中,我們需要用到模式切換,而且不是用NLP處理,我們就需要寫一個中介的程式去處理這個工作。以下程式會詢問模式並記錄下來,10分鐘後會重問。此程式不需資料庫,直接記在檔案裡。
--------------------------------------------------------------------------------------------------------------------------------
$timeLimit = 600; // 保持模式的最長時間
$arrModeName = array();
$arrModeName[0] = '哈囉,這裡是入口,您想要處理務還是詢問相關問題? ';
$arrModeName[2] = '處理務';//務模式
$arrModeName[3] = '詢問相關問題';//問題模式
function router($message)
{
global $timeLimit;
global $arrModeName;
if($message['message']['text'] == $arrModeName[2])
{
setUserMode($message['source']['userId'],2);
}
else if($message['message']['text'] == $arrModeName[3])
{
setUserMode($message['source']['userId'],3);
}
list($mode,$time) = getUserMode($message['source']['userId']);
if(time() - $time > $timeLimit)
{//超過時間就重設為詢問模式
$mode = 1;
setUserMode($message['source']['userId'],$mode);
}
if($mode == 1)
{//詢問模式
echo $arrModeName[0];
}else if($mode == 2){
//傳給務模組
receiveMsg($message);
}
else if($mode == 3)
{//傳給問題模組
receiveMsg2($message);
}else
{
echo ("\n ERROR MODE");
}
}
function setUserMode($user,$mode)
{
$filename = './user/'.$user;
$strWrite = $mode.':'.time();
$filenum=fopen($filename,'w');
if(fwrite($filenum,$strWrite) === FALSE)
echo "Cannot write to file ($filename)";
fclose($filenum);
}
function getUserMode($user)
{
$filename = './user/'.$user;
if(file_exists($filename) ){
$filenum=fopen($filename,'r');
$str = fread($filenum,1);
fread($filenum,1);
$time = fread($filenum,10);
fclose($filenum);
$mode = intval($str);
$time = intval($time);
$strWrite = $mode.':'.time();
$filenum=fopen($filename,'w');
if(fwrite($filenum,$strWrite) === FALSE)
echo "Cannot write to file ($filename)";
}
else
{
$time = time();
$mode = 1;
$filenum=fopen($filename,'w');
$strWrite = $mode.':'.$time;
if(fwrite($filenum,$strWrite) === FALSE)
echo "Cannot write to file ($filename)";
chmod($filename,0666);
}
fclose($filenum);
return array($mode,$time);
}
?>
沒有留言:
張貼留言