4 # :title: Twitter Status Update for rbot
6 # Author:: Carter Parks (carterparks) <carter@carterparks.com>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # Author:: NeoLobster <neolobster@snugglenets.com>
10 # Copyright:: (C) 2007 Carter Parks
11 # Copyright:: (C) 2007 Giuseppe Bilotta
13 # Users can setup their twitter username and password and then begin updating
19 error "OAuth module could not be loaded, twits will not be submitted and protected twits will not be accessible"
25 class TwitterPlugin < Plugin
26 Config.register Config::StringValue.new('twitter.key',
28 :desc => "Twitter OAuth Consumer Key")
30 Config.register Config::StringValue.new('twitter.secret',
32 :desc => "Twitter OAuth Consumer Secret")
34 Config.register Config::IntegerValue.new('twitter.status_count',
35 :default => 1, :validate => Proc.new { |v| v > 0 && v <= 10},
36 :desc => "Maximum number of status updates shown by 'twitter status'")
38 Config.register Config::IntegerValue.new('twitter.friends_status_count',
39 :default => 3, :validate => Proc.new { |v| v > 0 && v <= 10},
40 :desc => "Maximum number of status updates shown by 'twitter friends status'")
45 @has_oauth = defined? OAuth
57 def report_oauth_missing(m, failed_action)
58 m.reply [failed_action, "I cannot authenticate to Twitter (OAuth not available)"].join(' because ')
61 def report_key_missing(m, failed_action)
62 m.reply [failed_action, "no Twitter Consumer Key/Secret is defined"].join(' because ')
65 def help(plugin, topic="")
66 return "twitter status [nick] => show nick's (or your) status, use 'twitter friends status [nick]' to also show the friends' timeline | twitter update [status] => updates your status on twitter | twitter authorize => Generates an authorization URL which will give you a PIN to authorize the bot to use your twitter account. | twitter pin [pin] => Finishes bot authorization using the PIN provided by the URL from twitter authorize. | twitter deauthorize => Makes the bot forget your Twitter account. | twitter actions [on|off] => enable/disable twitting of actions (/me does ...)"
69 # update the status on twitter
70 def get_status(m, params)
71 friends = params[:friends]
73 if @registry.has_key?(m.sourcenick + "_access_token")
74 @access_token = YAML::load(@registry[m.sourcenick + "_access_token"])
75 nick = params[:nick] || @access_token.params[:screen_name]
79 m.reply "You are not authorized with Twitter. Please use 'twitter authorize' first to use this feature."
81 report_oauth_missing(m, "I cannot retrieve your friends status")
89 m.reply "you should specify the username of the twitter to use, or identify using 'twitter authorize'"
93 count = @bot.config['twitter.friends_status_count']
94 user = URI.escape(nick)
95 if @has_oauth and @registry.has_key?(m.sourcenick + "_access_token")
97 #no change to count variable
98 uri = "https://api.twitter.com/1/statuses/friends_timeline.xml?count=#{count}"
99 response = @access_token.get(uri).body
101 count = @bot.config['twitter.status_count']
102 uri = "https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=#{user}&count=#{count}"
103 response = @access_token.get(uri).body
106 #unauthorized user, will try to get from public timeline the old way
107 uri = "http://twitter.com/statuses/user_timeline/#{user}.xml?count=#{count}"
108 response = @bot.httputil.get(uri, :cache => false)
116 rex = REXML::Document.new(response)
117 rex.root.elements.each("status") { |st|
118 # month, day, hour, min, sec, year = st.elements['created_at'].text.match(/\w+ (\w+) (\d+) (\d+):(\d+):(\d+) \S+ (\d+)/)[1..6]
119 # debug [year, month, day, hour, min, sec].inspect
120 # time = Time.local(year.to_i, month, day.to_i, hour.to_i, min.to_i, sec.to_i)
121 time = Time.parse(st.elements['created_at'].text)
123 # Sometimes, time can be in the future; invert the relation in this case
124 delta = ((time > now) ? time - now : now - time)
125 msg = st.elements['text'].to_s + " (#{Utils.secs_to_string(delta.to_i)} ago via #{st.elements['source'].to_s})"
128 author = Utils.decode_html_entities(st.elements['user'].elements['name'].text) + ": " rescue ""
130 texts << author+Utils.decode_html_entities(msg).ircify_html
133 # friends always return the latest 20 updates, so we clip the count
139 m.reply "could not parse status for #{nick}'s friends"
141 m.reply "could not parse status for #{nick}"
146 m.reply "No status updates!"
148 m.reply texts.reverse.join("\n")
153 rep = "could not get status for #{nick}'s friends"
154 rep << ", try asking in private" unless m.private?
156 rep = "could not get status for #{nick}"
163 def deauthorize(m, params)
164 if @registry.has_key?(m.sourcenick + "_request_token")
165 @registry.delete(m.sourcenick + "_request_token")
167 if @registry.has_key?(m.sourcenick + "_access_token")
168 @registry.delete(m.sourcenick + "_access_token")
170 m.reply "Done! You can reauthorize this account in the future by using 'twitter authorize'"
173 def authorize(m, params)
174 failed_action = "we can't complete the authorization process"
176 report_oauth_missing(m, failed_action)
180 #remove all old authorization data
181 if @registry.has_key?(m.sourcenick + "_request_token")
182 @registry.delete(m.sourcenick + "_request_token")
184 if @registry.has_key?(m.sourcenick + "_access_token")
185 @registry.delete(m.sourcenick + "_access_token")
188 key = @bot.config['twitter.key']
189 secret = @bot.config['twitter.secret']
190 if key.empty? or secret.empty?
191 report_key_missing(m, failed_action)
195 @consumer = OAuth::Consumer.new(key, secret, {
196 :site => "https://api.twitter.com",
197 :request_token_path => "/oauth/request_token",
198 :access_token_path => "/oauth/access_token",
199 :authorize_path => "/oauth/authorize"
201 @request_token = @consumer.get_request_token
202 @registry[m.sourcenick + "_request_token"] = YAML::dump(@request_token)
203 m.reply "Go to this URL to get your authorization PIN, then use 'twitter pin <pin>' to finish authorization: " + @request_token.authorize_url
207 unless @registry.has_key?(m.sourcenick + "_request_token")
208 m.reply "You must first use twitter authorize to get an authorization URL, which you can use to get a PIN for me to use to verify your Twitter account"
211 @request_token = YAML::load(@registry[m.sourcenick + "_request_token"])
213 @access_token = @request_token.get_access_token( { :oauth_verifier => params[:pin] } )
215 m.reply "Error: There was a problem registering your Twitter account. Please make sure you have the right PIN. If the problem persists, use twitter authorize again to get a new PIN"
218 @registry[m.sourcenick + "_access_token"] = YAML::dump(@access_token)
219 m.reply "Okay, you're all set"
222 # update the status on twitter
223 def update_status(m, params)
225 report_oauth_missing(m, "I cannot update your status")
229 unless @registry.has_key?(m.sourcenick + "_access_token")
230 m.reply "You must first authorize your Twitter account before tweeting."
233 @access_token = YAML::load(@registry[m.sourcenick + "_access_token"])
235 uri = "https://api.twitter.com/statuses/update.json"
236 msg = params[:status].to_s
239 m.reply "your status message update is too long, please keep it under 140 characters"
243 response = @access_token.post(uri, { :status => msg })
246 reply_method = params[:notify] ? :notify : :reply
247 if response.class == Net::HTTPOK
248 m.__send__(reply_method, "status updated")
250 m.__send__(reply_method, "could not update status")
254 # ties a nickname to a twitter username and password
255 def identify(m, params)
256 @registry[m.sourcenick + "_username"] = params[:username].to_s
257 @registry[m.sourcenick + "_password"] = params[:password].to_s
258 m.reply "you're all set up!"
261 # update on ACTION if the user has enabled the option
262 # Possible TODO: move the has_oauth check further down and alert
263 # the user the first time we do not update because of the missing oauth
265 return unless @has_oauth
266 return unless m.action?
267 return unless @registry[m.sourcenick + "_actions"]
268 update_status(m, :status => m.message, :notify => true)
271 # show or toggle action twitting
272 def actions(m, params)
275 @registry[m.sourcenick + "_actions"] = true
278 @registry.delete(m.sourcenick + "_actions")
281 if @registry[m.sourcenick + "_actions"]
282 m.reply _("actions will be twitted")
284 m.reply _("actions will not be twitted")
290 # create an instance of our plugin class and register for the "length" command
291 plugin = TwitterPlugin.new
292 plugin.map 'twitter update *status', :action => "update_status", :threaded => true
293 plugin.map 'twitter authorize', :action => "authorize", :public => false
294 plugin.map 'twitter deauthorize', :action => "deauthorize", :public => false
295 plugin.map 'twitter pin :pin', :action => "pin", :public => false
296 plugin.map 'twitter actions [:toggle]', :action => "actions", :requirements => { :toggle => /^on|off$/ }
297 plugin.map 'twitter status [:nick]', :action => "get_status", :threaded => true
298 plugin.map 'twitter :friends [status] [:nick]', :action => "get_status", :requirements => { :friends => /^friends?$/ }, :threaded => true