PageRenderTime 94ms CodeModel.GetById 68ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/duckduck.js

https://github.com/gcr/ips-lurker
JavaScript | 83 lines | 64 code | 9 blank | 10 comment | 21 complexity | e8972c42f322428aa983e894981762f7 MD5 | raw file
  1. /*
  2. * duckduckgo.js -- zero-click API for duck duck go
  3. * see http://duckduckgo.com/api.html
  4. *
  5. */
  6. var http = require('http'),
  7. querystring = require('querystring'),
  8. randomSay = require('../lib/plugin_glue').randomSay;
  9. function duckDuckGoQuery(query, cb) {
  10. // run cb(wittyResponse) when DDG returns something special
  11. http
  12. .createClient(80, 'api.duckduckgo.com')
  13. .request('GET', '/?'+querystring.stringify(
  14. {q: query, format: "json", no_redirect: 1, no_html: 1}
  15. ),
  16. {'host':'api.duckduckgo.com'})
  17. .on('response', function(res) {
  18. // response could come in more than one packet, so create a buffer
  19. // to hold it all
  20. var body='';
  21. res.on('data',function(data){body+=data;})
  22. .on('end', function(end) {
  23. try {
  24. // Parse the object we get
  25. var response = JSON.parse(body.toString().trim());
  26. console.log(response);
  27. if (response.Answer) {
  28. return cb(response.Answer);
  29. } else if (response.Abstract) {
  30. if (response.AbstractURL) {
  31. return cb(response.Abstract+" [url=\""+response.AbstractURL+"\"](see also)[/url]");
  32. } else {
  33. return cb(response.Abstract);
  34. }
  35. } else if (response.Definition) {
  36. return cb(response.Definition);
  37. } else if (response.RelatedTopics[0]) {
  38. return cb(response.RelatedTopics[0].Text);
  39. } else {
  40. return cb();
  41. }
  42. } catch (err) {}
  43. });
  44. })
  45. .end(); // Send our request
  46. }
  47. exports.init = function(chat) {
  48. chat.on('message', function(msg, usr, uid) {
  49. if (!chat.settled || uid == chat.userId) { return; }
  50. if (msg.match(/lurker/i)) {
  51. var query = msg.match(/what('s| is) *(the|an|a)* ([^?]*)/i);
  52. // vim: '
  53. if (query) {
  54. var q = query[3];
  55. if (q.length) {
  56. if (q.match(/coitus/i) || q.match(/sex/i)) {
  57. chat.say("It's what you wish you were having, "+usr+"!");
  58. } else {
  59. duckDuckGoQuery(q, function(text) {
  60. if (text) {
  61. chat.say(text);
  62. } else {
  63. randomSay([
  64. "no clue", "not sure", "magic 8-ball says: OUTCOME UNCERTAIN",
  65. "haven't the foggiest", "dunno", "your guess is as good as mine"]);
  66. }
  67. });
  68. }
  69. }
  70. }
  71. }
  72. });
  73. };
  74. exports.duckDuckGoQuery = duckDuckGoQuery;