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>
9 # Author:: Raine Virta <rane@kapsi.fi>
11 # Copyright:: (C) 2005 Jeremy Voorhis
12 # Copyright:: (C) 2007 Giuseppe Bilotta
13 # Copyright:: (C) 2008 Casey Link
14 # Copyright:: (C) 2009 Raine Virta
18 require 'rexml/document'
25 @location = hash[:location]
26 @description = hash[:description]
27 @attendance = hash[:attendance]
29 @artists = hash[:artists]
31 if @artists.length > 10 #more than 10 artists and it floods
32 diff = @artists.length - 10
33 @artist_string = Bold + @artists[0..10].join(', ') + Bold
34 @artist_string << _(" and %{n} more...") % {:n => diff}
36 @artist_string = Bold + @artists.join(', ') + Bold
41 unless @attendance.zero?
42 return "%s %s @ %s (%s attending) %s" % [@date.strftime("%a, %b %d"), @artist_string, @location, @attendance, @url]
44 return "%s %s @ %s %s" % [@date.strftime("%a, %b %d"), @artist_string, @location, @url]
46 alias :to_s :compact_display
50 class LastFmPlugin < Plugin
52 Config.register Config::IntegerValue.new('lastfm.max_events',
53 :default => 25, :validate => Proc.new{|v| v > 1},
54 :desc => "Maximum number of events to display.")
55 Config.register Config::IntegerValue.new('lastfm.default_events',
56 :default => 3, :validate => Proc.new{|v| v > 1},
57 :desc => "Default number of events to display.")
58 Config.register Config::IntegerValue.new('lastfm.max_shouts',
59 :default => 5, :validate => Proc.new{|v| v > 1},
60 :desc => "Maximum number of user shouts to display.")
61 Config.register Config::IntegerValue.new('lastfm.default_shouts',
62 :default => 3, :validate => Proc.new{|v| v > 1},
63 :desc => "Default number of user shouts to display.")
64 Config.register Config::IntegerValue.new('lastfm.max_user_data',
65 :default => 25, :validate => Proc.new{|v| v > 1},
66 :desc => "Maximum number of user data entries (except events and shouts) to display.")
67 Config.register Config::IntegerValue.new('lastfm.default_user_data',
68 :default => 10, :validate => Proc.new{|v| v > 1},
69 :desc => "Default number of user data entries (except events and shouts) to display.")
71 APIKEY = "b25b959554ed76058ac220b7b2e0a026"
72 APIURL = "http://ws.audioscrobbler.com/2.0/?api_key=#{APIKEY}&"
86 def help(plugin, topic="")
87 period = _(", where <period> can be one of: 3|6|12 months, a year")
88 case (topic.intern rescue nil)
90 _("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']}
92 _("lastfm artist <name> => show information on artist <name> from last.fm")
94 _("lastfm album <name> => show information on album <name> from last.fm [not implemented yet]")
96 _("lastfm track <name> => search tracks matching <name> on last.fm")
98 _("lastfm now [<nick>] => show the now playing track from last.fm. np [<nick>] does the same.")
100 _("lastfm set user <user> => associate your current irc nick with a last.fm user. lastfm set verb <present>, <past> => set your preferred now playing/just played verbs. default \"is listening to\" and \"listened to\".")
102 _("lastfm who [<nick>] => show who <nick> is on last.fm. if <nick> is empty, show who you are on lastfm.")
104 _("lastfm compare [<nick1>] <nick2> => show musical taste compatibility between nick1 (or user if omitted) and nick2")
106 _("lastfm shouts [<nick>] => show shouts to <nick>")
108 _("lastfm friends [<nick>] => show <nick>'s friends")
109 when :neighbors, :neighbours
110 _("lastfm neighbors [<nick>] => show people who share similar musical taste as <nick>")
112 _("lastfm loved[tracks] [<nick>] => show tracks that <nick> has loved")
113 when :recenttracks, :recentracks
114 _("lastfm recent[tracks] [<nick>] => show tracks that <nick> has recently played")
116 _("lastfm topalbums [<nick>] [over <period>] => show <nick>'s top albums%{p}") % { :p => period }
118 _("lastfm topartists [<nick>] [over <period>] => show <nick>'s top artists%{p}") % { :p => period }
120 _("lastfm toptracks [<nick>] [over <period>] => show <nick>'s top tracks%{p}") % { :p => period }
121 when :weeklyalbumchart
122 _("lastfm weeklyalbumchart [<nick>] => show <nick>'s weekly album chart")
123 when :weeklyartistchart
124 _("lastfm weeklyartistchart [<nick>] => show <nick>'s weekly artist chart")
125 when :weeklytrackchart
126 _("lastfm weeklyartistchart [<nick>] => show <nick>'s weekly track chart")
128 _("last.fm plugin - topics: events, artist, album, track, now, set, who, compare, shouts, friends, neighbors, (loved|recent)tracks, top(albums|tracks|artists), weekly(album|artist|track)chart")
132 def find_events(m, params)
133 num = params[:num] || @bot.config['lastfm.default_events']
134 num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
136 location = params[:location]
137 artist = params[:who]
138 user = resolve_username(m, params[:user])
141 uri = "#{APIURL}method=geo.getevents&location=#{CGI.escape location.to_s}"
142 emptymsg = _("no events found in %{location}") % {:location => location.to_s}
144 uri = "#{APIURL}method=artist.getevents&artist=#{CGI.escape artist.to_s}"
145 emptymsg = _("no events found by %{artist}") % {:artist => artist.to_s}
147 uri = "#{APIURL}method=user.getevents&user=#{CGI.escape user}"
148 emptymsg = _("%{user} is not attending any events") % {:user => user}
150 xml = @bot.httputil.get_response(uri)
152 doc = Document.new xml.body
153 if xml.class == Net::HTTPInternalServerError
154 if doc.root and doc.root.attributes["status"] == "failed"
155 m.reply doc.root.elements["error"].text
157 m.reply _("could not retrieve events")
160 disp_events = Array.new
162 doc.root.elements.each("events/event"){ |e|
164 h[:title] = e.elements["title"].text
165 venue = e.elements["venue"].elements["name"].text
166 city = e.elements["venue"].elements["location"].elements["city"].text
167 country = e.elements["venue"].elements["location"].elements["country"].text
168 h[:location] = Underline + venue + Underline + " #{Bold + city + Bold}, #{country}"
169 date = e.elements["startDate"].text.split
170 h[:date] = Time.utc(date[3].to_i, date[2], date[1].to_i)
171 h[:desc] = e.elements["description"].text
172 h[:url] = e.elements["url"].text
173 h[:attendance] = e.elements["attendance"].text.to_i
175 e.elements.each("artists/artist"){ |a|
178 h[:artists] = artists
179 events << LastFmEvent.new(h)
185 events[0...num].each { |event|
186 disp_events << event.to_s
188 m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
192 def tasteometer(m, params)
193 opts = { :cache => false }
194 user1 = resolve_username(m, params[:user1])
195 user2 = resolve_username(m, params[:user2])
196 xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{CGI.escape user1}&value2=#{CGI.escape user2}", opts)
197 doc = Document.new xml.body
199 m.reply _("last.fm parsing failed")
202 if xml.class == Net::HTTPBadRequest
203 if doc.root.elements["error"].attributes["code"] == "7" then
204 error = doc.root.elements["error"].text
205 error.match(/Invalid username: \[(.*)\]/);
208 m.reply _("%{u} doesn't exist on last.fm") % {:u => baduser}
211 m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
215 score = doc.root.elements["comparison/result/score"].text.to_f
216 artists = doc.root.get_elements("comparison/result/artists/artist").map { |e| e.elements["name"].text}
221 rating = _("Very High")
229 rating = _("Very Low")
232 reply = _("%{a}'s and %{b}'s musical compatibility rating is %{bold}%{r}%{bold}") % {
235 :r => rating.downcase,
239 reply << _(" and music they have in common includes: %{artists}") % {
240 :artists => artists.join(", ")
241 } unless artists.empty?
246 def now_playing(m, params)
247 opts = { :cache => false }
248 user = resolve_username(m, params[:who])
249 xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{CGI.escape user}", opts)
250 doc = Document.new xml.body
252 m.reply _("last.fm parsing failed")
255 if xml.class == Net::HTTPBadRequest
256 if doc.root.elements["error"].text == "Invalid user name supplied" then
257 m.reply _("%{user} doesn't exist on last.fm, perhaps they need to: lastfm user <username>") % {
262 m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
266 now = artist = track = albumtxt = date = nil
267 unless doc.root.elements[1].has_elements?
268 m.reply _("%{u} hasn't played anything recently") % {:u => user}
271 first = doc.root.elements[1].elements[1]
272 now = first.attributes["nowplaying"]
273 artist = first.elements["artist"].text
274 track = first.elements["name"].text
275 albumtxt = first.elements["album"].text
278 year = get_album(artist, albumtxt)[2]
279 album = "[#{albumtxt}, #{year}] " if year
282 date = XPath.first(first, "//date")
284 time = date.attributes["uts"]
285 past = Time.at(time.to_i)
288 verb = _("is listening to")
289 if @registry.has_key? "#{m.sourcenick}_verb_present"
290 verb = @registry["#{m.sourcenick}_verb_present"]
292 m.reply _("%{u} %{v} \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
294 verb = _("listened to")
295 if @registry.has_key? "#{m.sourcenick}_verb_past"
296 verb = @registry["#{m.sourcenick}_verb_past"]
298 ago = Utils.timeago(past)
299 m.reply _("%{u} %{v} \"%{t}\" by %{a} %{b}%{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
303 def find_artist(m, params)
304 info_xml = @bot.httputil.get("#{APIURL}method=artist.getinfo&artist=#{CGI.escape params[:artist].to_s}")
306 m.reply _("I had problems getting info for %{a}") % {:a => params[:artist]}
309 info_doc = Document.new info_xml
311 m.reply _("last.fm parsing failed")
314 tags_xml = @bot.httputil.get("#{APIURL}method=artist.gettoptags&artist=#{CGI.escape params[:artist].to_s}")
315 tags_doc = Document.new tags_xml
317 first = info_doc.root.elements["artist"]
318 artist = first.elements["name"].text
319 url = first.elements["url"].text
321 %w(playcount listeners).each do |e|
322 t = first.elements["stats/#{e}"].text
323 stats[e.to_sym] = t.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
325 summary = first.elements["bio"].elements["summary"].text
326 similar = first.get_elements("similar/artist").map { |a|
327 _("%{b}%{a}%{b}") % { :a => a.elements["name"].text, :b => Bold } }
328 tags = tags_doc.root.get_elements("toptags/tag")[0..4].map { |t|
329 _("%{u}%{t}%{u}") % { :t => t.elements["name"].text, :u => Underline } }
330 reply = _("%{b}%{a}%{b} <%{u}> has been played %{b}%{c}%{b} times and is being listened to by %{b}%{l}%{b} people") % {
331 :b => Bold, :a => artist, :u => url, :c => stats[:playcount], :l => stats[:listeners] }
332 reply << _(". Tagged as: %{t}") % {
333 :t => tags.join(", "), :b => Bold } unless tags.empty?
334 reply << _(". Similar artists: %{s}") % {
335 :s => similar.join(", "), :b => Bold } unless similar.empty?
337 m.reply summary.ircify_html
340 def find_track(m, params)
341 track = params[:track].to_s
342 xml = @bot.httputil.get("#{APIURL}method=track.search&track=#{CGI.escape track}")
344 m.reply _("I had problems getting info for %{a}") % {:a => track}
348 doc = Document.new xml
350 m.reply _("last.fm parsing failed")
354 results = doc.root.elements["results/opensearch:totalResults"].text.to_i rescue 0
358 doc.root.each_element("results/trackmatches/track") do |track|
359 hits << _("%{bold}%{t}%{bold} by %{bold}%{a}%{bold} (%{n} listeners)") % {
360 :t => track.elements["name"].text,
361 :a => track.elements["artist"].text,
362 :n => track.elements["listeners"].text,
366 m.reply hits.join(' -- '), :split_at => ' -- '
369 m.reply _("last.fm parsing failed")
372 m.reply _("track %{a} not found") % {:a => track}
376 def get_album(artist, album)
377 xml = @bot.httputil.get("#{APIURL}method=album.getinfo&artist=#{CGI.escape artist}&album=#{CGI.escape album}")
379 return [_("I had problems getting album info")]
381 doc = Document.new xml
383 return [_("last.fm parsing failed")]
385 album = date = playcount = artist = date = year = nil
386 first = doc.root.elements["album"]
387 artist = first.elements["artist"].text
388 playcount = first.elements["playcount"].text
389 album = first.elements["name"].text
390 date = first.elements["releasedate"].text
391 unless date.strip.length < 2
392 year = date.strip.split[2].chop
394 result = [artist, album, year, playcount]
398 def find_album(m, params)
399 album = get_album(params[:artist].to_s, params[:album].to_s)
401 m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
404 year = "(#{album[2]}) " unless album[2] == nil
405 m.reply _("the album \"%{a}\" by %{r} %{y}has been played %{c} times") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
408 def set_user(m, params)
409 user = params[:who].to_s
411 @registry[ nick ] = user
412 m.reply _("okay, I'll remember that %{n} is %{u} on last.fm") % {:n => nick, :u => user}
415 def set_verb(m, params)
416 past = params[:past].to_s
417 present = params[:present].to_s
418 key = "#{m.sourcenick}_verb_"
419 @registry[ "#{key}past" ] = past
420 @registry[ "#{key}present" ] = present
421 m.reply _("okay, I'll remember that %{n} prefers \"%{r}\" and \"%{p}\"") % {:n => m.sourcenick, :p => past, :r => present}
424 def get_user(m, params)
427 nick = params[:who].to_s
431 if @registry.has_key? nick
432 user = @registry[ nick ]
433 m.reply _("%{nick} is %{user} on last.fm") % {
438 m.reply _("sorry, I don't know who %{n} is on last.fm, perhaps they need to: lastfm set user <username>") % {:n => nick}
442 def lastfm(m, params)
443 action = case params[:action]
444 when "neighbors" then "neighbours"
445 when "recentracks", "recent" then "recenttracks"
446 when "loved" then "lovedtracks"
447 when /^weekly(track|album|artist)s$/
450 find_events(m, params)
457 num = params[:num] || @bot.config['lastfm.default_shouts']
458 num = num.to_i.clip(1, @bot.config['lastfm.max_shouts'])
460 num = params[:num] || @bot.config['lastfm.default_user_data']
461 num = num.to_i.clip(1, @bot.config['lastfm.max_user_data'])
464 user = resolve_username(m, params[:user])
465 uri = "#{APIURL}method=user.get#{action}&user=#{CGI.escape user}"
467 if period = params[:period]
468 period_uri = (period.last == "year" ? "12month" : period.first + "month")
469 uri << "&period=#{period_uri}"
473 res = @bot.httputil.get_response(uri)
474 raise _("no response body") unless res.body
475 rescue Exception => e
476 m.reply _("I had problems accessing last.fm: %{e}") % {:e => e.message}
479 doc = Document.new(res.body)
481 m.reply _("last.fm parsing failed")
486 when Net::HTTPBadRequest
487 if doc.root and doc.root.attributes["status"] == "failed"
488 m.reply "error: " << doc.root.elements["error"].text.downcase
493 seemore = _("; see %{uri} for more")
496 friends = doc.root.get_elements("friends/user").map do |u|
497 u.elements["name"].text
501 reply = _("%{user} has no friends :(")
502 elsif friends.length <= num
503 reply = _("%{user} has %{total} friends: %{friends}")
505 reply = _("%{user} has %{total} friends, including %{friends}")
510 :total => friends.size,
511 :friends => friends.shuffle[0, num].join(", "),
512 :uri => "http://www.last.fm/user/#{CGI.escape user}/friends"
515 loved = doc.root.get_elements("lovedtracks/track").map do |track|
516 [track.elements["artist/name"].text, track.elements["name"].text].join(" - ")
518 loved_prep = loved.shuffle[0, num].to_enum(:each_with_index).collect { |e,i| (i % 2).zero? ? Underline+e+Underline : e }
521 reply = _("%{user} has not loved any tracks")
522 elsif loved.length <= num
523 reply = _("%{user} has loved %{total} tracks: %{tracks}")
525 reply = _("%{user} has loved %{total} tracks, including %{tracks}")
530 :total => loved.size,
531 :tracks => loved_prep.join(", "),
532 :uri => "http://www.last.fm/user/#{CGI.escape user}/library/loved"
535 nbrs = doc.root.get_elements("neighbours/user").map do |u|
536 u.elements["name"].text
540 reply = _("no one seems to share %{user}'s musical taste")
541 elsif nbrs.length <= num
542 reply = _("%{user} musical neighbours are %{nbrs}")
544 reply = _("%{user} musical neighbours include %{nbrs}")
549 :nbrs => nbrs.shuffle[0, num].join(", "),
550 :uri => "http://www.last.fm/user/#{CGI.escape user}/neighbours"
553 tracks = doc.root.get_elements("recenttracks/track").map do |track|
554 [track.elements["artist"].text, track.elements["name"].text].join(" - ")
556 tracks_prep = tracks[0, num].to_enum(:each_with_index).collect { |e,i| (i % 2).zero? ? Underline+e+Underline : e }
559 m.reply _("%{user} hasn't played anything recently") % { :user => user }
561 m.reply _("%{user} has recently played %{tracks}") %
562 { :user => user, :tracks => tracks_prep.join(", ") }
565 shouts = doc.root.get_elements("shouts/shout")
567 m.reply _("there are no shouts for %{user}") % { :user => user }
569 shouts[0, num].each do |shout|
570 m.reply _("<%{author}> %{body}") % {
571 :body => shout.elements["body"].text,
572 :author => shout.elements["author"].text,
576 when :toptracks, :topalbums, :topartists, :weeklytrackchart, :weeklyalbumchart, :weeklyartistchart
577 type = action.to_s.scan(/track|album|artist/).to_s
578 items = doc.root.get_elements("#{action}/#{type}").map do |item|
580 when :weeklytrackchart, :weeklyalbumchart
581 format = "%{artist} - %{title} (%{bold}%{plays}%{bold})"
582 artist = item.elements["artist"].text
583 when :weeklyartistchart, :topartists
584 format = "%{artist} (%{bold}%{plays}%{bold})"
585 artist = item.elements["name"].text
586 when :toptracks, :topalbums
587 format = "%{artist} - %{title} (%{bold}%{plays}%{bold})"
588 artist = item.elements["artist/name"].text
593 :title => item.elements["name"].text,
594 :plays => item.elements["playcount"].text,
599 m.reply _("%{user} hasn't played anything in this period of time") % { :user => user }
601 m.reply items[0, num].join(", ")
606 def resolve_username(m, name)
607 name = m.sourcenick if name.nil?
608 @registry[name] or name
612 plugin = LastFmPlugin.new
613 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
614 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
615 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
616 plugin.map 'lastfm artist *artist', :action => :find_artist, :thread => true
617 plugin.map 'lastfm album *album [by *artist]', :action => :find_album
618 plugin.map 'lastfm track *track', :action => :find_track, :thread => true
619 plugin.map 'lastfm set user[name] :who', :action => :set_user, :thread => true
620 plugin.map 'lastfm set verb *present, *past', :action => :set_verb, :thread => true
621 plugin.map 'lastfm who [:who]', :action => :get_user, :thread => true
622 plugin.map 'lastfm compare to :user2', :action => :tasteometer, :thread => true
623 plugin.map 'lastfm compare [:user1] [to] :user2', :action => :tasteometer, :thread => true
624 plugin.map "lastfm [user] [:num] :action [:user]", :thread => true,
626 :action => /^(?:events|shouts|friends|neighbou?rs|loved(?:tracks)?|recent(?:t?racks)?|top(?:album|artist|track)s?|weekly(?:albums?|artists?|tracks?)(?:chart)?)$/,
629 plugin.map 'lastfm [user] [:num] :action [:user] over [*period]', :thread => true,
631 :action => /^(?:top(?:album|artist|track)s?)$/,
632 :period => /^(?:(?:3|6|12) months)|(?:a\s|1\s)?year$/,
635 plugin.map 'lastfm [now] [:who]', :action => :now_playing, :thread => true
636 plugin.map 'np [:who]', :action => :now_playing, :thread => true