PageRenderTime 5ms CodeModel.GetById 1ms app.highlight 2ms 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
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using System.Threading.Tasks;
 6using Meebey.SmartIrc4net;
 7using System.Xml;
 8
 9namespace IrcBot.Search
10{
11    /// <summary>
12    /// Searches DuckDuckGo for a zero-click answer.
13    /// </summary>
14    public class Search : IPlugin
15    {
16        string IPlugin.InvokeWithMessage(string source, string message, ref IrcClient client)
17        {
18            string toSend = null;
19            if (message.StartsWith(".ddg"))
20            {
21                XmlDocument xd = new XmlDocument();
22                xd.Load(GetDDGApiUrl(message.Split(new char[] { ' ' }, 2)[1]));
23                if (xd.SelectSingleNode("/DuckDuckGoResponse/Answer") != null)
24                {
25                    toSend = xd.SelectSingleNode("/DuckDuckGoResponse/Answer").InnerText;
26                }
27                // dear diary, can I have my ?. operator soon?
28                if (xd.SelectSingleNode("/DuckDuckGoResponse/Abstract") != null)
29                {
30                    if (!String.IsNullOrWhiteSpace(xd.SelectSingleNode("/DuckDuckGoResponse/Abstract").InnerText))
31                    {
32                        toSend = String.Format("{0} - {1}", xd.SelectSingleNode("/DuckDuckGoResponse/Abstract").InnerText, xd.SelectSingleNode("/DuckDuckGoResponse/AbstractURL").InnerText);
33                    }
34                }
35            }
36            return toSend;
37        }
38
39        string IPlugin.InvokeWithChannelUserChange(string channel, string user, string kicker, string message, ChannelUserChange type, ref IrcClient client)
40        {
41            return null; // Not implemented
42        }
43
44        static string GetDDGApiUrl(string query)
45        {
46            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));
47        }
48    }
49}