lastfm plugin: added now playing info to the help
[rbot] / data / rbot / plugins / urban.rb
1 class UrbanPlugin < Plugin
2   URBAN = 'http://www.urbandictionary.com/define.php?term='
3
4   def help( plugin, topic="")
5     "urban [word] [n]: give the [n]th definition of [word] from urbandictionary.com. urbanday: give the word-of-the-day at urban"
6   end
7
8   def format_definition(total, num, word, desc, ex)
9     "#{Bold}#{word} (#{num}/#{total})#{Bold}: " +
10     desc.ircify_html(:limit => 300) + " " +
11     "<i>#{ex}</i>".ircify_html(:limit => 100)
12   end
13
14   def get_def(m, word, n = nil)
15     n = n ? n.to_i : 1
16     u = URBAN + URI.escape(word)
17     u += '&skip=' + n.to_s if n
18     s = @bot.httputil.get(u)
19
20     notfound = s.match %r{<div style="color: #669FCE"><i>.*?</i> isn't defined}
21
22     total = nil
23     if s.sub!(%r{<div class="pager"><b>(\d+)</b>\s*definition.*$}m, '')
24       total = $1.to_i
25     end
26
27     rv = Array.new
28
29     s.scan(%r{<td class="def_number"[^>]*>(\d+)\.</td>.*?<td class="def_word">(?:<a.*?>)?([^>]+)(?:</a>)?</td>.*?<div class="def_p">.*?<p>(.+?)</p>.*?<p style=".*?>(.+?)</p>}m) do |num, wrd, desc, ex|
30       rv << [num.to_i, wrd, desc, ex]
31     end
32
33     total ||= rv.size
34
35     return m.reply("#{Bold}#{word}#{Bold} not found") if rv.empty?
36
37     if notfound
38       suggestions = rv.map { |s| Underline + s[1] + Underline }.uniq.join ', '
39       m.reply "#{Bold}#{word}#{Bold} not found. maybe you mean #{suggestions}?"
40       return
41     end
42
43     answer = rv.find { |a| a[0] == n }
44     answer ||= (n > total ? rv.last : rv.first)
45     m.reply format_definition(total, *answer)
46   end
47
48   def urban(m, params)
49     words = params[:words].to_s
50     if words.empty?
51       resp = @bot.httputil.head('http://www.urbandictionary.com/random.php',
52                                :max_redir => -1,
53                                :cache => false)
54       if resp.code == "302" && (loc = resp['location'])
55         words = URI.unescape(loc.match(/define.php\?term=(.*)$/)[1]) rescue nil
56       end
57     end
58     get_def(m, words, params[:n])
59   end
60
61   def uotd(m, params)
62     home = @bot.httputil.get("http://www.urbandictionary.com/daily.php")
63     if home.nil?
64       m.reply "Couldn't get the urban dictionary word of the day"
65       return
66     end
67     home.match(%r{href="/define.php\?term=.*?">(.*?)<})
68     wotd = $1
69     debug "Urban word of the day: #{wotd}"
70     if !wotd
71       m.reply "Couldn't get the urban dictionary word of the day"
72       return
73     end
74     get_def(m, wotd, 1)
75   end
76 end
77
78 plugin = UrbanPlugin.new
79 plugin.map "urban *words :n", :requirements => { :n => /^-?\d+$/ }, :action => 'urban'
80 plugin.map "urban [*words]", :action => 'urban'
81 plugin.map "urbanday", :action => 'uotd'
82