OAuthのアイコン変更

OAuthによるアイコン変更ができたのでメモしておきます。
参考にさせていただいたのは

Blogger

です。こちらにならってtwitteroauth.phpを改造。
例に出ているソースが私のブログで使っているバージョンとは違ったので、変更箇所もそれにあわせて変えました。

<?php
//前略190行目ぐらい、 function httpの前の行に
 //画像アップ関数
  function oAuthRequestImage($url, $method = NULL ,$args = array()) {//この行の引数と順序変わってます
    $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, array());
    $req->sign_request($this->sha1_method, $this->consumer, $this->token);
    return $this->http($req->get_normalized_http_url(), $method,$args, $req->to_header());//この行の引数と順序変わってます
}
  /**
   * Make an HTTP request
   *
   * @return API results
   */
  function http($url, $method, $postfields = NULL,$header = '') { //この行の引数に,$header = ''追加、順番も違う
  //中略
  curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:',$header)); //array('Expect:'));の部分を書き換え
  //後略
?>

こんな感じで書き換えます。わかりにくいですかね、ちょっと他にも置いてみようかと思います。

http://program.kir.jp/script/twitteroauth_php.txt twitteroauth.phpにしてね

アイコン変えスクリプト自体は↓

<?php
// twitteroauth.phpを読み込む。パスはあなたが置いた適切な場所に変更してください
require_once("twitteroauth.php");

// Consumer keyの値
$consumer_key = "";
// Consumer secretの値
$consumer_secret = "";
// Access Tokenの値
$access_token = "";
// Access Token Secretの値
$access_token_secret = "";

// OAuthオブジェクト生成
$to = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret);

//アイコン変更
$req = $to->OAuthRequestImage('https://twitter.com/account/update_profile_image.xml',"POST",array('image' => '@test.jpg'));

?>

同じフォルダに置いたtest.jpgをアップしている状態です。ファイル名の前に@を付けるのが流儀です。
これで変わりましたが、リプライ等で変えたい場合はもう少し工夫が必要です。

アイコンをリプライ等で変える - プログラミングを始める10の理由

でやったように、記録ファイルを用意して関数で変えられるようにします。
おなじみの、リプライで占いやって画像も変えるというもので。使い方はBasic認証でやった時と同じ感じです

<?php

// twitteroauth.phpを読み込む。パスはあなたが置いた適切な場所に変更してください
require_once("twitteroauth.php");

// Consumer keyの値
$consumer_key = "";
// Consumer secretの値
$consumer_secret = "";
// Access Tokenの値
$access_token = "";
// Access Token Secretの値
$access_token_secret = "";

//画像を入れておくディレクトリ
$img_dir = "./img/";

//無駄な画像アップロードをさけるため、最後にUPしたjpgファイル名を保存しておくテキスト
$last_img = "img2.txt";

$filename = "./tmp/data.txt";

$host = "http://twitter.com/statuses/mentions.xml"; //返信一覧

$fp = @fopen($filename,'rb') or die("ファイルが開けません");
flock($fp, LOCK_EX);
$line = fgets($fp, 64);
fclose($fp); 

// OAuthオブジェクト生成
$to = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret);


//保存しておいたステータスid取得。このid以降の返信を読み込む。なかったり読み込めなかったら最新1件

if(!empty($line)){
$req = $to->OAuthRequest($host,"GET",array("since_id"=>$line));
}
else{
    $req = $to->OAuthRequest($host,"GET",array("count"=>"1"));
    }


//XML文字列をオブジェクトに代入する 
$XML = simplexml_load_string($req);


//ここからが変わったところ。以前保存したid以降、複数リプライある場合whileで処理。
//新しい程配列のキーが若いので、減算子を使う(for文でもできるんじゃ…)
$i = count($XML)-1;
$j = 0;
 while($i >= $j) {
$var =  $XML->status[$i]->text;
$com = ereg_replace("\@$username", "", $var);
$reply_name = $XML->status[$i]->user->screen_name;
$name = $XML->status[$i]->user->name;

//ゴチャゴチャするので、返信のセリフ組み合わせはユーザー定義関数で。
$message = serif($reply_name,$name,$com);
//そのままポストの関数へ…

$rel = $to->OAuthRequest("https://twitter.com/statuses/update.xml","POST",array("status"=>$message));
print $rel;
$i--;
}

//最終発言リプライのidを保存してる部分。先頭を調べて…
$string = $XML->status[0]->id;
//空じゃなかったら書き込み
if(!empty($string)){
$dat = (string)$string;
file_put_contents($filename,$dat,LOCK_EX);
}
//これでメインの処理は終わり


//セリフ生成のユーザー定義関数
function serif($reply_name,$name,$com){
//配列を用意して…
$uranai=array("大吉","中吉","小吉","末吉","","");
$janken=array("ぐー","ちょき","ぱー"); 
$img_array = array("daikiti.jpg","chuukiti.jpg","syoukiti.jpg","suekiti.jpg","kiti.jpg","kyou.jpg");
//スクリーンネームに@を付ける
$reply_name = "@$reply_name";
//特定語句に反応する部分
if(stristr($com, "占い")){
     $key = array_rand($uranai);
     $post = $uranai[$key];
     
     //
     $img = $img_array[$key];
     change_profile($img);
     //
     
    $return = $reply_name." ".$name."さんの運勢…".$post;
    }
    else if(stristr($com, "じゃんけん")){
         $key = array_rand($janken);
    $post = $janken[$key];
    $return = $reply_name." ".$name."さん、勝負だ!じゃんけん…".$post;
}
else{
    //このままだと鸚鵡返し。色々工夫してみて下さい
    $return = $reply_name." ".$com;
}
//戻り値
return $return;
}

function change_profile($img){
//グローバルで各種変数を。画像を1ファイル渡すだけで変わる仕様になってます。
    global $to,$img_dir,$last_img;
    
    $dat = file_get_contents($last_img);
    if($img != (string)$dat or $dat == null){
    $file = $img_dir;
    $file .=$img;
    if(file_exists( $file )){
        
        $file = "@".$file;
        $req = $to->OAuthRequestImage('https://twitter.com/account/update_profile_image.xml',"POST",array('image' => $file));
        
        if($req == true){
        
        echo 'ファイル'.$img.'をアップしました';
        $dat = (string)$img;
        
        $result = file_put_contents($last_img,$dat,LOCK_EX);
        
        if($result == false){
            echo $last_img.'に書き込めませんでした。パーミッションを確かめて下さい';
            }

return true; 
}else{
    echo '何らかの理由でアップできませんでした';
    }
}else{
    echo 'ファイル'.$img.'が存在しないためアップロードしませんでした';
    }
    }else{
        echo 'ファイルが同じだったのでアップしませんでした';
    }
}

でした。これでOAuthに移行できるな…はやく書き換えなきゃ…

※2010年8月9日追記。API変更により少し記述が変わっています。詳しくは下のトラックバックを参照。