2011-05-28

自己动手改twitter2weibo,用APP KEY方式同步Twitter到新浪微博

Twitter2weibo又不能同步了,据说必须使用新浪的app
key才行。想换用tw2other,看了一下最新的版本,完全不理解为什么还需要twitter的密码以及xauth。

搜索到这篇blog,http://wangblog.org/2010/03/twitter-sina-api.html

试用了下文中代码,可以成功调用新浪围脖api,于是把twitter2weibo改写,成功恢复同步。




<?php
header('Content-type: text/html; charset=utf-8');
/* 所有都是utf-8字符的 */

//$d = getApi('http://twitter.com/users/show/wangblog.json');
/* wangblog的用户信息 */

//$d = getApi('http://twitter.com/statuses/friends_timeline.json', 'user:pass');
/* wangblog的所有Following用户的最新信息 */

//$d = getApi('http://twitter.com/statuses/update.json', 'user:pass',
'status='.urlencode('test twitter\'s api.'));
/* 发表微博给twitter */

//$d = getApi('http://api.t.sina.com.cn/statuses/update.json',
'user:pass', 'source=2924220432&status='.urlencode('test sina\'s
api.'));
/* 发表微博给sina,其中 source 是用的分享按钮的 */

$file = 'log';
/* 改成要同步的twitter ID */
$twitter_name = 'xxxxxx';

function getApi($url, $userpass, $data){
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
if($userpass){
curl_setopt($curl, CURLOPT_USERPWD, $userpass);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
if($data){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_URL, $url);
$cdata = curl_exec($curl);
$cheaders = curl_getinfo($curl);
if(200 == $cheaders['http_code']){
return $cdata;
}else{
print_r($cheaders);
exit;
}
}

//print_r(json_decode($d));

if(file_exists($file)){
$lastid = file_get_contents($file);
}else{
touch($file);
$lastid = 0;
}

#echo $lastid."<br />" ;

$timeline_url =
'http://montywz.appspot.com/statuses/user_timeline/'.$twitter_name.'.json';
/* 这里可以用twitter官方的api */
if($lastid!==0) $timeline_url.='?since_id='.$lastid;

#echo $timeline_url;

$timeline = file_get_contents($timeline_url);
$arr = json_decode($timeline,TRUE);
if(empty($arr)) exit();
$new_id = $arr[0]['id_str'];
if($new_id == '') exit();
file_put_contents($file,$new_id);
$post_arr = array();
foreach($arr as $tweet){
if(strpos($tweet['text'],'@')!==0){
$post_arr[] = $tweet['text'];
}
}

$post_arr = array_reverse($post_arr);

//发送信息到微博
foreach($post_arr as $item){
#echo $item."<br />";
getApi('http://api.t.sina.com.cn/statuses/update.json',
'user:pass', 'source=2924220432&status='.urlencode($item));
/* 发表微博给sina,其中 source 是用的分享按钮的, 把'user:pass'改成新浪微博的用户名和密码 */
}


?>

没有评论: