Exemple #1
0
        private async Task Say(BotMessage message, ResponseContext context)
        {
            string chatHubID = null;

            if (message.ChatHub != null)
            {
                chatHubID = message.ChatHub.ID;
            }
            else if (context != null && context.Message.ChatHub != null)
            {
                chatHubID = context.Message.ChatHub.ID;
            }

            if (chatHubID != null)
            {
                NoobWebClient client = new NoobWebClient();
                await client.GetResponse(
                    "https://slack.com/api/chat.postMessage",
                    RequestType.Post,
                    "token", this.SlackKey,
                    "channel", chatHubID,
                    "text", message.Text,
                    "as_user", "true"
                    );
            }
            else
            {
                throw new ArgumentException("When calling the Say() method, the message parameter must have its ChatHub property set.");
            }
        }
Exemple #2
0
        private async Task Say(BotMessage message, ResponseContext context)
        {
            string chatHubID = null;

            if (message == null)
            {
                return;
            }

            if (message.ChatHub != null)
            {
                chatHubID = message.ChatHub.ID;
            }
            else if (context != null && context.Message.ChatHub != null)
            {
                chatHubID = context.Message.ChatHub.ID;
            }

            if (chatHubID == null)
            {
                throw new ArgumentException($"When calling the {nameof(Say)}() method, the {nameof(message)} parameter must have its {nameof(message.ChatHub)} property set.");
            }

            var client = new NoobWebClient();
            var values = new List <string>()
            {
                "token", SlackKey,
                "channel", chatHubID,
                "text", message.Text,
                "as_user", "true"
            };

            if (message.Attachments.Count > 0)
            {
                values.Add("attachments");
                values.Add(JsonConvert.SerializeObject(message.Attachments));
            }

            /** CUSTOM ATTRIBUTE INSERTION ****************************************/
            if (message.Thread_TS != null && message.Thread_TS != String.Empty)
            {
                values.Add("thread_ts");
                values.Add(message.Thread_TS);
            }
            foreach (KeyValuePair <string, string> kv in message.Custom_Attibs)
            {
                values.Add(kv.Key);
                values.Add(kv.Value);
            }
            /** END CUSTOM ATTRIBS *************************************************/

            await client.DownloadString(
                "https://slack.com/api/chat.postMessage",
                RequestMethod.Post,
                values.ToArray()
                );
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            var match = Regex.Match(context.Message.Text, WikiMultiwordRegex);
            string searchTerm;
            if (match.Success)
            {
                searchTerm = match.Groups["term"].Value;
            }
            else
            {
                match = Regex.Match(context.Message.Text, WikiSinglewordRegex);
                searchTerm = match.Groups["term"].Value;
            }
            var requestUrl =
                string.Format(
                    "http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&prop=extracts&exintro=&explaintext=&srsearch={0}&utf8=&continue=",
                    WebUtility.UrlEncode(searchTerm.Trim()));
            var response = new NoobWebClient().GetResponse(requestUrl, RequestMethod.Get).GetAwaiter().GetResult();
            var responseData = JObject.Parse(response);

            if (responseData["query"] != null && responseData["query"]["searchinfo"] != null)
            {
                var totalHits = responseData["query"]["searchinfo"]["totalhits"].Value<int>();

                if (totalHits > 0)
                {
                    var articleTitle = responseData["query"]["search"][0]["title"].Value<string>();
                    var articleRequestUrl =
                        "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" +
                        WebUtility.UrlEncode(articleTitle);
                    var articleResponse =
                        new NoobWebClient().GetResponse(articleRequestUrl, RequestMethod.Get).GetAwaiter().GetResult();
                    var articleData = JObject.Parse(articleResponse);

                    if (articleData["query"]["pages"]["-1"] == null)
                    {
                        var summary = articleData["query"]["pages"].First.First["extract"].Value<string>();
                        if (summary.IndexOf('\n') > 0)
                        {
                            summary = summary.Substring(0, summary.IndexOf('\n'));
                        }

                        return new BotMessage
                        {
                            Text = "http://en.wikipedia.org/wiki/{0}\n {1}".With(articleTitle.Replace(" ", "_"), summary)
                        };
                    }
                }
            }

            return new BotMessage
            {
                Text = "Har aldrig hört talas om {0}, vilket kanske inte är så konstigt. Men vad som _är_ konstigt är att Wikipedia inte heller har nån info om det."
                            .With(searchTerm)
            };
        }
        protected string GetWeatherReport(string city, string state)
        {
            string resultWeatherReport = string.Empty;

            NoobWebClient client = new NoobWebClient();

            string requestUrl = string.Format("http://api.wunderground.com/api/{0}/conditions/q/{1}/{2}.json", WundergroundAPIKey, state.ToUpperInvariant(), city.Replace(' ', '_'));

            resultWeatherReport = client.DownloadString(requestUrl, RequestMethod.Get).GetAwaiter().GetResult();

            return(resultWeatherReport);
        }
Exemple #5
0
        public BotMessage GetResponse(SlackMessage context)
        {
            Match  match      = Regex.Match(context.Message.Text, WIKI_MULTIWORD_REGEX);
            string searchTerm = string.Empty;

            if (match.Success)
            {
                searchTerm = match.Groups["term"].Value;
            }
            else
            {
                match      = Regex.Match(context.Message.Text, WIKI_SINGLEWORD_REGEX);
                searchTerm = match.Groups["term"].Value;
            }
            string  requestUrl   = string.Format("http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&prop=extracts&exintro=&explaintext=&srsearch={0}&utf8=&continue=", WebUtility.UrlEncode(searchTerm.Trim()));
            string  response     = new NoobWebClient().GetResponse(requestUrl, RequestMethod.Get).GetAwaiter().GetResult();
            JObject responseData = JObject.Parse(response);

            if (responseData["query"] != null && responseData["query"]["searchinfo"] != null)
            {
                int totalHits = responseData["query"]["searchinfo"]["totalhits"].Value <int>();

                if (totalHits > 0)
                {
                    string  articleTitle      = responseData["query"]["search"][0]["title"].Value <string>();
                    string  articleRequestUrl = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + WebUtility.UrlEncode(articleTitle);
                    string  articleResponse   = new NoobWebClient().GetResponse(articleRequestUrl, RequestMethod.Get).GetAwaiter().GetResult();
                    JObject articleData       = JObject.Parse(articleResponse);

                    if (articleData["query"]["pages"]["-1"] == null)
                    {
                        string summary = articleData["query"]["pages"].First.First["extract"].Value <string>();
                        if (summary.IndexOf('\n') > 0)
                        {
                            summary = summary.Substring(0, summary.IndexOf('\n'));
                        }

                        return(new BotMessage()
                        {
                            Text = "Awwww yeah. I know all about that. Check it, y'all!: " + string.Format("http://en.wikipedia.org/wiki/{0}", articleTitle.Replace(" ", "_")) + " \n> " + summary
                        });
                    }
                }
            }

            return(new BotMessage()
            {
                Text = "I never heard of that, which isn't all that surprisin'. What IS surprisin' is that neither has Wikipedia. Have you been hangin' out behind the barn again with SkeeterBot?"
            });
        }
Exemple #6
0
        private async Task Say(BotMessage message, ResponseContext context)
        {
            string chatHubID = null;

            if (message == null)
            {
                return;
            }

            if (message.ChatHub != null)
            {
                chatHubID = message.ChatHub.ID;
            }
            else if (context != null && context.Message.ChatHub != null)
            {
                chatHubID = context.Message.ChatHub.ID;
            }

            if (chatHubID != null)
            {
                NoobWebClient client = new NoobWebClient();

                List <string> values = new List <string>()
                {
                    "token", this.SlackKey,
                    "channel", chatHubID,
                    "text", message.Text,
                    "as_user", "true"
                };

                if (message.Attachments.Count > 0)
                {
                    values.Add("attachments");
                    values.Add(JsonConvert.SerializeObject(message.Attachments));
                }

                await client.DownloadString(
                    "https://slack.com/api/chat.postMessage",
                    RequestMethod.Post,
                    values.ToArray()
                    );
            }
            else
            {
                throw new ArgumentException("When calling the Say() method, the message parameter must have its ChatHub property set.");
            }
        }
Exemple #7
0
        private async Task React(BotReaction reaction, ResponseContext context)
        {
            string chatHubID = null;

            if (reaction == null)
            {
                return;
            }

            if (reaction.ChatHub != null)
            {
                chatHubID = reaction.ChatHub.ID;
            }
            else if (context != null && context.Message.ChatHub != null)
            {
                chatHubID = context.Message.ChatHub.ID;
            }

            if (chatHubID == null)
            {
                throw new ArgumentException($"When calling the {nameof(Say)}() method, the {nameof(reaction)} parameter must have its {nameof(reaction.ChatHub)} property set.");
            }

            var client = new NoobWebClient();
            var values = new List <string>()
            {
                "token", SlackKey,
                "channel", chatHubID,
                "name", reaction.Name,
                "timestamp", reaction.Timestamp,
                "file_comment", reaction.File_Comment,
                "file", reaction.File
            };

            foreach (KeyValuePair <string, string> kv in reaction.Custom_Attibs)
            {
                values.Add(kv.Key);
                values.Add(kv.Value);
            }
            /** END CUSTOM ATTRIBS *************************************************/

            await client.DownloadString(
                "https://slack.com/api/reactions.add",
                RequestMethod.Post,
                values.ToArray()
                );
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            Match match = Regex.Match(context.Message.Text, WIKI_MULTIWORD_REGEX);
            string searchTerm = string.Empty;
            if (match.Success) {
                searchTerm = match.Groups["term"].Value;
            }
            else {
                match = Regex.Match(context.Message.Text, WIKI_SINGLEWORD_REGEX);
                searchTerm = match.Groups["term"].Value;
            }
            string requestUrl = string.Format("http://en.wikipedia.org/w/api.php?action=query&list=search&format=json&prop=extracts&exintro=&explaintext=&srsearch={0}&utf8=&continue=", WebUtility.UrlEncode(searchTerm.Trim()));
            string response = new NoobWebClient().GetResponse(requestUrl, RequestMethod.Get).GetAwaiter().GetResult();
            JObject responseData = JObject.Parse(response);

            if (responseData["query"] != null && responseData["query"]["searchinfo"] != null) {
                int totalHits = responseData["query"]["searchinfo"]["totalhits"].Value<int>();

                if (totalHits > 0) {
                    string articleTitle = responseData["query"]["search"][0]["title"].Value<string>();
                    string articleRequestUrl = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + WebUtility.UrlEncode(articleTitle);
                    string articleResponse = new NoobWebClient().GetResponse(articleRequestUrl, RequestMethod.Get).GetAwaiter().GetResult();
                    JObject articleData = JObject.Parse(articleResponse);

                    if (articleData["query"]["pages"]["-1"] == null) {
                        string summary = articleData["query"]["pages"].First.First["extract"].Value<string>();
                        if (summary.IndexOf('\n') > 0) {
                            summary = summary.Substring(0, summary.IndexOf('\n'));
                        }
                        
                        return new BotMessage() {
                            Text = "Awwww yeah. I know all about that. Check it, y'all!: " + string.Format("http://en.wikipedia.org/wiki/{0}", articleTitle.Replace(" ", "_")) + " \n> " + summary
                        };
                    }
                }
            }

            return new BotMessage() {
                Text = "I never heard of that, which isn't all that surprisin'. What IS surprisin' is that neither has Wikipedia. Have you been hangin' out behind the barn again with SkeeterBot?"
            };
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            string data = string.Empty;
            if (LastDataGrab != null && LastDataGrab.Value > DateTime.Now.AddMinutes(-10)) {
                data = LastData;
            }
            else {
                NoobWebClient client = new NoobWebClient();
                data = client.GetResponse("http://api.wunderground.com/api/" + WundergroundAPIKey + "/conditions/q/TN/Nashville.json", RequestMethod.Get).GetAwaiter().GetResult();
                LastData = data;
                LastDataGrab = DateTime.Now;
            }
            
            JObject jData = JObject.Parse(data);
            if (jData["current_observation"] != null) {
                string tempString = jData["current_observation"]["temp_f"].Value<string>();
                double temp = double.Parse(tempString);

                return new BotMessage() { Text = "It's about " + Math.Round(temp).ToString() + "° out, and it's " + jData["current_observation"]["weather"].Value<string>().ToLower() + ". " + context.Get<Phrasebook>().GetWeatherAnalysis(temp) + "\n\nIf you wanna see more. head over to " + jData["current_observation"]["forecast_url"].Value<string>() + " - my girlfriend DonnaBot works over there!" };
            }
            else {
                return new BotMessage() { Text = "Aww, nuts. My weatherbot gal-pal ain't around. Try 'gin later - she's prolly just fixin' her makeup." };
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            string data = string.Empty;

            if (LastDataGrab != null && LastDataGrab.Value > DateTime.Now.AddMinutes(-10))
            {
                data = LastData;
            }
            else
            {
                NoobWebClient client = new NoobWebClient();
                data         = client.GetResponse("http://api.wunderground.com/api/" + WundergroundAPIKey + "/conditions/q/TN/Nashville.json", RequestType.Get).GetAwaiter().GetResult();
                LastData     = data;
                LastDataGrab = DateTime.Now;
            }

            JObject jData = JObject.Parse(data);

            if (jData["current_observation"] != null)
            {
                string tempString = jData["current_observation"]["temp_f"].Value <string>();
                double temp       = double.Parse(tempString);

                return(new BotMessage()
                {
                    Text = "It's about " + Math.Round(temp).ToString() + "° out, and it's " + jData["current_observation"]["weather"].Value <string>().ToLower() + ". Not bad, but it ain't hoedown weather, is it?\n\nIf you wanna see more. head over to " + jData["current_observation"]["forecast_url"].Value <string>() + " - my girlfriend DonnaBot works over there!"
                });
            }
            else
            {
                return(new BotMessage()
                {
                    Text = "Aww, nuts. My weatherbot gal-pal ain't around. Try 'gin later - she's prolly just fixin' her makeup."
                });
            }
        }
Exemple #11
0
        public BotMessage GetResponse(SlackMessage context)
        {
            string term = WebUtility.UrlEncode(Regex.Match(context.Message.Text, DEFINE_REGEX).Groups["term"].Value);

            NoobWebClient client = new NoobWebClient();
            string definitionData = client.GetResponse(
                string.Format(
                    "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/{0}?key={1}",
                    term,
                    ApiKey
                ),
                RequestMethod.Get
            ).GetAwaiter().GetResult();

            XElement root = XElement.Parse(definitionData);

            if (root.Descendants("suggestion").FirstOrDefault() != null) {
                return new BotMessage() {
                    Text = "You know what? I don't even know what that is, and neither does my buddy WebsterBot. And he's super smart, y'all. He wanted to know if maybe you meant *" + root.Descendants("suggestion").First().Value + "*?"
                };
            }
            else if (root.Descendants("ew").FirstOrDefault() == null) {
                return new BotMessage() {
                    Text = "Are y'all funnin' with me again? That can't be a real thing, can it?"
                };
            }
            else {
                string word = root.Descendants("ew").First().Value;
                string partOfSpeech = root.Descendants("fl").First().Value;
                string definition = root.Descendants("dt").First().Value;
                string etymology = null;
                string audioFile = null;

                if (root.Descendants("et").FirstOrDefault() != null) {
                    etymology = root.Descendants("et").First().Value;
                    etymology = Regex.Replace(etymology, "</?it>", "_");
                }

                // compute the sound url thing
                if (root.Descendants("sound") != null) {
                    audioFile = root.Descendants("wav").First().Value;

                    // do a bunch of dumb stuff to find the audio file URL because this API is wacky
                    // http://www.dictionaryapi.com/info/faq-audio-image.htm#collegiate
                    if (audioFile.StartsWith("bix")) {
                        audioFile = "bix/" + audioFile;
                    }
                    else if (audioFile.StartsWith("gg")) {
                        audioFile = "gg/" + audioFile;
                    }
                    else if (audioFile.StartsWith("number")) {
                        audioFile = "number/" + audioFile;
                    }
                    else {
                        audioFile = audioFile.Substring(0, 1) + "/" + audioFile;
                    }

                    audioFile = "http://media.merriam-webster.com/soundc11/" + audioFile;
                }

                string[] defSplits = definition.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if (defSplits.Length > 1) {
                    StringBuilder defBuilder = new StringBuilder();

                    foreach (string def in defSplits) {
                        defBuilder.Append("• " + def + "\n");
                    }

                    definition = defBuilder.ToString();
                }
                else { definition = definition.Replace(":", string.Empty); }

                return new BotMessage() {
                    Attachments = new List<SlackAttachment>() {
                    new SlackAttachment() {
                        ColorHex = "#AD91C2",
                        Fallback = "Define " + term,
                        Fields = new List<SlackAttachmentField>() {
                            new SlackAttachmentField() { IsShort = true, Title = "Definition", Value = definition },
                            new SlackAttachmentField() { IsShort = true, Title = "Part of Speech", Value = partOfSpeech },
                            new SlackAttachmentField() { IsShort = true, Title = "Etymology", Value = (!string.IsNullOrEmpty(etymology) ? etymology : "It's a made up word. They all are.") },
                            new SlackAttachmentField() { IsShort = true, Title = "How to Say It", Value = audioFile },
                        },
                        Title =  "Define: " + term,
                        TitleLink = "http://dictionary.reference.com/browse/" + WebUtility.UrlEncode(term),
                    }
                },
                    Text = "Well, I have literally _no_ idea what that means, so I called my friend WebsterBot."
                };
            }
        }
Exemple #12
0
        public BotMessage GetResponse(ResponseContext context)
        {
            string term = WebUtility.UrlEncode(Regex.Match(context.Message.Text, DEFINE_REGEX).Groups["term"].Value);

            NoobWebClient client         = new NoobWebClient();
            string        definitionData = client.GetResponse(
                string.Format(
                    "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/{0}?key={1}",
                    term,
                    ApiKey
                    ),
                RequestMethod.Get
                ).GetAwaiter().GetResult();

            XElement root = XElement.Parse(definitionData);

            if (root.Descendants("suggestion").FirstOrDefault() != null)
            {
                return(new BotMessage()
                {
                    Text = "You know what? I don't even know what that is, and neither does my buddy WebsterBot. And he's super smart, y'all. He wanted to know if maybe you meant *" + root.Descendants("suggestion").First().Value + "*?"
                });
            }
            else if (root.Descendants("ew").FirstOrDefault() == null)
            {
                return(new BotMessage()
                {
                    Text = "Are y'all funnin' with me again? That can't be a real thing, can it?"
                });
            }
            else
            {
                string word         = root.Descendants("ew").First().Value;
                string partOfSpeech = root.Descendants("fl").First().Value;
                string definition   = root.Descendants("dt").First().Value;
                string etymology    = null;
                string audioFile    = null;

                if (root.Descendants("et").FirstOrDefault() != null)
                {
                    etymology = root.Descendants("et").First().Value;
                    etymology = Regex.Replace(etymology, "</?it>", "_");
                }

                // compute the sound url thing
                if (root.Descendants("sound") != null)
                {
                    audioFile = root.Descendants("wav").First().Value;

                    // do a bunch of dumb stuff to find the audio file URL because this API is wacky
                    // http://www.dictionaryapi.com/info/faq-audio-image.htm#collegiate
                    if (audioFile.StartsWith("bix"))
                    {
                        audioFile = "bix/" + audioFile;
                    }
                    else if (audioFile.StartsWith("gg"))
                    {
                        audioFile = "gg/" + audioFile;
                    }
                    else if (audioFile.StartsWith("number"))
                    {
                        audioFile = "number/" + audioFile;
                    }
                    else
                    {
                        audioFile = audioFile.Substring(0, 1) + "/" + audioFile;
                    }

                    audioFile = "http://media.merriam-webster.com/soundc11/" + audioFile;
                }

                string[] defSplits = definition.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if (defSplits.Length > 1)
                {
                    StringBuilder defBuilder = new StringBuilder();

                    foreach (string def in defSplits)
                    {
                        defBuilder.Append("• " + def + "\n");
                    }

                    definition = defBuilder.ToString();
                }
                else
                {
                    definition = definition.Replace(":", string.Empty);
                }

                return(new BotMessage()
                {
                    Attachments = new List <SlackAttachment>()
                    {
                        new SlackAttachment()
                        {
                            ColorHex = "#AD91C2",
                            Fallback = "Define " + term,
                            Fields = new List <SlackAttachmentField>()
                            {
                                new SlackAttachmentField()
                                {
                                    IsShort = true, Title = "Definition", Value = definition
                                },
                                new SlackAttachmentField()
                                {
                                    IsShort = true, Title = "Part of Speech", Value = partOfSpeech
                                },
                                new SlackAttachmentField()
                                {
                                    IsShort = true, Title = "Etymology", Value = (!string.IsNullOrEmpty(etymology) ? etymology : "It's a made up word. They all are.")
                                },
                                new SlackAttachmentField()
                                {
                                    IsShort = true, Title = "How to Say It", Value = audioFile
                                },
                            },
                            Title = "Define: " + term,
                            TitleLink = "http://dictionary.reference.com/browse/" + WebUtility.UrlEncode(term),
                        }
                    },
                    Text = "Well, I have literally _no_ idea what that means, so I called my friend WebsterBot."
                });
            }
        }
Exemple #13
0
        private static async Task PopulateUsernameCache()
        {
            var client = new NoobWebClient();

            var values = new List<string>
                {
                    "token", _slackKey
                };

            var json = await client.GetResponse("https://slack.com/api/users.list", RequestMethod.Post, values.ToArray());
            var jData = JObject.Parse(json);

            foreach (var user in jData[Keys.Slack.UserListJson.Members].Values<JObject>())
            {
                _userNameCache.Add(user["id"].Value<string>(), user["name"].Value<string>());
            }
        }
Exemple #14
0
        private async Task Say(BotMessage message, ResponseContext context)
        {
            string chatHubID = null;

            if(message.ChatHub != null) {
                chatHubID = message.ChatHub.ID;
            }
            else if(context != null && context.Message.ChatHub != null) {
                chatHubID = context.Message.ChatHub.ID;
            }

            if(chatHubID != null) {
                NoobWebClient client = new NoobWebClient();

                List<string> values = new List<string>() {
                    "token", this.SlackKey,
                    "channel", chatHubID,
                    "text", message.Text,
                    "as_user", "true"
                };

                if (message.Attachments.Count > 0) {
                    values.Add("attachments");
                    values.Add(JsonConvert.SerializeObject(message.Attachments));
                }

                await client.GetResponse(
                    "https://slack.com/api/chat.postMessage",
                    RequestMethod.Post,
                    values.ToArray()
                );
            }
            else {
                throw new ArgumentException("When calling the Say() method, the message parameter must have its ChatHub property set.");
            }
        }
Exemple #15
0
        public async Task Connect(string slackKey)
        {
            this.SlackKey = slackKey;

            // disconnect in case we're already connected like a crazy person
            Disconnect();

            // kill the regex for our bot's name - we'll rebuild it upon request with some of the info we get here
            BotNameRegex = string.Empty;

            NoobWebClient client = new NoobWebClient();
            string json = await client.GetResponse("https://slack.com/api/rtm.start", RequestMethod.Post, "token", this.SlackKey);
            JObject jData = JObject.Parse(json);

            TeamID = jData["team"]["id"].Value<string>();
            TeamName = jData["team"]["name"].Value<string>();
            UserID = jData["self"]["id"].Value<string>();
            UserName = jData["self"]["name"].Value<string>();
            string webSocketUrl = jData["url"].Value<string>();

            UserNameCache.Clear();
            foreach (JObject userObject in jData["users"]) {
                UserNameCache.Add(userObject["id"].Value<string>(), userObject["name"].Value<string>());
            }
            
            // load the channels, groups, and DMs that margie's in
            Dictionary<string, SlackChatHub> hubs = new Dictionary<string, SlackChatHub>();
            ConnectedHubs = hubs;
            
            // channelz
            if (jData["channels"] != null) {
                foreach (JObject channelData in jData["channels"]) {
                    if (!channelData["is_archived"].Value<bool>() && channelData["is_member"].Value<bool>()) {
                        SlackChatHub channel = new SlackChatHub() {
                            ID = channelData["id"].Value<string>(),
                            Name = "#" + channelData["name"].Value<string>(),
                            Type = SlackChatHubType.Channel
                        };
                        hubs.Add(channel.ID, channel);
                    }
                }
            }

            // groupz
            if (jData["groups"] != null) {
                foreach (JObject groupData in jData["groups"]) {
                    if (!groupData["is_archived"].Value<bool>() && groupData["members"].Values<string>().Contains(UserID)) {
                        SlackChatHub group = new SlackChatHub() {
                            ID = groupData["id"].Value<string>(),
                            Name = groupData["name"].Value<string>(),
                            Type = SlackChatHubType.Group
                        };
                        hubs.Add(group.ID, group);
                    }
                }
            }

            // dmz
            if (jData["ims"] != null) {
                foreach (JObject dmData in jData["ims"]) {
                    string userID = dmData["user"].Value<string>();
                    SlackChatHub dm = new SlackChatHub() {
                        ID = dmData["id"].Value<string>(),
                        Name = "@" + (UserNameCache.ContainsKey(userID) ? UserNameCache[userID] : userID),
                        Type = SlackChatHubType.DM
                    };
                    hubs.Add(dm.ID, dm);
                }
            }

            // set up the websocket and connect
            WebSocket = new WebSocket(webSocketUrl);
            WebSocket.OnOpen += (object sender, EventArgs e) => {
                // set connection-related properties
                ConnectedSince = DateTime.Now;
            };
            WebSocket.OnMessage += async (object sender, MessageEventArgs args) => {
                await ListenTo(args.Data);
            };
            WebSocket.OnClose += (object sender, CloseEventArgs e) => {
                // set connection-related properties
                ConnectedSince = null;
                TeamID = null;
                TeamName = null;
                UserID = null;
                UserName = null;
            };
            WebSocket.Connect();
        }
Exemple #16
0
        private static async Task PopulateChannelsCache()
        {
            var client = new NoobWebClient();

            var values = new List<string>
                {
                    "token", _slackKey,
                    "exclude_archived","1"
                };

            var json = await client.GetResponse("https://slack.com/api/channels.list", RequestMethod.Post, values.ToArray());
            var jData = JObject.Parse(json);

            foreach (var channel in jData[Keys.Slack.ChannelsListJson.Channels].Values<JObject>())
            {
                _channelsNameCache.Add(channel["id"].Value<string>(), channel["name"].Value<string>());
            }
        }
Exemple #17
0
        public async Task Connect()
        {
            // disconnect in case we're already connected like a crazy person
            Disconnect();

            // kill the regex for our bot's name - we'll rebuild it upon request with some of the info we get here
            BotNameRegex = string.Empty;

            NoobWebClient client = new NoobWebClient();
            string        json   = await client.GetResponse("https://slack.com/api/rtm.start", RequestType.Post, "token", this.SlackKey);

            JObject jData = JObject.Parse(json);

            TeamID   = jData["team"]["id"].Value <string>();
            UserID   = jData["self"]["id"].Value <string>();
            UserName = jData["self"]["name"].Value <string>();
            string webSocketUrl = jData["url"].Value <string>();

            UserNameCache.Clear();
            foreach (JObject userObject in jData["users"])
            {
                UserNameCache.Add(userObject["id"].Value <string>(), userObject["name"].Value <string>());
            }

            // load the channels, groups, and DMs that margie's in
            Dictionary <string, SlackChatHub> hubs = new Dictionary <string, SlackChatHub>();

            ConnectedHubs = hubs;

            // channelz
            if (jData["channels"] != null)
            {
                foreach (JObject channelData in jData["channels"])
                {
                    if (!channelData["is_archived"].Value <bool>() && channelData["is_member"].Value <bool>())
                    {
                        SlackChatHub channel = new SlackChatHub()
                        {
                            ID   = channelData["id"].Value <string>(),
                            Name = "#" + channelData["name"].Value <string>(),
                            Type = SlackChatHubType.Channel
                        };
                        hubs.Add(channel.ID, channel);
                    }
                }
            }

            // groupz
            if (jData["groups"] != null)
            {
                foreach (JObject groupData in jData["groups"])
                {
                    if (!groupData["is_archived"].Value <bool>() && groupData["members"].Values <string>().Contains(UserID))
                    {
                        SlackChatHub group = new SlackChatHub()
                        {
                            ID   = groupData["id"].Value <string>(),
                            Name = groupData["name"].Value <string>(),
                            Type = SlackChatHubType.Group
                        };
                        hubs.Add(group.ID, group);
                    }
                }
            }

            // dmz
            if (jData["ims"] != null)
            {
                foreach (JObject dmData in jData["ims"])
                {
                    string       userID = dmData["user"].Value <string>();
                    SlackChatHub dm     = new SlackChatHub()
                    {
                        ID   = dmData["id"].Value <string>(),
                        Name = "@" + (UserNameCache.ContainsKey(userID) ? UserNameCache[userID] : userID),
                        Type = SlackChatHubType.DM
                    };
                    hubs.Add(dm.ID, dm);
                }
            }

            // set up the websocket and connect
            WebSocket          = new WebSocket(webSocketUrl);
            WebSocket.OnClose += (object sender, CloseEventArgs e) => {
                IsConnected = false;
            };
            WebSocket.OnMessage += async(object sender, MessageEventArgs args) => {
                await ListenTo(args.Data);
            };
            WebSocket.OnOpen += (object sender, EventArgs e) => {
                IsConnected = true;
            };
            WebSocket.Connect();
        }
        protected string GetWeatherReport(string city, string state)
        {
            string resultWeatherReport = string.Empty;

            NoobWebClient client = new NoobWebClient();

            string requestUrl = string.Format("http://api.wunderground.com/api/{0}/conditions/q/{1}/{2}.json", WundergroundAPIKey, state.ToUpperInvariant(), city.Replace(' ', '_'));

            resultWeatherReport = client.GetResponse(requestUrl, RequestMethod.Get).GetAwaiter().GetResult();

            return resultWeatherReport;
        }