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."); } }
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); }
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."); } }
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." }); } }
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(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." }; } }
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." }); } }
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."); } }
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(); }
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(); }
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>()); } }
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>()); } }
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; }