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