twbot2.rb (new version)
twbot.rb (old version)
2011年7月より、ダイレクトメッセージ関連のAPIが、古いOAuthトークンでは利用不可能になります。利用されたい場合は、再度認証をお願いします。なお再度認証を行うには、まずconfig.ymlファイルから'users/USERNAME'のエントリ(直下の'token'や'secret'も含む)を削除し、その後'ruby BOT_SCRIPT_NAME.rb add=USERNAME'を実行します。(2011.6.28)
twbot.rbの新しいバージョン「twbot2.rb」を公開開始しました。古いtwbot.rbはOAuthに対応しておらず、8月31日以降は利用出来なくなりますのでご注意下さい。なお、twbot.rbからtwbot2.rbへの移行は少ない労力で行えるようになっております。(2010.5.16)
twbot2.rbは、RubyにてTwitterのbot(プログラムにより自動的に発言を行うアカウント)作成を行う際に、その補助を行うライブラリです。どちらかといえばフレームワークに近いかもしれません。
特に、定期的に特定の位置からデータを取得し(RSSやTwitterのタイムラインなど)、それに基づいて発言を行うbotを作るのに適したものとなっています。
Rubyインタプリタの導入されている、定期的にプログラムを実行させるためのPC
twbot.rbの中では、TwBotというクラスが定義されています。ただしTwBotはそのままで利用するものではなく、次の手順を踏む必要があります。
例として、返信が来た件数をつぶやくbotのコードを示します(上記zipファイルにも同梱しています)。
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
$: << File.dirname(__FILE__)
require "twbot2"
require "rexml/document"
class SimpleBot < TwBot
def load_data
# =============================================================
# What the bot talks should be defined in 'load_data' method.
# This example is to fetch mentions to the bot and notify them.
# =============================================================
# ---------- fetch replies ----------
# downloading the XML
response = auth_http.get("/1/statuses/mentions.xml")
xml = REXML::Document.new(response.body)
# extracting only message IDs of the XML
mentions_ids = xml.elements.to_a("/statuses/status/id")
mentions_ids.map!{ |x| x.text.to_i }
# ---------- exclude old replies ----------
# If you create a new key in the Hash @config,
# this will be kept in the config file.
@config['last_id'] ||= 0
# keeping the newest ID among the downloaded mentions
new_last_id = mentions_ids.first
# excluding the IDs representing old messages
mentions_ids.reject!{ |m_id| m_id < @config['last_id'] }
# renewing the newest ID
@config['last_id'] = new_last_id
# ---------- return the message to be posted ----------
# The return value must be an array.
# If you specify strings as the return value,
# the bot will talk it as it is,
# when you run 'ruby simplebot.rb post'.
["#{mentions_ids.size} new replies found!"]
end
end
self_path = File.dirname(__FILE__)
ARGV.each do |mode|
SimpleBot.new mode, "#{self_path}/config.yml", "#{self_path}/error.log"
end
これを起動する手順は以下の通りです。
ポイントは、根本的に書かなければならないコードは「botが何を発言するか」だけであることです。それさえ書けばbotを作ることが出来ます。
TwBot#get_followers, TwBot#get_friends, TwBot#follow, TwBot#unfollow, TwBot#following_status, TwBot.retrieve_followers, TwBot.retrieve_friends, TwBot.make_following, TwBot.make_unfollowing, TwBot.check_following)を追加した。(C)2008- H.Hiro(Maraigue)
twbot.rbの複製・改変の条件は、(新)BSDライセンスに合わせます。BSDライセンス(原文) BSDライセンス(参考訳)
簡単に言えば、このソフトは無保証であり、また再配布(改変した上での再配布含む)の場合にも元の著作権表示などの部分が記されている必要があります。
私が使いやすいように書いているため、使いにくい点があるかもしれません。あらかじめご了承下さい。要望は可能な限りお受けします。
スクリプトに関する報告は、Twitter/h_hiro_および、メールアドレスmain(あっとまーく)hhiro.netにお願いします。