]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/shortenurls.rb
shortenurls plugin, merging tinyurl and rubyurl and adding access to most of ShortURL...
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / shortenurls.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # Plugin to handle ShortURL, merges the funcionality of the old rubyurl and tinyurl plugins
5 # Note that it's called ShortenURLs and not ShortURL, to prevent conflicts with
6 # the actual ruby package used
7 #
8 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
9 # (C) 2007 Giuseppe Bilotta
10 # Based on existing rbot plugins, as mentioned above :)
11
12 require "shorturl"
13 require "uri"
14
15 class ShortenURLs < Plugin
16   include WWW
17
18   attr_accessor :services
19   def initialize
20     super
21     # Instead of catering for all the services, we only pick the ones with 'link' or 'url' in the name
22     @services = ShortURL.valid_services.select { |service| service.to_s =~ /(?:link|url)/ } << :shorturl
23   end
24
25   # return a help string when the bot is asked for help on this plugin
26   def help(plugin, topic="")
27     return "shorten urls. syntax: <service> <your long url> => creates a shortened url using the required service (choose between #{@services.join(', ')}). Example: #{@bot.nick}, tinyurl http://some.long.url/wow-this-is/really-long.html"
28   end
29
30   # do the dirty job. This method can be called by other plugins, in which case you
31   # should set the :called param to true
32   def shorten(m, params)
33     url = params[:url]
34     if url == "help"
35       m.reply help(m.plugin) unless params[:called]
36       return
37     end
38     begin
39       to_uri = URI.parse(url)
40       # We don't accept 'generic' URLs because almost everything gets in there
41       raise URI::InvalidURIError if to_uri.class == URI::Generic
42     rescue URI::InvalidURIError
43       m.reply "#{url} doesn't look like an URL to me ..." unless params[:called]
44       return
45     end
46
47     service = params[:service] || m.plugin.to_sym
48     service = :rubyurl if service == :shorturl
49
50     short = WWW::ShortURL.shorten(url, service)
51
52     if params[:called]
53       return short
54     else
55       m.reply "#{url} shortened to #{short}"
56     end
57   end
58
59 end
60
61 # create an instance of the RubyURL class and register it as a plugin
62 plugin = ShortenURLs.new
63
64 plugin.services.each { |service|
65   plugin.map "#{service} :url", :action => 'shorten'
66 }