PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 5ms RepoModel.GetById 36ms app.codeStats 0ms

/plugins/duckduckgo.js

https://github.com/johnkpaul/protobot
JavaScript | 37 lines | 30 code | 6 blank | 1 comment | 9 complexity | 881d29a5a1bcf489ebcc1d67c3b6ae8c MD5 | raw file
 1exports.register = register
 2
 3var exec = require( 'child_process' ).exec
 4
 5/* ---------------------------- DuckDuckGo ---------------------------- */
 6function DuckDuckGo() {
 7}
 8
 9DuckDuckGo.prototype.search = function( query, cloudback ) {
10  exec("curl 'http://api.duckduckgo.com/?format=json&q=" + escape( query ) + "'", function ( err, stdout, stderr ) {
11    var results = JSON.parse( stdout ) // What could possibly go wrong?
12    cloudback.call( this, results )
13  })
14}
15
16function register( j ) {
17  var ddg = new DuckDuckGo()
18
19  j.watch_for( /^([\/.,`?]?)ddg ([^#@]+)(?:\s*#([1-9]))?(?:\s*@\s*([-\[\]\{\}`|_\w]+))?$/, function( message ) {
20    var user = message.match_data[4] || message.name
21      , term = message.match_data[2]
22      , num  = +message.match_data[3]-1 || 0
23
24    ddg.search( term, function( results ) {
25      if ( results["AbstractText"] )
26        message.say( user + ': ' + unescapeAll( results["AbstractText"] ) + ' - ' + results["AbstractURL"] )
27      else if ( results["Definition"] )
28        message.say( user + ': ' + results["Definition"] + ' - ' + results["DefinitionURL"] )
29      else if ( results["Redirect"] ) // !bang syntax used
30        message.say( user + ': ' + results["Redirect"] )
31      else if ( results["Results"].length )
32        message.say( user + ': ' + results["Results"][num]["Text"] + " - " + results["Results"][num]["FirstURL"] )
33      else
34        message.say( user + ": Sorry, no results for '" + term + "'" )
35    })
36  })
37}