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() ); }
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); }
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."); } }
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) { string term = WebUtility.UrlEncode(Regex.Match(context.Message.Text, DEFINE_REGEX).Groups["term"].Value); NoobWebClient client = new NoobWebClient(); string definitionData = client.DownloadString( 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 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.DownloadString("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(); }