PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/IrcBot.Search/Search.cs

https://github.com/cmpct/c-irc-bot
C# | 49 lines | 42 code | 3 blank | 4 comment | 6 complexity | 87b39c07e55290ca74eec8a97e31e35c MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Meebey.SmartIrc4net;
  7. using System.Xml;
  8. namespace IrcBot.Search
  9. {
  10. /// <summary>
  11. /// Searches DuckDuckGo for a zero-click answer.
  12. /// </summary>
  13. public class Search : IPlugin
  14. {
  15. string IPlugin.InvokeWithMessage(string source, string message, ref IrcClient client)
  16. {
  17. string toSend = null;
  18. if (message.StartsWith(".ddg"))
  19. {
  20. XmlDocument xd = new XmlDocument();
  21. xd.Load(GetDDGApiUrl(message.Split(new char[] { ' ' }, 2)[1]));
  22. if (xd.SelectSingleNode("/DuckDuckGoResponse/Answer") != null)
  23. {
  24. toSend = xd.SelectSingleNode("/DuckDuckGoResponse/Answer").InnerText;
  25. }
  26. // dear diary, can I have my ?. operator soon?
  27. if (xd.SelectSingleNode("/DuckDuckGoResponse/Abstract") != null)
  28. {
  29. if (!String.IsNullOrWhiteSpace(xd.SelectSingleNode("/DuckDuckGoResponse/Abstract").InnerText))
  30. {
  31. toSend = String.Format("{0} - {1}", xd.SelectSingleNode("/DuckDuckGoResponse/Abstract").InnerText, xd.SelectSingleNode("/DuckDuckGoResponse/AbstractURL").InnerText);
  32. }
  33. }
  34. }
  35. return toSend;
  36. }
  37. string IPlugin.InvokeWithChannelUserChange(string channel, string user, string kicker, string message, ChannelUserChange type, ref IrcClient client)
  38. {
  39. return null; // Not implemented
  40. }
  41. static string GetDDGApiUrl(string query)
  42. {
  43. return String.Format("https://api.duckduckgo.com/?q={0}&format=xml&t=IrcBot.Search&no_redirect=1&no_html=1&skip_disambig=1", Uri.EscapeUriString(query));
  44. }
  45. }
  46. }