Skip to content

Instantly share code, notes, and snippets.

@Pistos
Created May 21, 2011 02:45
Show Gist options
  • Select an option

  • Save Pistos/984182 to your computer and use it in GitHub Desktop.

Select an option

Save Pistos/984182 to your computer and use it in GitHub Desktop.
require 'cgi'
require 'open-uri'
module Mathetes; module Plugins
class Google
MAX_RESULTS = 5
def initialize( mathetes )
$stderr.puts "Loading Google plugin..."
mathetes.hook_privmsg( :regexp => /^!g(oogle)?\b/ ) do |message|
$stderr.puts "!g triggered"
args = message.text[ /^\S+\s+(.*)/, 1 ]
nick = message.from.nick
num_results = 1
args_array = args.split( /\s+/ )
if args_array.length < 1
message.answer "!google [number of results] <search terms>"
return
end
if args_array[ 0 ].to_i.to_s == args_array[ 0 ]
$stderr.puts "1" * 80
# A number of results has been specified
num_results = args_array[ 0 ].to_i
if num_results > MAX_RESULTS
num_results = MAX_RESULTS
end
arg = args_array[ 1..-1 ].join( "+" )
unescaped_arg = args_array[ 1..-1 ].join( " " )
else
$stderr.puts "2" * 80
arg = args_array.join( "+" )
unescaped_arg = args_array.join( " " )
end
arg = CGI.escape( arg )
$stderr.puts "Hitting google...."
open( "http://www.google.com/search?q=#{ CGI.escape( args ) }&safe=active" ) do |html|
counter = 0
$stderr.puts "parsing..."
html.read.scan /<a href="?([^"]+)" class=l.*?>(.+?)<\/a>/m do |match|
$stderr.puts "Found match: #{match.inspect}"
url, title = match
title.gsub!( /<.+?>/, "" )
ua = unescaped_arg.gsub( /-?site:\S+/, '' ).strip
$stderr.puts "Responding to #{message.inspect}..."
message.answer "[#{ua}]: #{url} - #{title}"
counter += 1
break if counter >= num_results
end
$stderr.puts "... parsing complete"
if counter == 0
message.answer "(no results)"
end
end
$stderr.puts "end of privmsg hook"
end
end
end
end; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment