4 # :title: lastfm plugin for rbot
6 # Author:: Jeremy Voorhis
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # Author:: Casey Link <unnamedrambler@gmail.com>
10 # Copyright:: (C) 2005 Jeremy Voorhis
11 # Copyright:: (C) 2007 Giuseppe Bilotta
12 # Copyright:: (C) 2008 Casey Link
16 require 'rexml/document'
23 @location = hash[:location]
24 @description = hash[:description]
25 @attendance = hash[:attendance]
27 @artists = hash[:artists]
29 if @artists.length > 10 #more than 10 artists and it floods
30 diff = @artists.length - 10
31 @artist_string = Bold + @artists[0..10].join(', ') + Bold
32 @artist_string << _(" and %{n} more...") % {:n => diff}
34 @artist_string = Bold + @artists.join(', ') + Bold
40 return "%s %s @ %s (%s attending) %s" % [@date.strftime("%a %b, %d %Y"), @artist_string, @location, @attendance, @url]
42 return "%s %s @ %s %s" % [@date.strftime("%a %b, %d %Y"), @artist_string, @location, @url]
44 alias :to_s :compact_display
48 class LastFmPlugin < Plugin
50 Config.register Config::IntegerValue.new('lastfm.max_events',
51 :default => 25, :validate => Proc.new{|v| v > 1},
52 :desc => "Maximum number of events to display.")
53 Config.register Config::IntegerValue.new('lastfm.default_events',
54 :default => 3, :validate => Proc.new{|v| v > 1},
55 :desc => "Default number of events to display.")
57 APIKEY = "b25b959554ed76058ac220b7b2e0a026"
58 APIURL = "http://ws.audioscrobbler.com/2.0/?api_key=#{APIKEY}&"
72 def help(plugin, topic="")
73 case (topic.intern rescue nil)
75 _("lastfm [<num>] events in <location> => show information on events in or near <location>. lastfm [<num>] events by <artist/group> => show information on events by <artist/group>. The number of events <num> that can be displayed is optional, defaults to %{d} and cannot be higher than %{m}") % {:d => @bot.config['lastfm.default_events'], :m => @bot.config['lastfm.max_events']}
77 _("lastfm artist <name> => show information on artist <name> from last.fm")
79 _("lastfm album <name> => show information on album <name> from last.fm [not implemented yet]")
81 _("lastfm track <name> => search tracks matching <name> on last.fm")
83 _("lastfm now [<user>] => show the now playing track from last.fm. np [<user>] does the same.")
85 _("lastfm set nick <user> => associate your current irc nick with a last.fm user. lastfm set verb <present> <past> => set your preferred now playing verb. default \"listening\" and \"listened\".")
87 _("lastfm who [<nick>] => show who <nick> is at last.fm. if <nick> is empty, show who you are at lastfm.")
89 _("lastfm compare <nick1> <nick2> => show musical taste compatibility between nick1 and nick2.")
91 _("lastfm [<user>] => show your or <user>'s now playing track at lastfm. np [<user>] => same as 'lastfm'. other topics: events, artist, album, track, now, set, who, compare")
95 def find_events(m, params)
96 num = params[:num] || @bot.config['lastfm.default_events']
97 num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
99 location = artist = nil
100 location = params[:location].to_s if params[:location]
101 artist = params[:who].to_s if params[:who]
105 uri = "#{APIURL}method=geo.getevents&location=#{CGI.escape location}"
107 uri = "#{APIURL}method=artist.getevents&artist=#{CGI.escape artist}"
109 xml = @bot.httputil.get_response(uri)
111 doc = Document.new xml.body
112 if xml.class == Net::HTTPInternalServerError
113 if doc.root and doc.root.attributes["status"] == "failed"
114 m.reply doc.root.elements["error"].text
116 m.reply _("Could not retrieve events")
119 disp_events = Array.new
121 doc.root.elements.each("events/event"){ |e|
123 h[:title] = e.elements["title"].text
124 venue = e.elements["venue"].elements["name"].text
125 city = e.elements["venue"].elements["location"].elements["city"].text
126 country = e.elements["venue"].elements["location"].elements["country"].text
127 h[:location] = Underline + venue + Underline + " #{Bold + city + Bold}, #{country}"
128 date = e.elements["startDate"].text.split
129 h[:date] = Time.utc(date[3].to_i, date[2], date[1].to_i)
130 h[:desc] = e.elements["description"].text
131 h[:url] = e.elements["url"].text
133 if node.kind_of? Element and node.attributes["name"] == "attendance" then
134 h[:attendance] = node.text
138 e.elements.each("artists/artist"){ |a|
141 h[:artists] = artists
142 events << LastFmEvent.new(h)
144 events[0...num].each { |event|
145 disp_events << event.to_s
147 m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
151 def tasteometer(m, params)
152 opts = { :cache => false }
153 user1 = params[:user1].to_s
154 user2 = params[:user2].to_s
155 xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{CGI.escape user1}&value2=#{CGI.escape user2}", opts)
156 doc = Document.new xml.body
158 m.reply _("last.fm parsing failed")
161 if xml.class == Net::HTTPInternalServerError
162 if doc.root.elements["error"].attributes["code"] == "7" then
163 error = doc.root.elements["error"].text
164 error.match(/Invalid username: \[(.*)\]/);
165 if @registry.has_key? $1 and not params[:recurs]
167 params[:user1] = @registry[ $1 ]
169 params[:user2] = @registry[ $1 ]
171 params[:recurs] = true
172 tasteometer(m, params)
174 m.reply _("%{u} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>") % {:u => baduser}
178 m.reply _("Bad: %{e}") % {:e => doc.root.element["error"].text}
182 now = artist = track = albumtxt = date = nil
183 score = doc.root.elements["comparison/result/score"].text.to_f
189 rating = _("Very High")
197 rating = _("Very Low")
199 m.reply _("%{a}'s and %{b}'s musical compatibility rating is: %{r}") % {:a => user1, :b => user2, :r => rating}
202 def now_playing(m, params)
203 opts = { :cache => false }
206 user = params[:who].to_s
207 elsif @registry.has_key? m.sourcenick
208 user = @registry[ m.sourcenick ]
212 xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{CGI.escape user}", opts)
213 doc = Document.new xml.body
215 m.reply _("last.fm parsing failed")
218 if xml.class == Net::HTTPBadRequest
219 if doc.root.elements["error"].text == "Invalid user name supplied" then
220 if @registry.has_key? user and not params[:recurs]
221 params[:who] = @registry[ user ]
222 params[:recurs] = true
223 now_playing(m, params)
225 m.reply "#{user} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>"
229 m.reply _("Error %{e}") % {:e => doc.root.element["error"].text}
233 now = artist = track = albumtxt = date = nil
234 unless doc.root.elements[1].has_elements?
235 m.reply _("%{u} hasn't played anything recently") % {:u => user}
238 first = doc.root.elements[1].elements[1]
239 now = first.attributes["nowplaying"]
240 artist = first.elements["artist"].text
241 track = first.elements["name"].text
242 albumtxt = first.elements["album"].text
245 year = get_album(artist, albumtxt)[2]
246 album = "[#{albumtxt}, #{year}] " if year
248 date = first.elements["date"].attributes["uts"]
249 past = Time.at(date.to_i)
251 verb = _("listening")
252 if @registry.has_key? "#{m.sourcenick}_verb_present"
253 verb = @registry["#{m.sourcenick}_verb_present"]
255 m.reply _("%{u} is %{v} to \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
258 if @registry.has_key? "#{m.sourcenick}_verb_past"
259 verb = @registry["#{m.sourcenick}_verb_past"]
261 ago = Utils.timeago(past)
262 m.reply _("%{u} %{v} to \"%{t}\" by %{a} %{b}%{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
266 def find_artist(m, params)
267 xml = @bot.httputil.get("#{APIURL}method=artist.getinfo&artist=#{CGI.escape params[:artist].to_s}")
269 m.reply _("I had problems getting info for %{a}.") % {:a => params[:artist]}
272 doc = Document.new xml
274 m.reply _("last.fm parsing failed")
277 first = doc.root.elements["artist"]
278 artist = first.elements["name"].text
279 playcount = first.elements["stats"].elements["plays"].text
280 listeners = first.elements["stats"].elements["listeners"].text
281 summary = first.elements["bio"].elements["summary"].text
282 m.reply _("%{b}%{a}%{b} has been played %{c} times and is being listened to by %{l} people.") % {:b => Bold, :a => artist, :c => playcount, :l => listeners}
283 m.reply summary.ircify_html
286 def find_track(m, params)
287 track = params[:track].to_s
288 xml = @bot.httputil.get("#{APIURL}method=track.search&track=#{CGI.escape track}")
290 m.reply _("I had problems getting info for %{a}.") % {:a => track}
294 doc = Document.new xml
296 m.reply _("last.fm parsing failed")
300 results = doc.root.elements["results/opensearch:totalResults"].text.to_i rescue 0
304 doc.root.each_element("results/trackmatches/track") do |track|
305 hits << _("%{bold}%{t}%{bold} by %{bold}%{a}%{bold} (%{n} listeners)") % {
306 :t => track.elements["name"].text,
307 :a => track.elements["artist"].text,
308 :n => track.elements["listeners"].text,
312 m.reply hits.join(' -- '), :split_at => ' -- '
315 m.reply _("last.fm parsing failed")
318 m.reply _("track %{a} not found") % {:a => track}
322 def get_album(artist, album)
323 xml = @bot.httputil.get("#{APIURL}method=album.getinfo&artist=#{CGI.escape artist}&album=#{CGI.escape album}")
325 return [_("I had problems getting album info")]
327 doc = Document.new xml
329 return [_("last.fm parsing failed")]
331 album = date = playcount = artist = date = year = nil
332 first = doc.root.elements["album"]
333 artist = first.elements["artist"].text
334 playcount = first.elements["playcount"].text
335 album = first.elements["name"].text
336 date = first.elements["releasedate"].text
337 unless date.strip.length < 2
338 year = date.strip.split[2].chop
340 result = [artist, album, year, playcount]
344 def find_album(m, params)
345 album = get_album(params[:artist].to_s, params[:album].to_s)
347 m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
350 year = "(#{album[2]}) " unless album[2] == nil
351 m.reply _("The album \"%{a}\" by %{r} %{y}has been played %{c} times.") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
354 def set_user(m, params)
355 user = params[:who].to_s
357 @registry[ nick ] = user
358 m.reply _("Ok, I'll remember that %{n} is %{u} at last.fm") % {:n => nick, :u => user}
361 def set_verb(m, params)
362 past = params[:past].to_s
363 present = params[:present].to_s
364 key = "#{m.sourcenick}_verb_"
365 @registry[ "#{key}past" ] = past
366 @registry[ "#{key}present" ] = present
367 m.reply _("Ok, I'll remember that %{n} prefers %{r} and %{p}.") % {:n => m.sourcenick, :p => past, :r => present}
370 def get_user(m, params)
373 nick = params[:who].to_s
377 if @registry.has_key? nick
378 user = @registry[ nick ]
379 m.reply "#{nick} is #{user} at last.fm"
381 m.reply _("Sorry, I don't know who %{n} is at last.fm perhaps you need to: lastfm set <username>") % {:n => nick}
385 # TODO this user data retrieval should be upgraded to API 2.0 but it would need separate parsing
386 # for each dataset, or almost
387 def lastfm(m, params)
388 action = params[:action].intern
389 action = :neighbours if action == :neighbors
390 action = :recenttracks if action == :recentracks
391 action = :topalbums if action == :topalbum
392 action = :topartists if action == :topartist
393 action = :toptags if action == :toptag
395 if params[:user] then
396 user = params[:user].to_s
397 elsif @registry.has_key? m.sourcenick
398 user = @registry[ m.sourcenick ]
400 # m.reply "I don't know who you are on last.fm. Use 'lastfm set username' to identify yourself."
405 data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
406 m.reply "#{action} for #{user}:"
407 m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
409 m.reply "could not find #{action} for #{user} (is #{user} a user?). perhaps you need to: lastfm set <username>"
414 plugin = LastFmPlugin.new
415 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
416 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
417 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
418 plugin.map 'lastfm now :who', :action => :now_playing, :thread => true
419 plugin.map 'lastfm now', :action => :now_playing, :thread => true
420 plugin.map 'np :who', :action => :now_playing, :thread => true
421 plugin.map 'lastfm artist *artist', :action => :find_artist, :thread => true
422 plugin.map 'lastfm album *album [by *artist]', :action => :find_album
423 plugin.map 'lastfm track *track', :action => :find_track, :thread => true
424 plugin.map 'lastfm set nick :who', :action => :set_user, :thread => true
425 plugin.map 'lastfm set verb :present :past', :action => :set_verb, :thread => true
426 plugin.map 'lastfm who :who', :action => :get_user, :thread => true
427 plugin.map 'lastfm who', :action => :get_user, :thread => true
428 plugin.map 'lastfm compare :user1 :user2', :action => :tasteometer, :thread => true
429 plugin.map 'np', :action => :now_playing, :thread => true
430 plugin.map 'lastfm', :action => :now_playing, :thread => true
431 plugin.map "lastfm [user] :action [:user]", :thread => true,
432 :requirements => { :action =>
433 /^(?:events|friends|neighbou?rs|playlists|recent?tracks|top(?:album|artist|tag)s?|weekly(?:album|artist|track)chart|weeklychartlist)$/