PageRenderTime 52ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/data/rbot/plugins/search.rb

https://github.com/Oblomov/rbot
Ruby | 413 lines | 332 code | 52 blank | 29 comment | 45 complexity | 1d5b6c6866b66e456174cae344b13797 MD5 | raw file
  1. #-- vim:sw=2:et
  2. #++
  3. #
  4. # :title: Google and Wikipedia search plugin for rbot
  5. #
  6. # Author:: Tom Gilbert (giblet) <tom@linuxbrit.co.uk>
  7. # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
  8. #
  9. # Copyright:: (C) 2002-2005 Tom Gilbert
  10. # Copyright:: (C) 2006 Tom Gilbert, Giuseppe Bilotta
  11. # Copyright:: (C) 2006-2007 Giuseppe Bilotta
  12. # TODO:: use lr=lang_<code> or whatever is most appropriate to let google know
  13. # it shouldn't use the bot's location to find the preferred language
  14. # TODO:: support localized uncyclopedias -- not easy because they have different names
  15. # for most languages
  16. GOOGLE_SEARCH = "https://www.google.com/search?hl=en&oe=UTF-8&ie=UTF-8&gbv=1&q="
  17. GOOGLE_WAP_SEARCH = "https://www.google.com/m/search?hl=en&ie=UTF-8&gbv=1&q="
  18. GOOGLE_WAP_LINK = /<a\s+href="\/url\?(q=[^"]+)"[^>]*>\s*<div[^>]*>(.*?)\s*<\/div>/im
  19. GOOGLE_CALC_RESULT = />Calculator<\/span>(?:<\/?[^>]+>\s*)+([^<]+)/
  20. GOOGLE_XPATH_DEF = "//img[@id='flex_text_audio_icon_chunk']/../../../../div[3]//text()"
  21. DDG_API_SEARCH = "http://api.duckduckgo.com/?format=xml&no_html=1&skip_disambig=1&no_redirect=0&q="
  22. WOLFRAM_API_SEARCH = "http://api.wolframalpha.com/v2/query?input=%{terms}&appid=%{key}&format=plaintext" +
  23. "&scantimeout=3.0&podtimeout=4.0&formattimeout=8.0&parsetimeout=5.0" +
  24. "&excludepodid=SeriesRepresentations:*"
  25. WOLFRAM_API_KEY = "9RW6XR-QTL2JT7J4W"
  26. class SearchPlugin < Plugin
  27. Config.register Config::IntegerValue.new('duckduckgo.hits',
  28. :default => 3, :validate => Proc.new{|v| v > 0},
  29. :desc => "Number of hits to return from searches")
  30. Config.register Config::IntegerValue.new('duckduckgo.first_par',
  31. :default => 0,
  32. :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
  33. Config.register Config::IntegerValue.new('google.hits',
  34. :default => 3,
  35. :desc => "Number of hits to return from Google searches")
  36. Config.register Config::IntegerValue.new('google.first_par',
  37. :default => 0,
  38. :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
  39. Config.register Config::IntegerValue.new('wikipedia.hits',
  40. :default => 3,
  41. :desc => "Number of hits to return from Wikipedia searches")
  42. Config.register Config::IntegerValue.new('wikipedia.first_par',
  43. :default => 1,
  44. :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
  45. def help(plugin, topic="")
  46. case topic
  47. when "ddg"
  48. "Use '#{topic} <string>' to return a search or calculation from " +
  49. "DuckDuckGo. Use #{topic} define <string> to return a definition."
  50. when "search", "google"
  51. "#{topic} <string> => search google for <string>"
  52. when "gcalc"
  53. "gcalc <equation> => use the google calculator to find the answer to <equation>"
  54. when "gdef"
  55. "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
  56. when "wa"
  57. "wa <string> => searches WolframAlpha for <string>"
  58. when "wp"
  59. "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
  60. when "unpedia"
  61. "unpedia <string> => search for <string> on Uncyclopedia"
  62. else
  63. "search <string> (or: google <string>) => search google for <string> | ddg <string> to search DuckDuckGo | wp <string> => search for <string> on Wikipedia | wa <string> => search for <string> on WolframAlpha | unpedia <string> => search for <string> on Uncyclopedia"
  64. end
  65. end
  66. def duckduckgo(m, params)
  67. what = params[:words].to_s
  68. terms = CGI.escape what
  69. url = DDG_API_SEARCH + terms
  70. hits = @bot.config['duckduckgo.hits']
  71. first_pars = params[:firstpar] || @bot.config['duckduckgo.first_par']
  72. single = params[:lucky] || (hits == 1 and first_pars == 1)
  73. begin
  74. feed = @bot.httputil.get(url)
  75. raise unless feed
  76. rescue => e
  77. m.reply "error duckduckgoing for #{what}"
  78. return
  79. end
  80. xml = REXML::Document.new feed
  81. heading = xml.elements['//Heading/text()'].to_s
  82. # answer is returned for calculations
  83. answer = xml.elements['//Answer/text()'].to_s
  84. # abstract is returned for definitions etc
  85. abstract = xml.elements['//AbstractText/text()'].to_s
  86. abfrom = ""
  87. unless abstract.empty?
  88. absrc = xml.elements['//AbstractSource/text()'].to_s
  89. aburl = xml.elements['//AbstractURL/text()'].to_s
  90. unless absrc.empty? and aburl.empty?
  91. abfrom = " --"
  92. abfrom << " " << absrc unless absrc.empty?
  93. abfrom << " " << aburl unless aburl.empty?
  94. end
  95. end
  96. # but also definition (yes, you can have both, see e.g. printf)
  97. definition = xml.elements['//Definition/text()'].to_s
  98. deffrom = ""
  99. unless definition.empty?
  100. defsrc = xml.elements['//Definition/@source/text()'].to_s
  101. defurl = xml.elements['//Definition/@url/text()'].to_s
  102. unless defsrc.empty? and defurl.empty?
  103. deffrom = " --"
  104. deffrom << " " << defsrc unless defsrc.empty?
  105. deffrom << " " << defurl unless defurl.empty?
  106. end
  107. end
  108. if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
  109. m.reply "no results"
  110. return
  111. end
  112. # if we got a one-shot answer (e.g. a calculation, return it)
  113. unless answer.empty?
  114. m.reply answer
  115. return
  116. end
  117. # otherwise, return the abstract, followed by as many hits as found
  118. unless heading.empty? or abstract.empty?
  119. m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
  120. :bold => Bold, :heading => heading,
  121. :abstract => abstract, :abfrom => abfrom
  122. }
  123. end
  124. unless heading.empty? or definition.empty?
  125. m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
  126. :bold => Bold, :heading => heading,
  127. :abstract => definition, :abfrom => deffrom
  128. }
  129. end
  130. # return zeroclick search results
  131. links, texts = [], []
  132. xml.elements.each("//Results/Result/FirstURL") { |element|
  133. links << element.text
  134. break if links.size == hits
  135. }
  136. return if links.empty?
  137. xml.elements.each("//Results/Result/Text") { |element|
  138. texts << " #{element.text}"
  139. break if links.size == hits
  140. }
  141. # TODO see treatment of `single` in google search
  142. single ||= (links.length == 1)
  143. pretty = []
  144. links.each_with_index do |u, i|
  145. t = texts[i]
  146. pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
  147. :n => (single ? "" : "#{i}. "),
  148. :sep => (single ? " -- " : ": "),
  149. :b => Bold, :t => t, :u => u
  150. })
  151. end
  152. result_string = pretty.join(" | ")
  153. # If we return a single, full result, change the output to a more compact representation
  154. if single
  155. fp = first_pars > 0 ? " -- #{Utils.get_first_pars(@bot, links, first_pars)}" : ""
  156. m.reply("Result for %{what}: %{string}%{fp}" % {
  157. :what => what, :string => result_string, :fp => fp
  158. }, :overlong => :truncate)
  159. return
  160. end
  161. m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
  162. return unless first_pars > 0
  163. Utils.get_first_pars(@bot, urls, first_pars, :message => m)
  164. end
  165. def google(m, params)
  166. what = params[:words].to_s
  167. if what.match(/^define:/)
  168. return google_define(m, what, params)
  169. end
  170. searchfor = CGI.escape what
  171. # This method is also called by other methods to restrict searching to some sites
  172. if params[:site]
  173. site = "site:#{params[:site]}+"
  174. else
  175. site = ""
  176. end
  177. # It is also possible to choose a filter to remove constant parts from the titles
  178. # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
  179. filter = params[:filter] || ""
  180. url = GOOGLE_WAP_SEARCH + site + searchfor
  181. hits = params[:hits] || @bot.config['google.hits']
  182. hits = 1 if params[:lucky]
  183. first_pars = params[:firstpar] || @bot.config['google.first_par']
  184. single = params[:lucky] || (hits == 1 and first_pars == 1)
  185. begin
  186. wml = @bot.httputil.get(url)
  187. raise unless wml
  188. rescue => e
  189. m.reply "error googling for #{what}"
  190. return
  191. end
  192. results = wml.scan(GOOGLE_WAP_LINK)
  193. if results.length == 0
  194. m.reply "no results found for #{what}"
  195. return
  196. end
  197. results = results.map {|result|
  198. url = CGI::parse(Utils.decode_html_entities(result[0]))['q'].first
  199. title = Utils.decode_html_entities(result[1].gsub(/<\/?[^>]+>/, ''))
  200. [url, title] unless url.empty? or title.empty?
  201. }.reject {|item| not item}[0..hits]
  202. result_string = results.map {|url, title| "#{Bold}#{title}#{NormalText}: #{url}"}
  203. if params[:lucky]
  204. m.reply result_string.first
  205. Utils.get_first_pars(@bot, [results.map {|url, title| url}.first], first_pars, :message => m)
  206. return
  207. end
  208. m.reply "Results for #{what}: #{result_string.join(' | ')}", :split_at => /\s+\|\s+/
  209. return unless first_pars > 0
  210. Utils.get_first_pars(@bot, results.map {|url, title| url}, first_pars, :message => m)
  211. end
  212. def google_define(m, what, params)
  213. begin
  214. wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
  215. raise unless wml
  216. rescue => e
  217. m.reply "error googling for #{what}"
  218. return
  219. end
  220. begin
  221. related_index = wml.index(/Related phrases:/, 0)
  222. raise unless related_index
  223. defs_index = wml.index(/Definitions of <b>/, related_index)
  224. raise unless defs_index
  225. defs_end = wml.index(/<input/, defs_index)
  226. raise unless defs_end
  227. rescue => e
  228. m.reply "no results found for #{what}"
  229. return
  230. end
  231. related = wml[related_index...defs_index]
  232. defs = wml[defs_index...defs_end]
  233. m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
  234. end
  235. def lucky(m, params)
  236. params.merge!(:lucky => true)
  237. google(m, params)
  238. end
  239. def gcalc(m, params)
  240. what = params[:words].to_s
  241. searchfor = CGI.escape(what)
  242. debug "Getting gcalc thing: #{searchfor.inspect}"
  243. url = GOOGLE_WAP_SEARCH + searchfor
  244. begin
  245. html = @bot.httputil.get(url)
  246. rescue => e
  247. m.reply "error googlecalcing #{what}"
  248. return
  249. end
  250. debug "#{html.size} bytes of html recieved"
  251. debug html
  252. candidates = html.match(GOOGLE_CALC_RESULT)
  253. debug "candidates: #{candidates.inspect}"
  254. if candidates.nil?
  255. m.reply "couldn't calculate #{what}"
  256. return
  257. end
  258. result = candidates[1].remove_nonascii
  259. debug "replying with: #{result.inspect}"
  260. m.reply result.ircify_html
  261. end
  262. def gdef(m, params)
  263. what = params[:words].to_s
  264. searchfor = CGI.escape("define " + what)
  265. debug "Getting gdef thing: #{searchfor.inspect}"
  266. url = GOOGLE_WAP_SEARCH + searchfor
  267. begin
  268. resp = @bot.httputil.get(url, resp: true)
  269. rescue => e
  270. m.reply "error googledefining #{what}"
  271. return
  272. end
  273. results = resp.xpath(GOOGLE_XPATH_DEF).map(&:content)
  274. if results.empty?
  275. m.reply "couldn't find a definition for #{what} on Google"
  276. else
  277. m.reply "#{results.first} -- #{results[1..-1].join(' ')}"
  278. end
  279. end
  280. def wolfram(m, params)
  281. what = params[:words].to_s
  282. terms = CGI.escape what
  283. url = WOLFRAM_API_SEARCH % {
  284. :terms => terms, :key => WOLFRAM_API_KEY
  285. }
  286. begin
  287. feed = @bot.httputil.get(url)
  288. raise unless feed
  289. rescue => e
  290. m.reply "error asking WolframAlfa about #{what}"
  291. return
  292. end
  293. debug feed
  294. xml = REXML::Document.new feed
  295. if xml.elements['/queryresult'].attributes['error'] == "true"
  296. m.reply xml.elements['/queryresult/error/text()'].to_s
  297. return
  298. end
  299. unless xml.elements['/queryresult'].attributes['success'] == "true"
  300. m.reply "no data available"
  301. return
  302. end
  303. answer_type, answer = [], []
  304. xml.elements.each("//pod") { |element|
  305. answer_type << element.attributes['title']
  306. answer << element.elements['subpod/plaintext'].text
  307. }
  308. # find the first answer that isn't nil,
  309. # starting on the second pod in the array
  310. n = 1
  311. answer[1..-1].each { |a|
  312. break unless a.nil?
  313. n += 1
  314. }
  315. if answer[n].nil?
  316. m.reply "no results"
  317. return
  318. end
  319. # strip spaces, pipes, and line breaks
  320. sep = Bold + ' :: ' + Bold
  321. chars = [ [/\n/, sep], [/\t/, " "], [/\s+/, " "], ["|", "-"] ]
  322. chars.each { |c| answer[n].gsub!(c[0], c[1]) }
  323. m.reply answer_type[n] + sep + answer[n]
  324. end
  325. def wikipedia(m, params)
  326. lang = params[:lang]
  327. site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
  328. debug "Looking up things on #{site}"
  329. params[:site] = site
  330. params[:filter] = / - Wikipedia.*$/
  331. params[:hits] = @bot.config['wikipedia.hits']
  332. params[:firstpar] = @bot.config['wikipedia.first_par']
  333. return google(m, params)
  334. end
  335. def unpedia(m, params)
  336. site = "uncyclopedia.org"
  337. debug "Looking up things on #{site}"
  338. params[:site] = site
  339. params[:filter] = / - Uncyclopedia.*$/
  340. params[:hits] = @bot.config['wikipedia.hits']
  341. params[:firstpar] = @bot.config['wikipedia.first_par']
  342. return google(m, params)
  343. end
  344. end
  345. plugin = SearchPlugin.new
  346. plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
  347. plugin.map "search *words", :action => 'google', :threaded => true
  348. plugin.map "google *words", :action => 'google', :threaded => true
  349. plugin.map "lucky *words", :action => 'lucky', :threaded => true
  350. plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
  351. plugin.map "gdef *words", :action => 'gdef', :threaded => true
  352. plugin.map "wa *words", :action => 'wolfram', :threaded => true
  353. plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
  354. plugin.map "wp *words", :action => 'wikipedia', :threaded => true
  355. plugin.map "unpedia *words", :action => 'unpedia', :threaded => true