public bool CanRespond(ResponseContext context) { if (this.Scorebook == null || this.TeamID != context.TeamID) { // start up scorebook for this team this.TeamID = context.TeamID; this.Scorebook = new Scorebook(TeamID); } // put the scorebook in context in case someone wants to see the scoreboard context.Set<Scorebook>(this.Scorebook); return !context.Message.User.IsSlackbot && Regex.IsMatch(context.Message.Text, SCORE_REGEX); }
private async Task ListenTo(string json) { JObject jObject = JObject.Parse(json); if (jObject["type"].Value<string>() == "message") { string channelID = jObject["channel"].Value<string>(); SlackChatHub hub = null; if (ConnectedHubs.ContainsKey(channelID)) { hub = ConnectedHubs[channelID]; } else { hub = SlackChatHub.FromID(channelID); Dictionary<string, SlackChatHub> hubs = new Dictionary<string, SlackChatHub>(ConnectedHubs.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); hubs.Add(hub.ID, hub); ConnectedHubs = hubs; } string messageText = (jObject["text"] != null ? jObject["text"].Value<string>() : null); // check to see if bot has been mentioned SlackMessage message = new SlackMessage() { ChatHub = hub, MentionsBot = (messageText != null ? Regex.IsMatch(messageText, BotNameRegex, RegexOptions.IgnoreCase) : false), RawData = json, // some messages may not have text or a user (like unfurled data from URLs) Text = messageText, User = (jObject["user"] != null ? new SlackUser() { ID = jObject["user"].Value<string>() } : null) }; ResponseContext context = new ResponseContext() { BotHasResponded = false, BotUserID = UserID, BotUserName = UserName, Message = message, TeamID = this.TeamID, UserNameCache = new ReadOnlyDictionary<string, string>(this.UserNameCache) }; // if the end dev has added any static entries to the ResponseContext collection of Bot, add them to the context being passed to the responders. if (ResponseContext != null) { foreach (string key in ResponseContext.Keys) { context.Set(key, ResponseContext[key]); } } // margie can never respond to herself and requires that the message have text and be from an actual person if (message.User != null && message.User.ID != UserID && message.Text != null) { foreach (IResponder responder in Responders) { if (responder.CanRespond(context)) { await Say(responder.GetResponse(context), context); context.BotHasResponded = true; } } } } RaiseMessageReceived(json); }
static void _bot_MessageReceived(string json) { //Copied from MargieBot source and modified to allow all messages var jObject = JObject.Parse(json); if (jObject[Keys.Slack.MessageJson.Type].Value<string>() != "message") return; var channelID = jObject[Keys.Slack.MessageJson.Channel].Value<string>(); SlackChatHub hub; if (_bot.ConnectedHubs.ContainsKey(channelID)) { hub = _bot.ConnectedHubs[channelID]; } else { hub = SlackChatHub.FromID(channelID); var hubs = new List<SlackChatHub>(); hubs.AddRange(_bot.ConnectedHubs.Values); hubs.Add(hub); } var messageText = (jObject[Keys.Slack.MessageJson.Text] != null ? jObject[Keys.Slack.MessageJson.Text].Value<string>() : null); var message = new SlackMessage { ChatHub = hub, RawData = json, Text = messageText, User = (jObject[Keys.Slack.MessageJson.User] != null ? new SlackUser { ID = jObject[Keys.Slack.MessageJson.User].Value<string>() } : null) }; var context = new ResponseContext { BotHasResponded = false, BotUserID = _bot.UserID, BotUserName = _bot.UserName, Message = message, TeamID = _bot.TeamID, UserNameCache = new ReadOnlyDictionary<string, string>(_userNameCache) }; if (_bot.ResponseContext != null) { foreach (var key in _bot.ResponseContext.Keys) { context.Set(key, _bot.ResponseContext[key]); } } foreach (var handler in _messageHandlers) { handler.Execute(context); } }
/// <summary> /// Listens to events sent from the rtm Interface. Uses a simple web socket to get the requests /// </summary> /// <param name="json">The json.</param> /// <returns></returns> private async Task ListenTo(string json) { ResponseContext context = null; JObject jObject = JObject.Parse(json); if (jObject["type"] != null && jObject["type"].Value <string>() == "message") { string channelID = jObject["channel"].Value <string>(); SlackMessage message = new SlackMessage() { ChatHub = null, RawData = json, Attachments = new List <SlackAttachment>(), Files = new List <SlackFile>() }; if (ConnectedHubs.ContainsKey(channelID)) { message.ChatHub = ConnectedHubs[channelID]; } else { message.ChatHub = SlackChatHub.FromID(channelID); List <SlackChatHub> hubs = new List <SlackChatHub>(); hubs.AddRange(ConnectedHubs.Values); hubs.Add(message.ChatHub); } try { message.Text = (jObject["text"] != null ? jObject["text"].Value <string>() : string.Empty); message.User = new SlackUser(); if (jObject["user"] != null) { WebClient client = new WebClient(); string responseJson = await client.GetResponse("https://slack.com/api/users.info?", WebClient.RequestMethod.Post, "token", this.SlackKey, "user", jObject["user"].Value <string>()); JObject jData = JObject.Parse(responseJson); message.User.ID = jObject["user"].Value <string>(); message.User.Name = jData["user"]["real_name"].Value <string>(); message.User.ImageUrl = jData["user"]["profile"]["image_192"].Value <string>(); } if (jObject["bot_id"] != null && jObject["username"] != null) { message.User.ID = jObject["bot_id"].Value <string>(); message.User.IsBot = true; message.User.Name = jObject["username"].Value <string>(); if (!string.IsNullOrEmpty(message.User.ID) && !UserNameCache.ContainsKey(message.User.ID)) { UserNameCache.Add(message.User.ID, message.User.Name); } } if (jObject["attachments"] != null) { List <string> msg = new List <string>(); foreach (JObject attachment in jObject["attachments"]) { SlackAttachment sla = new SlackAttachment() { Fallback = attachment["fallback"] != null ? attachment["fallback"].Value <string>() : string.Empty, ColorHex = attachment["color"] != null ? attachment["color"].Value <string>(): string.Empty, Text = attachment["text"] != null ? attachment["text"].Value <string>() : string.Empty, Title = attachment["title"] != null? attachment["title"].Value <string>(): string.Empty, }; message.Attachments.Add(sla); msg.Add(sla.Title); msg.Add(sla.Text); } if (string.IsNullOrEmpty(message.Text)) { message.Text = string.Empty; } message.Text += string.Join(Environment.NewLine, msg); } if (jObject["files"] != null) { foreach (JObject file in jObject["files"]) { message.Files.Add(new SlackFile() { Id = file["id"]?.Value <string>() ?? string.Empty, Name = file["name"]?.Value <string>() ?? string.Empty, Title = file["title"]?.Value <string>() ?? string.Empty, Filetype = file["filetype"]?.Value <string>() ?? string.Empty, Mimetype = file["mimetype"]?.Value <string>() ?? string.Empty, Size = file["size"]?.Value <int>() ?? 0, Permalink = file["permalink"]?.Value <string>() ?? string.Empty, Url_private = file["url_private"]?.Value <string>() ?? string.Empty }); } } // check to see if bot has been mentioned if (message.Text != null && Regex.IsMatch(message.Text, BotNameRegex, RegexOptions.IgnoreCase)) { message.MentionsBot = true; } context = new ResponseContext() { BotHasResponded = false, BotUserID = UserID, BotUserName = UserName, Message = message, TeamID = this.TeamID, UserNameCache = new ReadOnlyDictionary <string, string>(this.UserNameCache), }; // if the end dev has added any static entries to the ResponseContext collection of Bot, add them to the context being passed to the responders. if (ResponseContext != null) { foreach (string key in ResponseContext.Keys) { context.Set(key, ResponseContext[key]); } } } catch (Exception ee) { BotMessage errorMessage = new BotMessage() { ChatHub = message.ChatHub, Text = "ERROR parsing message : " + ee.Message + " " + ee.StackTrace }; logger.Error(errorMessage.Text); if (errorChannel != null) { //TODO //await Say(errorMessage); } } try { // Avoid to answer to yourself if (context != null && context.Message != null && context.Message.Text != null && !string.IsNullOrEmpty(context.Message.User.ID) && context.Message.User.ID != context.BotUserID) { foreach (IResponder responder in Responders) { if (responder.CanRespond(context)) { await Say(responder.GetResponse(context), context); context.BotHasResponded = true; } } } } catch (Exception ee) { BotMessage errorMessage = new BotMessage() { ChatHub = message.ChatHub, Text = "ERROR in responder: " + ee.Message + " " + ee.StackTrace }; logger.Error(errorMessage.Text); if (errorChannel != null) { //TODO //await Say(errorMessage); } } try { RaiseMessageReceived(context); } catch (Exception ee) { BotMessage errorMessage = new BotMessage() { ChatHub = message.ChatHub, Text = "ERROR with Message received event: " + ee.Message + " " + ee.StackTrace }; logger.Error(errorMessage.Text); if (errorChannel != null) { //TODO //await Say(errorMessage); } } } }