Hatena::ブログ(Diary)

システムエンジニア奮闘記 〜ダメダメSEの備忘録〜

オススメ商品

2009/12/20

Twitter Bot by PHP

PHPTwitterBotを作った。

実行された時に自動フォローやフォロー解除する仕組みを実装した。


0.

PEAR::HTTP_Client」を使うと超簡単なので使う。

-----

pear install --alldeps HTTP_Client

-----


1.

Botプログラム

指定するのは「$username」と「$password」で「$msg」に入れた文字をPostする。

<?php

require_once 'HTTP/Client.php';

$twitter_url = 'http://twitter.com/';
$post_url    = $twitter_url . 'statuses/update.xml';
$follow_url  = $twitter_url . 'followers/ids.xml';
$friend_url  = $twitter_url . 'friends/ids.xml';
$create_url  = $twitter_url . 'friendships/create.xml';
$destroy_url = $twitter_url . 'friendships/destroy.xml';

$username = 'xxxxxxxx';
$password = 'xxxxxxxx';

$basic  = array('Authorization'=>'Basic ' . base64_encode($username . ':' . $password));
$client = new HTTP_Client(null, $basic);

// post message
   ・
   ・
   ・
$client->post($post_url, array('status' => $msg));

// get follow ids
$follow_ids = array();
$client->get($follow_url);
$res = $client->currentResponse();
$xml = new SimpleXMLElement($res['body']);
for ($i = 0; $i < count($xml->id); $i++) {
    $id = $xml->id[$i];
    $follow_ids[] = (int)$id;
}

// get friend ids
$friend_ids = array();
$client->get($friend_url);
$res = $client->currentResponse();
$xml = new SimpleXMLElement($res['body']);
for ($i = 0; $i < count($xml->id); $i++) {
    $id = $xml->id[$i];
    $friend_ids[] = (int)$id;
}

// create friend step
$ids = array();
$ids = array_diff($follow_ids, $friend_ids);
foreach ($ids as $id) {
    $client->post($create_url, array('user_id' => $id));
}

// destroy follow step
$ids = array();
$ids = array_diff($friend_ids, $follow_ids);
foreach ($ids as $id) {
    $client->post($destroy_url, array('user_id' => $id));
}

〜参考〜

Twitterbotを作ってみた - math, programming, and little something to laugh

http://d.hatena.ne.jp/aomori-ringo2/20091001/1254541419

PHPTwitterに投稿 - HIRACCHI H.D.

http://d.hatena.ne.jp/hirataka522/20080126/1201300282

PHPによる誰でも出来る簡単Twitterbotの作り方 - 遥か彼方の彼方から

http://d.hatena.ne.jp/tek_koc/20080804/1217822667

[観] Twitter API 仕様書 (勝手に日本語訳シリーズ)

http://watcher.moe-nifty.com/memo/2007/04/twitter_api.html