思路:
通過用戶發送的關鍵字判斷的方式來判斷功能,再調用回復相應的內容。
當一個功能不匹配的時候,則進入下一個功能判斷。
程序示例如下:
//接收文本消息 private function receiveText($object) { $keyword = trim($object->Content); //判斷天氣 if (strstr($keyword, "天氣")){ $city = str_replace('天氣', '', $keyword); include("weather.php"); $content = getWeatherInfo($city); //判斷笑話 }else if (strstr($keyword, "笑話")){ include("joke.php"); $content = getJokeInfo(); //判斷世界杯 }else if (strstr($keyword, "世界杯")){ $content[] = array("Title" =>"2014年巴西世界杯賽程","Description" =>"", "PicUrl" =>"https://images0.cnblogs.com/i/340216/201406/111304544204656.jpg", "Url" =>"http://url.cn/RInu1v"); //其他默認回復 }else{ $content = date("Y-m-d H:i:s",time())."\n技術支持 方倍工作室"; } if(is_array($content)){ if (isset($content[0]['PicUrl'])){ $result = $this->transmitNews($object, $content); }else if (isset($content['MusicUrl'])){ $result = $this->transmitMusic($object, $content); } }else{ $result = $this->transmitText($object, $content); } return $result; }
上述代碼使用if else if這樣的分支語句實現類別區分,比如發送“深圳天氣”之后,
if (strstr($keyword, "天氣")){
判斷文字中包括“天氣”二個字,就進入了天氣類別,
剩下還要把“深圳”2個字提取出來,使用字符串替換的方式,把“天氣”2個字替換成空(也就是相當於刪除)。
$city = str_replace('天氣', '', $keyword);
這樣就得到城市名稱了。
再將天氣查詢文件包含進來,並且將城市名稱傳入
include("weather.php"); $content = getWeatherInfo($city);
這樣就查詢到了深圳的天氣預報信息。
同樣的方法,可以將其他功能完整整合進來。