2012/04/05

特定のキーワードでリスト追加/削除

お前はガンダムだ。

SRWZ2再世編発売日ですし、EasyBotter.phpを改造して、botが勝手にリスト追加・削除をするようにします。
リストIDはAPIからXMLを確認するなどでご確認ください。

class EasyBotter {
  // 最初のプライベート変数宣言群に追加
  private $_list_id = リストID;

  // 途中省略

  //リストに追加
  private function addMemberToList($user_id) {
    //リストID
    $list_id = $this->_list_id;
    //API実行
    $response = $this->createListMember($list_id, $user_id);
    if(empty($response->error)) {
      // 追加成功のリプライ
      return "分かった……お前はガンダムだ。";
    } else {
      // 追加失敗のリプライ
      return "お前はガンダムにはなれない。";
    }
  }

  //リストから削除
  private function removeMemberFromList($user_id) {
    //リストID
    $list_id = $this->_list_id;
    //API実行
    $response = $this->destroyListMember($list_id, $user_id);
    if(empty($response->error)) {
      // 削除成功のリプライ
      return "お前はガンダムではない……そういうことか。";
    } else {
      // 削除失敗のリプライ
      return "そうか……。";
    }
  }

  // 途中省略

  //リプライを作る
  private function makeReplyTweets($replies, $replyFile, $replyPatternFile){
    if(empty($this->_replyPatternData[$replyPatternFile]) && !empty($replyPatternFile)){
      $this->_replyPatternData[$replyPatternFile] = $this->readPatternFile($replyPatternFile);
    }
    $replyTweets = array();
    foreach($replies as $reply){
      $status = "";
      // ここから変更
      if(strpos((string)$reply->text, "俺がガンダムだ") !== FALSE) {
        //リスト追加
        $status = $this->addMemberToList((string)$reply->user->id);
      } else if(strpos((string)$reply->text, "俺はガンダムにはなれない") !== FALSE) {
        //リスト削除
        $status = $this->removeMemberFromList((string)$reply->user->id);
      } else if(!empty($this->_replyPatternData[$replyPatternFile])){
      // ここまで変更
        // リプライパターンと照合
        foreach($this->_replyPatternData[$replyPatternFile] as $pattern => $res){
          if(preg_match("@".$pattern."@u",$reply->text, $matches) === 1){
            $status = $res[array_rand($res)];
            for($i=1;$i <count($matches);$i++){
              $p = "$".$i;
              $status = str_replace($p,$matches[$i],$status);
            }
            break;
          }
        }
      }
    // 以下省略
  }

  // 途中省略

  // 基本的なAPIを叩く
  // 以下のメソッドを最下部に追加
  private function createListMember($list_id, $user_id) {
    $url = "https://api.twitter.com/1/lists/members/create.xml";
    return $this->_setData($url, array("list_id" => $list_id, "user_id" => $user_id));
  }
  private function destroyListMember($list_id, $user_id) {
    $url = "https://api.twitter.com/1/lists/members/destroy.xml";
    return $this->_setData($url, array("list_id" => $list_id, "user_id" => $user_id));
  }
}