]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/urban.rb
Urban dictionary plugin, contributed by eean (#105)
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / urban.rb
1 require 'cgi'
2 require 'rubyful_soup'
3 require 'uri/common'
4
5 class UrbanPlugin < Plugin
6
7   def help( plugin, topic="")
8     "~urban [word] [n]. Give the [n]th definition of [word] from urbandictionary.com."
9   end
10
11   def privmsg( m )
12
13     unless(m.params && m.params.length > 0)
14       m.reply "incorrect usage: " + help(m.plugin)
15       return
16     end
17
18     paramArray = m.params.split(' ')
19     definitionN = 0
20     if m.params == 'random' then
21       uri = URI.parse( "http://www.urbandictionary.com/random.php" )
22     else 
23       if( paramArray.last.to_i != 0 ) then
24         definitionN = paramArray.last.to_i - 1
25         query = m.params.chomp( paramArray.last )
26         query.rstrip!
27       else
28         query = m.params
29       end
30       uri = URI.parse( "http://www.urbandictionary.com/define.php?term=#{ URI.escape query}" )
31     end
32
33     soup = BeautifulSoup.new( @bot.httputil.get( uri ) )
34     if titleNavi = soup.find_all( 'td', :attrs => { 'class' => 'def_word' } )[0] then
35       title = titleNavi.contents
36       results = soup.find_all( 'div', :attrs => { 'class' => 'def_p' } )
37       debug PP.pp(results,'')
38       output = Array.new
39       if results[definitionN] then
40         results[definitionN].p.contents.each { |s| output.push( strip_tags( s.to_s ) ) }
41         m.reply "\002#{title}\002 - #{output}"
42       else
43         m.reply "#{query} does not have #{definitionN + 1} definitions."
44       end
45     else
46       m.reply "#{m.params} not found."
47     end
48
49   end
50
51   def strip_tags(html)
52     html.gsub(/<.+?>/,'').
53     gsub(/&amp;/,'&').
54     gsub(/&quot;/,'"').
55     gsub(/&lt;/,'<').
56     gsub(/&gt;/,'>').
57     gsub(/&ellip;/,'...').
58     gsub(/&apos;/, "'").
59     gsub("\n",'')
60   end
61 end
62
63 plugin = UrbanPlugin.new
64 plugin.register( "urban" )