1 class UrbanPlugin < Plugin
2 URBAN = 'http://www.urbandictionary.com/define.php?term='
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"
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)
14 def get_def(m, word, n = nil)
17 u = URBAN + URI.escape(word)
18 u += '&page=' + p.to_s if p > 1
19 s = @bot.httputil.get(u)
20 return m.reply("Couldn't get the urban dictionary definition for #{word}") if s.nil?
22 notfound = s.match %r{<i>.*?</i> isn't defined}
24 numpages = if s[%r{<ul class="pagination[^"]+">.*?</ul>}m]
25 $&.scan(/>(\d+)</).collect {|x| x[0].to_i}.max || 1
30 s.scan(%r{<a class="word"[^>]* href="\/define[^>]*>([^<]+)</a>.*?<div class='meaning'>(.+?)</div>.*?<div class='example'>(.+?)</div>}m) do |wrd, desc, ex|
31 rv << [num, wrd.strip, desc.strip, ex.strip]
35 maxnum = rv.collect {|x| x[0]}.max || 0
36 return m.reply("#{Bold}#{word}#{Bold} not found") if rv.empty?
39 suggestions = rv.map { |str| Underline + str[1] + Underline }.uniq.join ', '
40 m.reply "#{Bold}#{word}#{Bold} not found. maybe you mean #{suggestions}?"
44 answer = rv.find { |a| a[0] == n }
45 answer ||= (n > maxnum ? rv.last : rv.first)
46 m.reply format_definition((p == numpages ? maxnum : "#{(numpages-1)*7 + 1}+"), *answer)
50 words = params[:words].to_s
52 resp = @bot.httputil.head('http://www.urbandictionary.com/random.php',
55 return m.reply("Couldn't get a random urban dictionary word") if resp.nil?
56 if resp.code == "302" && (loc = resp['location'])
57 words = URI.unescape(loc.match(/define.php\?term=(.*)$/)[1]) rescue nil
60 get_def(m, words, params[:n])
64 home = @bot.httputil.get("http://www.urbandictionary.com/daily.php")
66 m.reply "Couldn't get the urban dictionary word of the day"
69 home.match(%r{href="/define.php\?term=.*?">(.*?)<})
71 debug "Urban word of the day: #{wotd}"
73 m.reply "Couldn't get the urban dictionary word of the day"
80 plugin = UrbanPlugin.new
81 plugin.map "urban *words :n", :requirements => { :n => /^-?\d+$/ }, :action => 'urban'
82 plugin.map "urban [*words]", :action => 'urban'
83 plugin.map "urbanday", :action => 'uotd'