Skip to content

Instantly share code, notes, and snippets.

@atmos
Created March 12, 2014 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atmos/9516145 to your computer and use it in GitHub Desktop.
Save atmos/9516145 to your computer and use it in GitHub Desktop.
Google Search Completion for Hubot. needs xml2js in your package.json file
# Description
# Hubot, you complete me
#
# Commands:
# hubot complete me - Google Suggest a phrase
XMLJS = require "xml2js"
module.exports = (robot) ->
robot.respond /complete( me)?(?: x(\d+))? (.*)$/i, (msg) ->
number = parseInt(msg.match[2], 10) || 1
phrase = msg.match[3]
msg.http('https://suggestqueries.google.com/complete/search')
.query(q: phrase, output: 'toolbar')
.get() (err, res, body) ->
parser = new XMLJS.Parser(explicitArray: true)
parser.parseString body, (err, result) ->
suggestions = result.toplevel? and result.toplevel.CompleteSuggestion
if suggestions?
suggestions = (x.suggestion[0]['$'].data for x in shuffle(suggestions)[0..number - 1])
(msg.send x for x in suggestions)
else
msg.send "No meatbag has ever searched for \"#{phrase}\""
shuffle = (array) ->
if array.length > 0
i = array.length
until --i == 0
j = Math.floor(Math.random() * (i + 1))
[array[i], array[j]] = [array[j], array[i]]
array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment