/lib/rib/modules/search.rb

https://github.com/aibor/rib · Ruby · 90 lines · 61 code · 24 blank · 5 comment · 3 complexity · d97c11c9efd8b108fec52383e5394ca8 MD5 · raw file

  1. # coding: utf-8
  2. require 'resolv'
  3. require 'json'
  4. class RIB::Module::Search < RIB::Module
  5. desc 'Search on Google for the passes string'
  6. def google(*args)
  7. format gsearch(:google, args)
  8. end
  9. alias :g :google
  10. defaults wiki_lang: :en
  11. #desc 'Search on Wikipedia using the DNS API'
  12. desc 'Search on Wikipedia using the Wikipedia API'
  13. def wikipedia(*args)
  14. #dnsrequest(args.join('_') + ".wp.dg.cx",
  15. # %w(208.67.220.220 208.67.222.222 8.8.8.8)).join
  16. #format gsearch(:google, ['site:wikipedia.org'] + args)
  17. res = wikipedia_api(args, 1, bot.config.wiki_lang)
  18. "#{res[2].first} - #{res[3].first}" if res.last.any?
  19. end
  20. alias :w :wikipedia
  21. desc "Search on DuckDuckGo. Jumps to first search
  22. result, unless bang syntax is used. Try '!ddg !bang'"
  23. def duckduckgo(*args)
  24. format gsearch(:ddg, args)
  25. end
  26. alias :ddg :duckduckgo
  27. private
  28. def format(found)
  29. lt = RIB::Module::LinkTitle.new(bot, msg)
  30. title = lt.send(:formattitle, ::HTML.title(found)) rescue ''
  31. "%s: %s\n%s" % [msg.user, found, title]
  32. end
  33. def gsearch(site, keys)
  34. url = case site
  35. when :ddg
  36. keys.first.gsub!(/^[^!]/, '\\\\\&')
  37. 'https://duckduckgo.com/html?q=%s' % keys.join('+')
  38. when :google
  39. "https://www.google.com/search?hl=de&btnI=1&q=" +
  40. "#{keys * '+'}&ie=utf-8&oe=utf-8&pws=0"
  41. end
  42. url = ::URI.escape(url)
  43. 10.times do |i|
  44. uri = ::URI.parse(url)
  45. http = ::Net::HTTP.new(uri.host)
  46. resp = http.request_head(uri.request_uri)
  47. break if url == resp['location'] || resp['location'].nil?
  48. url = resp['location']
  49. end
  50. url
  51. end
  52. WikiApiURL = 'https://%s.wikipedia.org/w/api.php?action=opensearch' +
  53. '&search=%s&format=json&redirects=return&limit=%d'
  54. def wikipedia_api(keys, limit = 1, lang = :en)
  55. url = URI.escape(WikiApiURL % [lang, keys.join('+'), limit])
  56. ::JSON.parse ::Net::HTTP.get(URI(url))
  57. end
  58. def dnsrequest(host, nameserver)
  59. dns = ::Resolv::DNS.new(nameserver: nameserver)
  60. dns.getresource(host, ::Resolv::DNS::Resource::IN::TXT).strings
  61. rescue ::Resolv::ResolvError
  62. ["Can't resolv. Halp!"]
  63. end
  64. end