Twitter bot 2
2009年 12月 18日
自動フォローをしようと探してみたら
自動followについて良い記事を発見!!
http://d.hatena.ne.jp/bardothodol/20090818
これはフォローされればフォローするだけなので、
フォロー外れたら消すのも付け加えて見た。
<?php
//フォロワー一覧取得のための情報
$host_follow = "http://twitter.com/followers/ids.xml";
$XML_follow = getlist($host_follow,$username,$password);
$list = array();
//フォロワーのリストを配列に
foreach ($XML_follow->id as $id){
$list[] = $id;
}
//フレンズ(フォロー済みの人)一覧取得のための情報
$host_friends = "http://twitter.com/friends/ids.xml";
$XML_friends = getlist($host_friends,$username,$password);
$friends = array();
//フレンズのリストを配列に
foreach ($XML_friends->id as $id){
$friends[] = $id;
}
//フォロワーからフレンズの差分を求める(つまり、これからフォローするリスト)
$followlist = array_diff($list, $friends);
//フレンズからフォロワーの差分を求める(つまり、これからデストロイするリスト)
$destroylist = array_diff($friends, $list);
//フォローリストが空じゃなかったらforeachでフォローする
if ( !empty($followlist) ) {
foreach($followlist as $value){
$follow_ids = $value;
following($follow_ids,$username,$password);
}
}
//デストロイリストが空じゃなかったらforeachでデストロイする
if ( !empty($destroylist) ) {
foreach($destroylist as $value){
$destroy_ids = $value;
destroy($destroy_ids,$username,$password);
}
}
//一覧取得の関数(例によってcurl使用)
function getlist($host,$username,$password){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$result = curl_exec($ch);
curl_close($ch);
$XML = simplexml_load_string($result);
//戻り値
return $XML;
}
//フォローする関数
function following($follow_ids,$username,$password){
$base_url = "http://twitter.com/friendships/create/";
$base_url.=$follow_ids.".xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
//フォローはPOSTじゃないと駄目なので
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$buffer = curl_exec($ch);
curl_close($ch);
}
//デストロイする関数
function destroy($destroy_ids,$username,$password){
$base_url = "http://twitter.com/friendships/destroy/";
$base_url.=$destroy_ids.".xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
//デストロイはPOSTじゃないと駄目?未調査
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$buffer = curl_exec($ch);
curl_close($ch);
}
?>
