]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
Clean up logging from the plugins
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / imdb.rb
1 # IMDB plugin for RubyBot
2 # (c) 2005 Arnaud Cornet <arnaud.cornet@gmail.com>
3 # Licensed under MIT License.
4
5 require 'net/http'
6 require 'cgi'
7 require 'uri/common'
8
9 class Imdb
10   def initialize(bot)
11     @bot = bot
12   end
13
14   def search(rawstr)
15     str = URI.escape(rawstr)
16     @http = @bot.httputil.get_proxy(URI.parse("http://us.imdb.com/find?q=#{str}"))
17     @http.start
18     begin
19     resp, data = @http.get("/find?q=#{str}", "User-Agent" => "Mozilla/5.0")
20     rescue Net::ProtoRetriableError => detail
21       head = detail.data
22       if head.code == "301" or head.code == "302"
23             return head['location'].gsub(/http:\/\/us.imdb.com/, "").gsub(/\?.*/, "")
24         end
25     end
26     if resp.code == "200"
27       m = /<a href="(\/title\/tt[0-9]+\/?)[^"]*"(:?[^>]*)>([^<]*)<\/a>/.match(resp.body)
28       if m
29         url = m[1]
30         title = m[2]
31         return url
32       end
33     elsif resp.code == "302"
34       return resp['location'].gsub(/http:\/\/us.imdb.com/, "").gsub(/\?.*/, "")
35     end
36     return nil
37   end
38
39   def info(rawstr)
40     sr = search(rawstr)
41     if !sr
42       debug "IMDB: search returned NIL"
43       return nil
44     end
45     resp, data = @http.get(sr, "User-Agent" =>
46       "Mozilla/5.0 (compatible; Konqueror/3.1; Linux)")
47     if resp.code == "200"
48       m = /<title>([^<]*)<\/title>/.match(resp.body)
49       return nil if !m
50       title = CGI.unescapeHTML(m[1])
51
52       m = /<b>([0-9.]+)\/10<\/b> \(([0-9,]+) votes?\)/.match(resp.body)
53       return nil if !m
54       score = m[1]
55       votes = m[2]
56
57       genre = Array.new
58       resp.body.scan(/<a href="\/Sections\/Genres\/[^\/]+\/">([^<]+)<\/a>/) do |gnr|
59         genre << gnr
60       end
61       return ["http://us.imdb.com" + sr, title, score, votes,
62         genre]
63     end
64     return nil
65   end
66 end
67
68 class ImdbPlugin < Plugin
69   def help(plugin, topic="")
70     "imdb <string> => search http://www.imdb.org for <string>"
71   end
72
73   def privmsg(m)
74     unless(m.params && m.params.length > 0)
75       m.reply "incorrect usage: " + help(m.plugin)
76       return
77     end
78
79     i = Imdb.new(@bot)
80     info = i.info(m.params)
81     if !info
82       m.reply "Nothing found for #{m.params}"
83       return nil
84     end
85     m.reply "#{info[1]} : #{info[0]}"
86     m.reply "Ratings: #{info[2]}/10 (#{info[3]} voters). Genre: #{info[4].join('/')}"
87   end
88 end
89
90 plugin = ImdbPlugin.new
91 plugin.register("imdb")
92