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)
21 notfound = s.match %r{<div style="color: #669FCE"><i>.*?</i> isn't defined}
23 numpages = s[%r{<div id='paginator'>.*?</div>}m].scan(/\d+/).collect {|x| x.to_i}.max || 1
26 s.scan(%r{<td class='index'[^>]*>.*?(\d+)\..*?</td>.*?<td class='word'>(?:<a.*?>)?([^>]+)(?:</a>)?</td>.*?<div class='definition'>(.+?)</div>.*?<div class='example'>(.+?)</div>}m) do |num, wrd, desc, ex|
27 rv << [num.to_i, wrd.strip, desc.strip, ex.strip]
30 maxnum = rv.collect {|x| x[0]}.max || 0
31 return m.reply("#{Bold}#{word}#{Bold} not found") if rv.empty?
34 suggestions = rv.map { |s| Underline + s[1] + Underline }.uniq.join ', '
35 m.reply "#{Bold}#{word}#{Bold} not found. maybe you mean #{suggestions}?"
39 answer = rv.find { |a| a[0] == n }
40 answer ||= (n > maxnum ? rv.last : rv.first)
41 m.reply format_definition((p == numpages ? maxnum : "#{(numpages-1)*7 + 1}+"), *answer)
45 words = params[:words].to_s
47 resp = @bot.httputil.head('http://www.urbandictionary.com/random.php',
50 if resp.code == "302" && (loc = resp['location'])
51 words = URI.unescape(loc.match(/define.php\?term=(.*)$/)[1]) rescue nil
54 get_def(m, words, params[:n])
58 home = @bot.httputil.get("http://www.urbandictionary.com/daily.php")
60 m.reply "Couldn't get the urban dictionary word of the day"
63 home.match(%r{href="/define.php\?term=.*?">(.*?)<})
65 debug "Urban word of the day: #{wotd}"
67 m.reply "Couldn't get the urban dictionary word of the day"
74 plugin = UrbanPlugin.new
75 plugin.map "urban *words :n", :requirements => { :n => /^-?\d+$/ }, :action => 'urban'
76 plugin.map "urban [*words]", :action => 'urban'
77 plugin.map "urbanday", :action => 'uotd'