PageRenderTime 101ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/duckduckgo.js

https://github.com/gildean/dunn
JavaScript | 86 lines | 64 code | 11 blank | 11 comment | 15 complexity | 43d02f3a3d510d73adc4c234ab70a45b MD5 | raw file
  1. /*
  2. * @Plugin DuckDuckGo
  3. * @Description Use the duckduckgo api
  4. * @Trigger .ddg
  5. *
  6. * @Author Olli K
  7. * @Website github.com/gildean
  8. * @License MIT
  9. * @Copyright -
  10. *
  11. */
  12. var qs = require('querystring');
  13. var url = require('url');
  14. function Ddg(irc) {
  15. "use strict";
  16. var trigger = 'ddg';
  17. var mesLen = trigger.length + irc.command.length + 1;
  18. var question = function (pla, channel, nick, par, message) {
  19. function isValidJson(json) {
  20. try {
  21. return JSON.parse(json);
  22. } catch (e) {
  23. return false;
  24. }
  25. }
  26. function sendToIrc(err, links) {
  27. return irc.send(channel, nick + ': ' + ((!err) ? links : err));
  28. }
  29. function getDataFromJson(jsonn, query, cb) {
  30. var json = isValidJson(jsonn);
  31. if (json) {
  32. var abstractText = (json.AbstractText) ? (json.AbstractText.replace(/\n/ig, ' ').replace(/<pre>.+?<\/pre>/ig, '')) + ' || ' : '';
  33. var abstractSource = (json.AbstractSource && json.AbstractURL) ? json.AbstractSource + ': ' + json.AbstractURL + ' || ' : '';
  34. var answerText = (json.Answer) ? json.Answer + ' || ' : '';
  35. var definitionText = (json.DefinitionText && json.DefinitionURL) ? 'Definition ( ' + json.DefinitionURL + ' ): ' + json.DefinitionText + ' || ' : '';
  36. var redirect = (json.Redirect) ? url.resolve('https://duckduckgo.com', json.Redirect) + ' || ' : '';
  37. var links = abstractText + abstractSource + answerText + definitionText + redirect;
  38. if (links === '') {
  39. links = 'https://duckduckgo.com/?q=' + query + ' ';
  40. }
  41. return cb(null, links.substring(0, links.length - 4));
  42. } else {
  43. return cb('No valid answer', null);
  44. }
  45. }
  46. function handleAnswer(err, answer, query) {
  47. if (!err) {
  48. return getDataFromJson(answer, query, sendToIrc);
  49. } else {
  50. return sendToIrc(err);
  51. }
  52. }
  53. (function searchDdg(message, cb) {
  54. var msg = qs.escape(message.substring(mesLen).trim());
  55. if (msg !== '') {
  56. var qPath = '/?q=' + msg + '&format=json&no_redirect=1&no_html=1';
  57. var options = {
  58. hostname: 'api.duckduckgo.com',
  59. path: qPath
  60. };
  61. var req = irc.httpGet(options, function (err, res, json) {
  62. if (!err) {
  63. return cb(null, json, msg);
  64. } else {
  65. return cb(err.message, null);
  66. }
  67. });
  68. } else {
  69. return cb('DuckDuckGo e.g. \'' + irc.command + trigger + ' define google\' or \'' + irc.command + trigger + ' 10+20*50\'', null);
  70. }
  71. }(message, handleAnswer));
  72. };
  73. irc.addTrigger(trigger, question);
  74. }
  75. exports.Plugin = Ddg;