Skip to content

Instantly share code, notes, and snippets.

@Sutto
Created February 13, 2009 02:42
Show Gist options
  • Save Sutto/63008 to your computer and use it in GitHub Desktop.
Save Sutto/63008 to your computer and use it in GitHub Desktop.
require 'uri'
require 'net/http'
require 'xmlsimple'
# A Nice wikipedia blabber extension for your amusement
module MatzBot::Commands
# eh?
# needs_gem 'xml-simple' => ['lookup_request']
# gem 'xml-simple'
hide_methods :lookup_request
# These are ugly, we need a unified configuration system...
WIKI_REJECTS = ['a','is','are','the','fuck','you']
WIKI_RANDOM = ['Who the hell knows anyway?', 'I bet someone here knows...', 'why dont you go look it up?', 'hrmm... thats a good question..', 'nfi man..']
WIKI_PATH = "/w/api.php?action=opensearch&format=xml&search="
RANDOM_SPEECH_FACTOR = 1 # 1 in X times he will respond.
# Clean up the data array for processing
def lookup_request(data)
return unless rand(RANDOM_SPEECH_FACTOR) == 0
data.reject!{|t| WIKI_REJECTS.include?(t)}
wiki_lookup(data.join(' '))
end
private
# Do the actual lookup for the request string
def wiki_lookup(request_string)
query = request_string.split(/[^\w\s]+/).first
result = Net::HTTP.start('en.wikipedia.org', 80) {|http|
http.get(WIKI_PATH + URI.encode(query).to_s)
}
process_result(result.body)
rescue => e
# Say something smart-assed
logger.debug(e)
puts WIKI_RANDOM[rand(WIKI_RANDOM.size)]
end
# extracts information from the XML
def process_result(raw)
xml = XmlSimple.xml_in(raw)
section = 0
item_count = xml['Section'][0]['Item'].size
say xml['Section'][0]['Item'][rand(item_count)]['Description']
end
public
# Speak wikipedia evil, but respond to it generously.
alias_method :what, :lookup_request
alias_method :who, :lookup_request
alias_method :when, :lookup_request
alias_method :how, :lookup_request
alias_method :are, :lookup_request
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment