一个简单的小黄鸡应用

人人的小黄鸡其实是调用了simsimi的接口,它的开发者是华中科技大学的一名学生wang2 ,作者把人人网小黄鸡的代码托管在Github上。可以看出,功能是很强大的,不单单是调个api的是,我简单看了下,python、shell、redis、消息队列都有用到。那么,怎样用最短的时间写一个自己的“小黄鸡”呢?

其实很简单,作者的gist上的一段代码 给出我们一个接口:http://www.simsimi.com/func/req?lc=ch&msg=%s ,通过这个接口,我们就可以调simsimi的智能回复了。

PHP实现起来非常简单,就是用CURL先请求下simsimi,得到cookie,然后利用保存的cookie再去请求接口,返回json,有个reponse的key,对应的value就是回复了。

代码:

<?php
error_reporting(E_ERROR);
$msg = daddslashes($_GET['msg']);
simsimi($msg);

function simsimi($msg) {
	/*get cookie*/
	$url = "http://www.simsimi.com/";
	$ch = curl_init ( $url );
	curl_setopt ( $ch, CURLOPT_HEADER, 1 );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	$content = curl_exec ( $ch );
	$arr = explode ( "\r\n\r\n", $content );
	$header = $arr[0];
	$matches = $arr[1];
	preg_match ( "/set\-cookie:([^\r\n]*);/iU", $header, $matches );
	$cookie = $matches [1];
	curl_close ( $ch ); 
	
	/*get json response*/
	$url = "http://www.simsimi.com/func/req?lc=ch&ft=0.0&msg=$msg";
	$ch = curl_init ($url);
	curl_setopt ( $ch, CURLOPT_REFERER, "http://www.simsimi.com/talk.htm?lc=ch" );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt ( $ch, CURLOPT_COOKIE, $cookie );
	$content = json_decode ( curl_exec ( $ch ), 1 );
	curl_close ( $ch );
	if ($content ['result'] == '100') {
		$content ['response'];
		var_dump($content ['response']);
	} else {
		var_dump( 'nothing...');
	}
}

function daddslashes($string, $force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
// 	if(!defined('MAGIC_QUOTES_GPC'))
// 		define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		  if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}

function dhtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1',
				//$string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
			str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string));
	}
	return $string;
}

function http_get($url, $ref_url=NULL) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.81 Safari/537.36");
	if ($ref_url) {
		curl_setopt($ch, CURLOPT_REFERER, $ref_url);
	}
	$data = curl_exec($ch);
	curl_close();
	return $data;
}
?>

有兴趣的朋友可以到 我的网站玩玩~



你可能感兴趣的:(一个简单的小黄鸡应用)