public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                var builder = new StringBuilder();
                builder.Append("Fine Count:\n");

                var slackUserIds = context.Message.GetSlackIdsFromMessageExcluding(context.BotUserID);

                if (!slackUserIds.Any())
                {
                    slackUserIds.Add(context.Message.User.FormattedUserID);
                }

                foreach (var slackUserId in slackUserIds)
                {
                    var user = userApi.GetUserBySlackId(slackUserId);
                    var userFineCount = userApi.GetSuccessfullyIssuedFineCountForUser(user.Id);

                    builder.Append(slackUserId);
                    builder.Append(" - ");
                    builder.Append(userFineCount);
                    builder.Append("\n");
                }

                return new BotMessage{ Text = builder.ToString() };
            }
            catch (Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                const string reason = "for a common reply";

                if(context.Message.Text.Contains("it works on my machine"))
                {
                    reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "itworksonmymachine", context.Message.GetChannelId(), context.Message.GetTimeStamp());
                }
                var issuer = userApi.GetUserBySlackId(context.FormattedBotUserID());
                var recipient = userApi.GetUserBySlackId(context.Message.User.FormattedUserID);
                var seconderSlackId = context.GetSecondCousinSlackId();
                if (seconderSlackId.Equals("")) seconderSlackId = recipient.SlackId;
                var seconder = userApi.GetUserBySlackId(seconderSlackId);

                fineApi.IssueAutoFine(issuer.Id, recipient.Id, seconder.Id, reason);

                reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "fine", context.Message.GetChannelId(), context.Message.GetTimeStamp());
                reactionApi.AddReaction(ConfigurationManager.AppSettings["SeconderBotKey"], "fine", context.Message.GetChannelId(), context.Message.GetTimeStamp());

                return new BotMessage { Text = ""};
            }
            catch(Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
 public virtual bool CanRespond(ResponseContext context)
 {
     return
         commandPattern.IsMatch(context.Message.Text) && //  Must match command regex.
         !context.Message.User.IsSlackbot && // Message must be said by a non-bot.
         context.Message.MentionsBot; // Message must mention the bot.
 }
 public bool CanRespond(ResponseContext context)
 {
     return
         context.Message.MentionsBot &&
         !context.Message.User.IsSlackbot &&
         context.Message.Text.Contains("help");
 }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                var slackId = context.Message.User.FormattedUserID;

                var seconder = this.userApi.GetUserBySlackId(slackId);

                var result = this.fineApi.SecondOldestPendingFine(seconder.Id);

                if (result.HasErrors || result.FineWithUserModel == null)
                {
                    return this.GetErrorResponse(result, context.Message);
                }

                var secondedFine = result.FineWithUserModel;

                var finedUser = this.GetUserName(secondedFine);

                reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "ok_hand", context.Message.GetChannelId(), context.Message.GetTimeStamp());

                return new BotMessage{ Text = "" };
            }
            catch (Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
 public override bool CanRespond(ResponseContext context)
 {
     return (context.Message.MentionsBot
             || context.Message.IsDirectMessage()) &&
            (Regex.IsMatch(context.Message.Text, SingleDayRegex, RegexOptions.IgnoreCase)
             || Regex.IsMatch(context.Message.Text, SingleDayRegex, RegexOptions.IgnoreCase));
 }
        public override BotMessage GetResponse(ResponseContext context)
        {
            Context = context;

            var match = Regex.Match(Context.Message.Text, HighScoreRegex, RegexOptions.IgnoreCase);
            _gameName = match.Groups[GameNameKey].Value.IsNullOrEmpty()
                        ? String.Empty
                        : match.Groups[GameNameKey].Value;

            string messageText;
            using (var session = DocumentStore.OpenSession())
            {
                if (_gameName.IsNullOrEmpty())
                {
                    var lists = session.Query<HighScore>().ToList();

                    if (!lists.Any())
                        return new BotMessage { Text = "Jag hittar tyvärr inte en enda lista med poäng." };

                    messageText = BuildMultipleListsTextMessage(lists);
                }
                else
                {
                    var hs = session.Query<HighScore>()
                                    .FirstOrDefault(x => x.Name.Equals(_gameName, StringComparison.InvariantCultureIgnoreCase));

                    if (hs == null)
                        return new BotMessage { Text = "Jag har ingen lista som heter så." };

                    messageText = BuildSingleListTestMessage(hs);
                }
            }

            return new BotMessage { Text = messageText };
        }
 public bool CanRespond(ResponseContext context)
 {
     return !context.BotHasResponded
            && context.Message.MentionsBot
            && context.Message.Text.ToLower().Contains("fine count")
            && !context.Message.Text.ToLower().Contains("all");
 }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                var youtubeLinkList = context.Message.GetYouTubeLinkList();
                const string reason = "for sharing the following YouTube video --> ";

                var issuer = userApi.GetUserBySlackId(context.FormattedBotUserID());
                var recipient = userApi.GetUserBySlackId(context.Message.User.FormattedUserID);
                var seconderSlackId = context.GetSecondCousinSlackId();
                if (seconderSlackId.Equals("")) seconderSlackId = recipient.SlackId;
                var seconder = userApi.GetUserBySlackId(seconderSlackId);

                for (var i = 0; i < youtubeLinkList.Count; i++)
                {
                    fineApi.IssueAutoFine(issuer.Id, recipient.Id, seconder.Id, reason + youtubeLinkList[i]);
                }

                reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "fine", context.Message.GetChannelId(), context.Message.GetTimeStamp());
                reactionApi.AddReaction(ConfigurationManager.AppSettings["SeconderBotKey"], "fine", context.Message.GetChannelId(), context.Message.GetTimeStamp());

                return new BotMessage { Text = "" };
            }
            catch (Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            var match = commandPattern.Match(context.Message.Text);

            using (var db = new DatabaseContext())
            {
                var newBeef = new BeefEntry();
                newBeef.ReportedOn = DateTimeOffset.UtcNow;

                var internalMessageUserId = context.Message.User.ID;
                var reportedByUserName = context.UserNameCache[internalMessageUserId];

                newBeef.ReporterUserId = reportedByUserName;
                newBeef.ExpiresOn = DetermineExpirationDate(match);
                newBeef.OffendingChatUserId = match.Groups[4].Value.Parse<int>();
                newBeef.Explination = match.Groups[5].Value;

                db.BeefEntries.Add(newBeef);
                db.SaveChanges();
            }

            return new BotMessage
            {
                Text = "Saved beef entry."
            };
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                List<string> slackIds = context.Message.GetSlackIdsFromMessage();

                if (slackIds.Any(x => x.Equals(context.FormattedBotUserID())))
                {
                    reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "middle_finger", context.Message.GetChannelId(), context.Message.GetTimeStamp());
                    return new BotMessage {Text = ""};
                }

                if (slackIds.Count == 0)
                {
                    reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "raised_hand", context.Message.GetChannelId(), context.Message.GetTimeStamp());
                    return new BotMessage { Text = "" };
                }

                var issuer = this.GetIssuer(context);

                string reason = this.GetReason(context);

                BotMessage botMessage = this.FineRecipients(slackIds, issuer, reason, context.Message);

                return botMessage;
            } catch (Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            using (var db = new DatabaseContext())
            {
                var currentBeefEntries = db.BeefEntries
                    .Where(x => x.ExpiresOn > DateTimeOffset.UtcNow)
                    .OrderBy(x => x.ReportedOn)
                    .ToList();

                var resultsTable = currentBeefEntries
                    .ToStringTable(
                        new[]
                        {
                            "Offending Member",
                            "Reported By",
                            "Reported On",
                            "Expires On"
                        },
                        x => x.OffendingChatUserId,
                        x => x.ReporterUserId,
                        x => x.ReportedOn.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"),
                        x => x.ExpiresOn.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"));

                var outputMessage = $"Current beefs:{Environment.NewLine}```{resultsTable}```";

                return new BotMessage()
                {
                    Text = outputMessage
                };
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            using (var db = new DatabaseContext())
            {
                var currentBeefEntries = db.BeefEntries
                    .Where(x => x.ExpiresOn > DateTimeOffset.UtcNow)
                    .OrderBy(x => x.ReportedOn)
                    .ToList();

                var resultsTable = currentBeefEntries
                    .ToStringTable(
                        new[]
                        {
                            "Id",
                            "Offender",
                            "Reported By",
                            "Reported On",
                            "Expires On",
                            "Explanation"
                        },
                        x => x.Id,
                        x => $"{SOChatAccessor.GetUserNameForChatId(x.OffendingChatUserId)} ({x.OffendingChatUserId})",
                        x => x.ReporterUserId,
                        x => x.ReportedOn.ToString("yyyy-MM-dd HH:mm 'UTC'"),
                        x => x.ExpiresOn.ToString("yyyy-MM-dd HH:mm 'UTC'"),
                        x => x.ShortExplanation);

                var outputMessage = $"Current beefs:{Environment.NewLine}```{resultsTable}```";

                return new BotMessage()
                {
                    Text = outputMessage
                };
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            BotMessage message = new BotMessage();
            if (context.Message.Text == m_RegisterMessage)
            {
                //register
                try
                {
                    m_Bot.AddRegisteredUser(context.Message.User);
                    message.Text = "You've been added.";
                }
                catch(DuplicateUserException ex)
                {
                    message.Text = "You're already registered!";
                }

            }
            else if (context.Message.Text == m_UnregisterMessage)
            {
                //unregister
                try
                {
                    m_Bot.RemoveRegisteredUser(context.Message.User);
                    message.Text = "You've been removed";
                }
                catch(UserNotPresentException ex)
                {
                    message.Text = "Name not found. Do not need to unregister.";
                }
            }
            return message;
        }
Exemple #15
0
        public bool CanRespond(ResponseContext context)
        {
            //TODO: don't respond to bots - needs context.Message.User.isBot property

            Debug.WriteLine("Message '"+ context.Message.Text + "' respondable: " + context.Message.Text.StartsWith("!quote"));
            return context.Message.Text.StartsWith("!quote");
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                var user = this.userApi.GetUserBySlackId(context.Message.User.FormattedUserID);

                var supportTypes = String.Join("|", Enum.GetNames(typeof(SupportType)));

                Regex regex = new Regex(String.Format("support ({0}) (.*)", supportTypes), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                var match = regex.Match(context.Message.Text);

                if(match.Groups.Count > 2)
                {
                    this.LogSupportTicketWithType(match, user);
                }
                else
                {
                    var message = context.Message.Text.Replace("support", "");

                    this.LogSupportTicket(user, message, SupportType.General);
                }

                return new BotMessage()
                       {
                           Text = "A support ticket has been created for your issue."
                       };
            }
            catch(Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
 public bool CanRespond(ResponseContext context)
 {
     return
         context.Message.Text.ToLower() == "beef current" &&
         !context.Message.User.IsSlackbot && // Message must be said by a non-bot.
         context.Message.MentionsBot; // Message must mention the bot.
 }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {
                var user = this.GetUser(context);

                var payer = this.userApi.GetUserBySlackId(context.Message.User.FormattedUserID);

                var number = this.GetNumberOfFinesPaid(context);

                PaymentImageModel paymentImage = this.GetImage(context.Message);

                if(paymentImage == null)
                {
                    return this.GetErrorResponse(new ValidationResult().AddMessage(Severity.Error, "You must upload an image to pay fines!"), context.Message);
                }

                ValidationResult result = this.fineApi.PayFines(user.Id, payer.Id, number, paymentImage);

                if(result.HasErrors)
                {
                    return this.GetErrorResponse(result, context.Message);
                }

                string s = Convert.ToInt32(number) > 1 ? "s" : string.Empty;

                reactionApi.AddReaction(ConfigurationManager.AppSettings["BotKey"], "ok_hand", context.Message.GetChannelId(), context.Message.GetTimeStamp());

                return new BotMessage { Text = "" };
            }
            catch(Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
        public override BotMessage GetResponse(ResponseContext context)
        {
            var offendingUserId = commandPattern.Match(context.Message.Text).Groups[1].Value.Parse<int>();

            using (var db = new DatabaseContext())
            {
                var dbEntriesForUser = db.BeefEntries
                    .Where(x => x.OffendingChatUserId == offendingUserId)
                    .Where(x => x.ExpiresOn > DateTimeOffset.UtcNow) //only get ones that are active
                    .OrderBy(x => x.ReportedOn)
                    .ToList();

                string outputMessage = "";

                if (!dbEntriesForUser.Any())
                {
                    outputMessage = "This user has no active beefs.";
                }
                else
                {
                    foreach (var dbEntry in dbEntriesForUser)
                    {
                        outputMessage += $"Closing beef #{dbEntry.Id}.\n";
                        dbEntry.ExpiresOn = DateTimeOffset.UtcNow;
                    }

                    db.SaveChanges();
                }

                return new BotMessage
                {
                    Text = outputMessage
                };
            }
        }
Exemple #20
0
        public BotMessage GetResponse(ResponseContext context)
        {
            Debug.WriteLine("Raw json data: "+context.Message.RawData);

            //Timezone adjustments for file logging is done here since files = frontend
            string logmsg = " [" + TimeZoneInfo.ConvertTimeFromUtc(context.Message.TimeStamp, fileLogTimeZone).ToString("dd/MM/yyyy HH:mm:ss") + "] "
                + "<" + context.UserNameCache[context.Message.User.ID] + "> "
                + context.Message.Text;

            Debug.WriteLine(context.Message.ChatHub.Name //Name includes #
                + logmsg);

            string filename = context.Message.TimeStamp.ToString("yyyy-MM-dd") + "_" + context.Message.ChatHub.Name + ".txt";
            string dir = context.Message.TimeStamp.ToString("yyyyMM");
            string path = System.IO.Path.Combine(dir, filename);

            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);

            using (StreamWriter outfile = File.AppendText(path))
            {
                outfile.WriteLine(logmsg);
            }

            addMessageToDb(context);

            return new BotMessage(); //empty response doesn't say anything
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            try
            {

                if (context.Message.Text.ToLower().Contains("pending"))
                {
                    var fines = from user in this.userApi.GetUsersWithPendingFines()
                                from fine in user.Fines
                                where fine.Pending
                                select new { user, fine };

                    StringBuilder builder = new StringBuilder();

                    builder.AppendLine("Pending Fines:");
                    builder.AppendLine("--------------------");

                    foreach (var userModel in fines)
                    {
                        builder.AppendLine(String.Format("{0} {1}", userModel.user.SlackId.FormatAsSlackUserId(), userModel.fine.Reason));
                    }

                    return new BotMessage { Text = builder.ToString() };
                }

                return new BotMessage { Text = "Show what?" };
            }
            catch (Exception ex)
            {
                return this.GetExceptionResponse(ex, context.Message);
            }
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            string city = Regex.Match(context.Message.Text, WEATHER_LOCATIONTERM_REGEX).Groups["cityTerm"].Value;
            string state = Regex.Match(context.Message.Text, WEATHER_LOCATIONTERM_REGEX).Groups["stateTerm"].Value;
            string weatherReport = string.Empty;

            if (!string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(state))
            {
                if (WeatherLookupCache.ContainsKey(city + state))
                {
                    WeatherLookupCache.TryGetValue(city + state, out weatherReport);
                }

                JObject jData = null;

                if (!string.IsNullOrEmpty(weatherReport))
                {
                    jData = JObject.Parse(weatherReport);

                    DateTime weatherReportAgeDateTimeStamp = jData["current_observation"]["local_time_rfc822"].Value<DateTime>();

                    if (weatherReportAgeDateTimeStamp < DateTime.Now.AddMinutes(-10))
                    {
                        WeatherLookupCache.Remove(city + state);

                        weatherReport = GetWeatherReport(city, state);

                        WeatherLookupCache.Add(city + state, weatherReport);
                    }
                }
                else
                {
                    weatherReport = GetWeatherReport(city, state);

                    WeatherLookupCache.Add(city + state, weatherReport);
                }

                if(jData == null)
                {
                    jData = JObject.Parse(weatherReport);
                }

                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." };
                }
            }
            else
            {
                // Default respone when request is not both a city and state
                return new BotMessage() { Text = "Shucks, hun. I don't think I understood. Can you try again? Make sure to tell me what city and state you want to hear about the weather from!" };
            }
        }
        public bool CanRespond(ResponseContext context)
        {
            var command = context.GetCommandMentioningBot("help");

            return context.Message.MentionsBot
                && !context.BotHasResponded
                && context.Message.Text.ToLower().Contains(command.ToLower());
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            if (GetResponseFunctions.Count == 0) {
                throw new InvalidOperationException("Attempted to get a response for \"" + context.Message.Text + "\", but no valid responses have been registered.");
            }

            return GetResponseFunctions[new Random().Next(GetResponseFunctions.Count - 1)](context);
        }
        public override BotMessage GetResponse(ResponseContext context)
        {
            Context = context;

            var invMan = new InventoryManager(Context);
            var userInv = invMan.GetUserInventory();

            if(userInv.BEK < GameCost)
                return new BotMessage{Text = PhraseBook.GetInsufficientFundsFormat().With(GameCost)};

            userInv.BEK -= GameCost;
            invMan.Save(userInv);

            var game = new Game();
            var score = game.Play();

            decimal payout;
            int outcome;
            using (var session = DocumentStore.OpenSession())
            {
                var pot = session.Query<MoneyPot>().FirstOrDefault(x => x.Name == GameKey) ?? new MoneyPot { Name = GameKey };
                pot.BEK += Math.Round(GameCost * PotPercentage,2);

                var highScore = session.Query<HighScore>().FirstOrDefault(x => x.Name == GameKey) ?? new HighScore { Name = GameKey };
                outcome = highScore.TryAddNewScore(new Score { UserId = userInv.UserId, Value = score });

                if (outcome < 1)
                {
                    session.Store(pot);
                    session.SaveChanges();
                    return new BotMessage { Text = PhraseBook.GetDidntMakeHighScoreFormat().With(score) };
                }

                payout = Math.Round(PayoutDictionary[outcome] * pot.BEK,2)+GameCost;
                pot.BEK -= payout;
                userInv.BEK += payout;

                session.Store(pot);
                session.Store(highScore);
                session.SaveChanges();
            }

            invMan.Save(userInv);

            var channelNames = context.Get<Dictionary<string, string>>(Keys.StaticContextKeys.ChannelsNameCache);
            SecondaryMessageResponder.Message = new BotMessage
            {
                ChatHub = new SlackChatHub{ID = channelNames.First(x=>x.Value=="general").Key},
                Text = PhraseBook.GetNewHighscoreFormat().With(GameKey, context.UserNameCache[context.Message.User.ID], outcome)
            };

            return new BotMessage
            {
                Text ="{0} {1}".With(
                        PhraseBook.GetPotPayoutFormat().With(score, outcome, payout),
                        PhraseBook.GetExclamation())
            };
        }
        public HttpListenerConnectionContext(ServerContext server, HttpListenerContext httpContext, DateTime acceptedAt)
        {
            _server = server;
            _httpContext = httpContext;
            _acceptedAt = acceptedAt;

            _request = new HttpListenerRequestContext(httpContext.Request);
            _response = new HttpListenerResponseContext(httpContext.Response);
        }
        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)
            };
        }
Exemple #28
0
 public bool CanRespond(ResponseContext context)
 {
     if (context.Message.ChatHub.ID.ToString() == "C08HQHX32" && !context.BotHasResponded) {
         Program.resetTimer();
         Program.postCount = 0;
         Console.WriteLine("Someone posted at " + DateTime.Now.ToString("h:mm tt") + ", " + Program.nextPost());
         //if bot is mentioned meow
     }
     return false;
 }
        public BotMessage GetResponse(ResponseContext context)
        {
            var builder = new StringBuilder();
            builder.Append("Hello ");
            builder.Append(context.Message.User.FormattedUserID);

            chatApi.PostMessage(ConfigurationManager.AppSettings["SlackBotApiToken"], context.Message.User.ID, "hello dm");

            return new BotMessage { Text = builder.ToString() };
        }
 public bool CanRespond(ResponseContext context)
 {
     return !context.BotHasResponded
            && context.Message.MentionsBot
            && (     context.Message.MatchesRegEx(@"pay [0-9]+ fines for")
                  || context.Message.MatchesRegEx(@"pay [0-9]+ fine for")
                  || context.Message.MatchesRegEx(@"pay [0-9]+ for")
                  || context.Message.MatchesRegEx(@"pay fine for")
                  );
 }
Exemple #31
0
 public bool CanRespond(ResponseContext context)
 {
     return((context.Message.ChatHub.Type == SlackChatHubType.DM || context.Message.MentionsBot) && (Regex.IsMatch(context.Message.Text, WIKI_MULTIWORD_REGEX) || Regex.IsMatch(context.Message.Text, WIKI_SINGLEWORD_REGEX)));
 }
Exemple #32
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext == null || actionContext.Request == null || actionContext.Request.RequestUri == null)
            {
                return;
            }

            //如果header中没有密钥则返回错误
            if (isCheckSecret)
            {
                string secret = ConfigurationManager.AppSettings["AppVisitSecret"];
                if (!string.IsNullOrEmpty(secret))
                {
                    IEnumerable <string> headers;
                    if (!actionContext.Request.Headers.TryGetValues("secret", out headers))
                    {
                        actionContext.Response = GernalUnauthorizedResponse(actionContext, ErrCode.Unauthorized);
                        return;
                    }
                    if (headers.Count() == 0 || headers.FirstOrDefault() != secret)
                    {
                        actionContext.Response = GernalUnauthorizedResponse(actionContext, ErrCode.Unauthorized);
                        return;
                    }
                }
            }

            var requestHead = actionContext.Request.GetRequestHead(actionContext);
            //IEnumerable<string> tokens;
            //var tokensExist=actionContext.Request.Headers.TryGetValues("token", out tokens);
            //if (tokensExist)
            //{
            //    token = tokens.FirstOrDefault();
            //}
            string token        = requestHead?.Token;
            bool   isTokenEmpty = string.IsNullOrEmpty(token);

            if (isTokenEmpty && isDoCheck)
            {
                ResponseContext result = new ResponseContext();
                result.Head.Ret        = -1;
                result.Head.Code       = ErrCode.TokenIsNotAllowedEmpty;
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, result);
                return;
            }
            if (!isTokenEmpty)
            {
                bool isExist = TokenSrv.IsTokenExist(token);
                if (!isExist)
                {
                    if (isDoCheck)
                    {
                        ResponseContext result = new ResponseContext();
                        result.Head.Ret  = -1;
                        result.Head.Code = ErrCode.TokenPastDue;
                        //if (TokenSrv.IsOtherWhereLogin(token))
                        //{
                        //    result.Head.Msg = "您的帐号已在其他地方登录,请重新登录!";
                        //}
                        actionContext.Response = GernalUnauthorizedResponse(actionContext, result);
                        base.OnActionExecuting(actionContext);
                        return;
                    }
                }
            }
            base.OnActionExecuting(actionContext);
        }
Exemple #33
0
        public bool CanRespond(ResponseContext context)
        {
            var message = context.Message;

            return(message.Message.StartsWith(GiphyCommand) && !message.Message.Equals(GiphyCommand));
        }
 public bool CanRespond(ResponseContext context)
 {
     return(context.Message.Text.ToLower().Contains("hello"));
 }
Exemple #35
0
 public void ResponseReady(ResponseContext response)
 {
     Test.StatusCodes.Add(response.Response.StatusCode);
 }
 public bool CanRespond(ResponseContext context)
 {
     return((context.Message.MentionsBot || context.Message.ChatHub.Type == SlackChatHubType.DM) &&
            (Regex.IsMatch(context.Message.Text, WEATHER_NOTERM_REGEX) || Regex.IsMatch(context.Message.Text, WEATHER_LOCATIONTERM_REGEX)));
 }
        /// <summary>
        /// Gets the channel data records for the specified data object URI and range.
        /// </summary>
        /// <param name="uri">The parent data object URI.</param>
        /// <param name="range">The data range to retrieve.</param>
        /// <param name="mnemonics">The mnemonics to fetch channel data for.
        /// This list will be modified to contain only those mnemonics that data was returned for.</param>
        /// <param name="requestLatestValues">The total number of requested latest values.</param>
        /// <param name="optimizeStart">if set to <c>true</c> start range can be optimized.</param>
        /// <returns>A collection of channel data.</returns>
        public List <List <List <object> > > GetChannelData(EtpUri uri, Range <double?> range, List <string> mnemonics, int?requestLatestValues, bool optimizeStart = false)
        {
            Logger.Debug($"Getting channel data for URI: {uri}");
            List <List <List <object> > > logData;

            var entity         = GetEntity(uri);
            var queryMnemonics = new HashSet <string>(mnemonics, StringComparer.InvariantCultureIgnoreCase);

            // Create a context to pass information required by the ChannelDataReader.
            var context = new ResponseContext()
            {
                RequestLatestValues = requestLatestValues,
                MaxDataNodes        = WitsmlSettings.LogMaxDataNodesGet,
                MaxDataPoints       = WitsmlSettings.LogMaxDataPointsGet
            };

            // Get the ranges for the query mnemonics
            var curveRanges =
                GetCurrentIndexRange(entity)
                .Where(c => queryMnemonics.Contains(c.Key))
                .Select(r => r.Value).ToList();

            var indexChannel       = entity.Index.FirstOrDefault();
            var increasing         = indexChannel.IsIncreasing();
            var isTimeIndex        = entity.IsTimeIndex();
            var rangeStart         = curveRanges.GetMinRangeStart(increasing);
            var optimizeRangeStart = curveRanges.GetOptimizeRangeStart(increasing);
            var rangeEnd           = curveRanges.GetMaxRangeEnd(increasing);
            var rangeStepSize      = WitsmlSettings.GetRangeStepSize(isTimeIndex);

            bool      finished;
            const int maxRequestFactor = 3;
            var       requestFactor    = 1;

            // Try an initial optimization for non-latest values and latest values.
            if (!requestLatestValues.HasValue && optimizeStart)
            {
                // Reset the start if specified start is before the minStart
                if (rangeStart.HasValue && range.StartsBefore(rangeStart.Value, increasing))
                {
                    range = new Range <double?>(rangeStart, range.End);
                }
            }
            else if (requestLatestValues.HasValue)
            {
                range = range.OptimizeLatestValuesRange(requestLatestValues, isTimeIndex, increasing, rangeStart, optimizeRangeStart, rangeEnd, requestFactor, rangeStepSize);
            }

            do // until finished
            {
                // Retrieve the data from the database
                var records = GetChannelData(uri, indexChannel?.Mnemonic, range, increasing, requestLatestValues);

                // Get a reader to process the log's channel data records
                var reader          = records.GetReader();
                var allMnemonics    = reader.AllMnemonics;
                var mnemonicIndexes = ComputeMnemonicIndexes(entity, allMnemonics, queryMnemonics);
                var keys            = mnemonicIndexes.Keys.ToArray();
                var units           = GetUnitList(entity, keys);
                var dataTypes       = GetDataTypeList(entity, keys);
                var nullValues      = GetNullValueList(entity, keys);

                // Get the data from the reader based on the context and mnemonicIndexes (slices)
                Dictionary <string, Range <double?> > ranges;
                logData = reader.GetData(context, mnemonicIndexes, units, dataTypes, nullValues, out ranges);

                var missingMnemonics = mnemonics.Where(m => !ranges.Keys.ContainsIgnoreCase(m)).ToList();
                missingMnemonics.ForEach(m => mnemonics.Remove(m));

                // Test if we're finished reading data
                finished =                                  // Finished if...
                           !requestLatestValues.HasValue || // not request latest values
                           context.HasAllRequestedValues || // request latest values and all values returned
                           (rangeStart.HasValue &&          // query range is at start of all channel data
                            range.StartsBefore(rangeStart.Value, increasing, true)) ||
                           !range.Start.HasValue;           // query was for all data

                // If we're not finished try a bigger range
                if (!finished)
                {
                    requestFactor += 1;
                    if (requestFactor < maxRequestFactor)
                    {
                        range = range.OptimizeLatestValuesRange(requestLatestValues, isTimeIndex, increasing, rangeStart, optimizeRangeStart, rangeEnd, requestFactor, rangeStepSize);
                    }
                    else
                    {
                        // This is the final optimization and will stop the iterations after the next pass
                        range = new Range <double?>(null, null);
                    }
                }
            } while (!finished);

            return(logData);
        }
Exemple #38
0
 public bool CanRespond(ResponseContext context)
 {
     return(CanRespondFunction(context));
 }
Exemple #39
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.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 bool CanRespond(ResponseContext context)
 {
     return(context.Message.MentionsBot &&
            !context.BotHasResponded &&
            context.Message.Text.ToLower().Contains("hello"));
 }
Exemple #41
0
 public IEnumerable <IMessageResponse> GetResponse(ResponseContext context, RocketChatBot caller)
 {
     return(null);
 }
Exemple #42
0
 public bool CanRespond(ResponseContext context)
 {
     return(false);
 }
Exemple #43
0
 /// <summary>
 /// Retrieves data objects from the data store using the specified parser.
 /// </summary>
 /// <param name="parser">The query template parser.</param>
 /// <param name="context">The response context.</param>
 /// <returns>
 /// A collection of data objects retrieved from the data store.
 /// </returns>
 public override List <T> Query(WitsmlQueryParser parser, ResponseContext context)
 {
     return(QueryEntities(parser));
 }
Exemple #44
0
        public ActionResult ReadSortedResponseInfo(string formId, int?page, string sort, string sortField, int orgId, bool reset = false)
        {
            page = page.HasValue ? page.Value : 1;
            bool isMobileDevice = this.Request.Browser.IsMobileDevice;

            //Code added to retain Search Starts

            if (reset)
            {
                RemoveSessionValue(UserSession.Key.SortOrder);
                RemoveSessionValue(UserSession.Key.SortField);
            }

            if (IsSessionValueNull(UserSession.Key.ProjectId))
            {
                // This will prime the cache if the project is not already loaded into cache.
                SetSessionValue(UserSession.Key.ProjectId, _projectMetadataProvider.GetProjectId_RetrieveProjectIfNecessary());
            }

            SetSessionValue(UserSession.Key.SelectedOrgId, orgId);
            var rootFormId = GetStringSessionValue(UserSession.Key.RootFormId, defaultValue: null);

            if (rootFormId == formId)
            {
                string sessionSortOrder = GetStringSessionValue(UserSession.Key.SortOrder, defaultValue: null);
                if (!string.IsNullOrEmpty(sessionSortOrder) && string.IsNullOrEmpty(sort))
                {
                    sort = sessionSortOrder;
                }

                string sessionSortField = GetStringSessionValue(UserSession.Key.SortField, defaultValue: null);
                if (!string.IsNullOrEmpty(sessionSortField) && string.IsNullOrEmpty(sortField))
                {
                    sortField = sessionSortField;
                }

                SetSessionValue(UserSession.Key.SortOrder, sort);
                SetSessionValue(UserSession.Key.SortField, sortField);
                SetSessionValue(UserSession.Key.PageNumber, page.Value);
            }
            else
            {
                SetSessionValue(UserSession.Key.RootFormId, formId);

                ResponseContext responseContext = InitializeResponseContext(formId: formId) as ResponseContext;
                SetSessionValue(UserSession.Key.ResponseContext, responseContext);

                RemoveSessionValue(UserSession.Key.SortOrder);
                RemoveSessionValue(UserSession.Key.SortField);
                SetSessionValue(UserSession.Key.PageNumber, page.Value);
            }

            //Code added to retain Search Ends.

            var formResponseInfoModel = GetSurveyResponseInfoModel(formId, page.Value, sort, sortField, orgId);

            if (isMobileDevice == false)
            {
                return(PartialView("ListResponses", formResponseInfoModel));
            }
            else
            {
                return(View("ListResponses", formResponseInfoModel));
            }
        }
Exemple #45
0
        public static void UpdateSurveyResponse(SurveyInfoModel surveyInfoModel,
                                                MvcDynamicForms.Form form,
                                                SurveyAnswerRequest surveyAnswerRequest,
                                                SurveyResponseBuilder surveyResponseBuilder,
                                                IDataEntryService dataEntryService,
                                                SurveyAnswerResponse surveyAnswerResponse,
                                                string responseId,
                                                SurveyAnswerDTO surveyAnswerDTO,
                                                bool isSubmited,
                                                bool isSaved,
                                                int pageNumber,
                                                int orgId,
                                                int userId)
        {
            // 1 Get the record for the current survey response
            // 2 update the current survey response
            // 3 save the current survey response

            var savedResponseDetail = surveyAnswerDTO.ResponseDetail;

            if (!isSubmited)
            {
                // 2 a. update the current survey answer request
                surveyAnswerRequest.SurveyAnswerList = surveyAnswerResponse.SurveyResponseList;

                surveyResponseBuilder.Add(form);

                FormResponseDetail formResponseDetail = surveyResponseBuilder.UpdateResponseDetail(savedResponseDetail, form.CurrentPage, form.PageId);

                surveyAnswerRequest.SurveyAnswerList[0].ResponseDetail = formResponseDetail;
                // 2 b. save the current survey response
                surveyAnswerRequest.Action = RequestAction.Update;

                var currentPageNumber = form.CurrentPage;
                FormResponseDetail currentFormResponseDetail = surveyAnswerRequest.SurveyAnswerList[0].ResponseDetail;
                PageResponseDetail currentPageResponseDetail = currentFormResponseDetail.GetPageResponseDetailByPageNumber(currentPageNumber);

                var mergedResponseDetail = MergeResponseDetail(savedResponseDetail, currentPageResponseDetail);
                surveyAnswerRequest.SurveyAnswerList[0].ResponseDetail.PageIds = mergedResponseDetail.PageIds;
                // keep only the pages that have updates
                var updatedPageResponseDetailList = mergedResponseDetail.PageResponseDetailList.ToList();
                surveyAnswerRequest.SurveyAnswerList[0].ResponseDetail.PageResponseDetailList.Clear();
                surveyAnswerRequest.SurveyAnswerList[0].ResponseDetail.PageResponseDetailList.AddRange(updatedPageResponseDetailList);
            }

            var updatedFromResponseDetail = surveyAnswerRequest.SurveyAnswerList[0].ResponseDetail;

            if (updatedFromResponseDetail.UserId <= 0)
            {
                updatedFromResponseDetail.UserId = userId;
            }
            if (updatedFromResponseDetail.UserOrgId <= 0)
            {
                updatedFromResponseDetail.UserOrgId = orgId;
            }

            ////Update page number before saving response
            if (surveyAnswerRequest.SurveyAnswerList[0].CurrentPageNumber != 0)
            {
                updatedFromResponseDetail.LastPageVisited = pageNumber;
            }
            if (form.HiddenFieldsList != null)
            {
                updatedFromResponseDetail.HiddenFieldsList = form.HiddenFieldsList;
            }
            if (form.HighlightedFieldsList != null)
            {
                updatedFromResponseDetail.HighlightedFieldsList = form.HighlightedFieldsList;
            }
            if (form.DisabledFieldsList != null)
            {
                updatedFromResponseDetail.DisabledFieldsList = form.DisabledFieldsList;
            }
            if (form.RequiredFieldsList != null)
            {
                updatedFromResponseDetail.RequiredFieldsList = form.RequiredFieldsList;
            }

            //  AssignList
            List <KeyValuePair <string, string> > fieldsList = GetHiddenFieldsList(form).Where(kvp => kvp.Value != null).ToList();

            if (fieldsList.Count > 0)
            {
                var formId           = form.SurveyInfo.SurveyId;
                var metadataAccessor = form.SurveyInfo as MetadataAccessor;
                var formDigest       = metadataAccessor.GetFormDigest(formId);
                foreach (var fieldsListKvp in fieldsList)
                {
                    var fieldName          = fieldsListKvp.Key.ToLower();
                    var pageId             = formDigest.FieldNameToPageId(fieldName);
                    var pageResponseDetail = updatedFromResponseDetail.PageResponseDetailList.SingleOrDefault(p => p.PageId == pageId);
                    if (pageResponseDetail == null)
                    {
                        var pageDigest = metadataAccessor.GetPageDigestByPageId(formId, pageId);
                        pageResponseDetail = new PageResponseDetail {
                            PageId = pageId, PageNumber = pageDigest.PageNumber
                        };
                        updatedFromResponseDetail.AddPageResponseDetail(pageResponseDetail);
                    }
                    pageResponseDetail.ResponseQA[fieldName] = fieldsListKvp.Value;
                    pageResponseDetail.HasBeenUpdated        = true;
                }
            }

            if (isSaved)
            {
                surveyAnswerRequest.SurveyAnswerList[0].Status = RecordStatus.Saved;
                surveyAnswerRequest.SurveyAnswerList[0].ReasonForStatusChange = RecordStatusChangeReason.Update;
            }

            /////Update Survey Mode ////////////////////
            surveyAnswerRequest.SurveyAnswerList[0].IsDraftMode = surveyAnswerDTO.IsDraftMode;
            //surveyAnswerRequest.Criteria.UserId = UserId;
            ResponseContext responseContext = ((IResponseContext)updatedFromResponseDetail).CloneResponseContext();

            if (responseContext.UserId == 0)
            {
                responseContext.UserId = userId;
            }
            if (responseContext.UserOrgId == 0)
            {
                responseContext.UserOrgId = orgId;
            }
            surveyAnswerRequest.ResponseContext = responseContext;

            dataEntryService.SetSurveyAnswer(surveyAnswerRequest);
        }
        //public async Task SimplePostAsync(string url)
        //{
        //    Log.Information($"SIMPLE POST: {url}");
        //    //client.DefaultHeaders = DefaultHeaders;
        //    DefaultHeaders.ToList().ForEach(a => client.SetHeader(a.Key, a.Value));
        //    //client.Cookies = this.Cookies;
        //    client.SetHeader("Cookie", this.Cookies);
        //    await client.PostAsync(url, (string) null);
        //    Cookies = client.LastCookie;
        //}

        public async Task <string> RunAsync(string url)
        {
            string content = string.Empty;

            try
            {
                string rc = null;
                if (string.IsNullOrEmpty(this.HttpMethod) || this.HttpMethod == "GET")
                {
                    var ct = await cachedRequester.GetAsync(url);

                    if (ct.HasErrors)
                    {
                        throw ct.Exception;
                    }

                    rc = ct.StringContent;

                    if (ct.HasUsedCache)
                    {
                        TotalRequestCached++;
                    }
                    else
                    {
                        TotalRequestOnline++;
                    }
                }
                else if (this.HttpMethod == "POST")
                {
                    ResponseContext ct = null;
                    if (!string.IsNullOrEmpty(this.HttpBody))
                    {
                        ct = await cachedRequester.PostAsync(url, this.HttpBody);

                        if (ct.HasErrors)
                        {
                            throw ct.Exception;
                        }
                        rc = ct.StringContent;
                    }
                    else if (PostData.Any())
                    {
                        ct = await cachedRequester.PostAsync(url, this.PostData);

                        if (ct.HasErrors)
                        {
                            throw ct.Exception;
                        }
                        rc = ct.StringContent;
                    }
                    else
                    {
                        ct = await cachedRequester.PostAsync(url, string.Empty);

                        if (ct.HasErrors)
                        {
                            throw ct.Exception;
                        }
                    }

                    if (ct.HasUsedCache)
                    {
                        TotalRequestCached++;
                    }
                    else
                    {
                        TotalRequestOnline++;
                    }
                }

                content = rc;
            }
            catch (HttpRequestException ex) when(ex.Message.Contains("404"))
            {
                return(string.Empty);
            }

            return(content);
        }
        public BotMessage GetResponse(ResponseContext context)
        {
            string city          = Regex.Match(context.Message.Text, WEATHER_LOCATIONTERM_REGEX).Groups["cityTerm"].Value;
            string state         = Regex.Match(context.Message.Text, WEATHER_LOCATIONTERM_REGEX).Groups["stateTerm"].Value;
            string weatherReport = string.Empty;

            if (!string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(state))
            {
                if (WeatherLookupCache.ContainsKey(city + state))
                {
                    WeatherLookupCache.TryGetValue(city + state, out weatherReport);
                }

                JObject jData = null;

                if (!string.IsNullOrEmpty(weatherReport))
                {
                    jData = JObject.Parse(weatherReport);

                    DateTime weatherReportAgeDateTimeStamp = jData["current_observation"]["local_time_rfc822"].Value <DateTime>();

                    if (weatherReportAgeDateTimeStamp < DateTime.Now.AddMinutes(-10))
                    {
                        WeatherLookupCache.Remove(city + state);

                        weatherReport = GetWeatherReport(city, state);

                        WeatherLookupCache.Add(city + state, weatherReport);
                    }
                }
                else
                {
                    weatherReport = GetWeatherReport(city, state);

                    WeatherLookupCache.Add(city + state, weatherReport);
                }

                if (jData == null)
                {
                    jData = JObject.Parse(weatherReport);
                }

                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."
                    });
                }
            }
            else
            {
                // Default respone when request is not both a city and state
                return(new BotMessage()
                {
                    Text = "Shucks, hun. I don't think I understood. Can you try again? Make sure to tell me what city and state you want to hear about the weather from!"
                });
            }
        }
Exemple #48
0
 public TestHandlerWithResponseContext(ResponseContext responseContext) => ResponseContext = responseContext;
 public ResponsesController(ResponseContext context)
 {
     _context = context;
 }
 public bool CanRespond(ResponseContext context)
 {
     return((context.Message.MentionsBot || context.Message.ChatHub.Type == SlackChatHubType.DM) && Regex.IsMatch(context.Message.Text, @"\b(what's new)\b", RegexOptions.IgnoreCase));
 }
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="responseContext"></param>
 public ResponseContextException(ResponseContext responseContext)
 {
     ResponseContext = responseContext;
 }
 public bool CanRespond(ResponseContext context)
 {
     return((context.Message.MentionsBot || context.Message.ChatHub.Type == SlackChatHubType.DM) && Regex.IsMatch(context.Message.Text, @"\bweather\b"));
 }
 public void WhenTheFunctionToGetAreExecuted()
 {
     _responseContext = _trelloEndpoints.GetBoardsWithParticularFields(Name);
 }
 protected virtual ResponseContext <IList <K> > GetAllHATEOAS <K>(ResponseContext <IList <K> > response, int page, int?pageSize) where K : T
 {
     //return _getAllHATEOAS != null ? _getAllHATEOAS(response) : response;
     return(response);
 }
Exemple #55
0
 /// <summary>
 /// 异常响应消息
 /// </summary>
 /// <param name="actionContext"></param>
 /// <returns></returns>
 public static HttpResponseMessage GernalUnauthorizedResponse(HttpActionContext actionContext, ResponseContext respContext)
 {
     return(actionContext.Request.CreateResponse(HttpStatusCode.OK, respContext));
 }
Exemple #56
0
 private RestResponse(ResponseContext responseContext)
 {
     this.responseContext = responseContext;
 }
 public HttpValidationStatus Validate(ResponseContext response, RouteContext context)
 {
     // TODO: Implement response validator
     return(HttpValidationStatus.Success());
 }
Exemple #58
0
 public bool CanRespond(ResponseContext context)
 {
     return(context.Message.MentionsBot && Regex.IsMatch(context.Message.Text, @"\bdebug\b", RegexOptions.IgnoreCase));
 }
Exemple #59
0
 public bool CanRespond(ResponseContext context)
 {
     return((context.Message.MentionsBot || context.Message.ChatHub.Type == SlackChatHubType.DM) && Regex.IsMatch(context.Message.Text, DEFINE_REGEX));
 }
Exemple #60
0
        public BotMessage GetResponse(ResponseContext context)
        {
            // perform scoring
            List <ScoringResult> scoringResults = new List <ScoringResult>();

            // bet you anything there's a better way to do this
            Match match = Regex.Match(context.Message.Text, SCORE_REGEX);

            for (int i = 0; i < match.Groups["formattedUserID"].Captures.Count; i++)
            {
                scoringResults.Add(new ScoringResult()
                {
                    FormattedUserID = match.Groups["formattedUserID"].Captures[i].Value,
                    IsNewScorer     = !this.Scorebook.HasUserScored(match.Groups["userID"].Captures[i].Value),
                    IsValidScorer   = (match.Groups["userID"].Captures[i].Value != context.Message.User.ID),
                    UserID          = match.Groups["userID"].Captures[i].Value
                });
            }

            IList <string> newScorers   = scoringResults.Where(r => r.IsNewScorer).Select(r => r.UserID).ToList();
            IList <string> scoringUsers = scoringResults.Where(r => r.IsValidScorer).Select(r => r.UserID).ToList();
            IList <string> allUsers     = scoringResults.Select(r => r.UserID).ToList();

            // score the users and shove the scorebook into the context for use by the ScoreboardRequestResponder
            Scorebook.ScoreUsers(scoringUsers, 1);

            Phrasebook    phrasebook      = context.Get <Phrasebook>();
            StringBuilder responseBuilder = new StringBuilder();

            if (allUsers.Contains(context.Message.User.ID))
            {
                responseBuilder.Append(string.Format("Bless your heart, {0}. You can't score yourself - what kinda game would that be?! Y'all, {0} is cute, but I think he/she might be dumb as a box o' rocks.\n\n", context.Message.User.FormattedUserID));
            }

            if (scoringUsers.Count() > 0)
            {
                if (responseBuilder.Length > 0)
                {
                    responseBuilder.Append("Anyway... ");
                }

                if (scoringUsers.Count() == 1)
                {
                    if (scoringUsers[0] == context.BotUserID)
                    {
                        int margieScore = Scorebook.GetUserScore(context.BotUserID);
                        responseBuilder.Append(string.Format("Awwww, aren't you a sweetie! *[blushes]* If you insist. Now I have {0} point{1}.\n\n", margieScore, margieScore == 1 ? string.Empty : "s"));
                    }
                    else if (newScorers.Contains(scoringUsers[0]))
                    {
                        responseBuilder.Append(string.Format("A new challenger appears, y'all! {0} is on the board with a point. {1}", scoringResults.Where(r => r.UserID == scoringUsers[0]).First().FormattedUserID, phrasebook.GetAffirmation()));
                    }
                    else
                    {
                        ScoringResult scoredUser = scoringResults.Where(r => r.UserID == scoringUsers[0]).First();

                        responseBuilder.Append(
                            string.Format(
                                "{0} {1} just scored a point. {2} {1}, your score is now {3}.",
                                phrasebook.GetExclamation(),
                                scoredUser.FormattedUserID,
                                phrasebook.GetAffirmation(),
                                Scorebook.GetUserScore(scoredUser.UserID)
                                )
                            );
                    }
                }
                else
                {
                    responseBuilder.Append("There's points all over this joint, y'all. ");
                    IList <ScoringResult> scoringUserResults = scoringResults.Where(r => r.IsValidScorer).ToList();

                    if (scoringUserResults.Count == 2)
                    {
                        responseBuilder.Append(
                            string.Format(
                                "{1} and {2} each just scored a point. {3}",
                                phrasebook.GetExclamation(),
                                scoringUserResults[0].FormattedUserID,
                                scoringUserResults[1].FormattedUserID,
                                phrasebook.GetAffirmation()
                                )
                            );
                    }
                    else
                    {
                        for (int i = 0; i < scoringUserResults.Count; i++)
                        {
                            responseBuilder.Append(scoringUserResults[i].FormattedUserID);

                            if (i < scoringResults.Count - 2)
                            {
                                responseBuilder.Append(", ");
                            }
                            else if (i == scoringResults.Count - 2)
                            {
                                responseBuilder.Append(", and ");
                            }
                        }

                        responseBuilder.Append(" each just scored a point. " + phrasebook.GetExclamation());
                    }
                }
            }

            return(new BotMessage()
            {
                Text = responseBuilder.ToString().Trim()
            });
        }