Пример #1
1
        public TwiMLResult Index(SmsRequest incomingMessage)
        {
            var messagingResponse = new MessagingResponse();

            messagingResponse.Message("The Knative copy cat says: " + incomingMessage.Body);
            return(TwiML(messagingResponse));
        }
        // handles incoming messages from users
        public TwiMLResult Index(SmsRequest incomingMessage)
        {
            MessagingResponse messagingResponse = new MessagingResponse();

            switch (incomingMessage.Body.ToLower().Trim())
            {
            case "reminders":
                messagingResponse.Message("Work at 4:30PM");
                break;

            case "commands":
                messagingResponse.Message(CommandListToString());
                break;

            case "time":
                messagingResponse.Message(DateTime.Now.ToString());
                break;

            case "hello":
                messagingResponse.Message("Whats up dude?");
                break;

            default:
                messagingResponse.Message("No Command Exists");
                break;
            }
            return(TwiML(messagingResponse));
        }
        private MessagingResponse GetTwilioResponseForEmployees(IEnumerable <Employee> employees, string incomingMessageText)
        {
            var response     = new MessagingResponse();
            var employeeList = employees.ToList();

            switch (employeeList.Count)
            {
            case 0:     // No Employees Found
                response.Message(string.Format(NotFoundMessage, incomingMessageText));
                break;

            case 1:     // A Single Employee Found
                var employee = employeeList.First();
                response.Message(
                    new Message().Body(
                        employee.FullName + " - " +
                        employee.Email + " - " +
                        employee.PhoneNumber)
                    .Media(employee.ImageUrl));
                break;

            default:     // Multiple Employees Found
                response.Message(GetMessageForMultipleEmployees(employeeList));
                break;
            }

            return(response);
        }
        /// <summary>
        /// Method for receicing replies via WebHook. Configure https://yourdomain.com/ in your twilio console
        /// </summary>
        /// <param name="incomingMessage"></param>
        /// <returns></returns>

        public async Task <TwiMLResult> Index(SmsRequest incomingMessage)
        {
            //Return message
            var messagingResponse = new MessagingResponse();


            try
            {
                //Convert input to message
                var message = new MessageModel()
                {
                    To          = incomingMessage.To,
                    From        = incomingMessage.From,
                    Body        = incomingMessage.Body,
                    CreatedDate = DateTime.Now
                };

                //Process request
                var reponse = await LoanRequestService.Process(message);



                messagingResponse.Message(reponse.Body);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                messagingResponse.Message(e.Message);
            }


            return(TwiML(messagingResponse));
        }
Пример #5
0
        private TwiMLResult RegisterDevice(TwilioSmsHookModel hookModel)
        {
            var response          = new MessagingResponse();
            var data              = hookModel.Body.Split(' ');
            var devicePhoneNumber = data[1].Trim();
            var deviceNickName    = data[2].Trim().ToLower();
            var ownerPhoneNumber  = hookModel.From;

            if (_db.Trackers.Any(x => x.DeviceNickName == deviceNickName))
            {
                response.Message("A device with that name is already registered. Please use another one.");
                return(TwiML(response));
            }

            _db.Trackers.Add(new Tracker
            {
                DeviceNickName    = deviceNickName,
                DevicePhoneNumber = devicePhoneNumber,
                OwnerPhoneNumber  = ownerPhoneNumber
            });

            _db.SaveChanges();

            response.Message($"Your device {deviceNickName} with number {devicePhoneNumber} has been successfully registered");
            return(TwiML(response));
        }
Пример #6
0
        public TwiMLResult Index(SmsRequest userRequest)
        {
            var response = new MessagingResponse();

            DateTime currentDate   = DateTime.Today;
            var      currentMonth  = currentDate.Month.ToString();
            var      requestNumber = (userRequest.From).ToString().Split("+1")[1];

            var userCategory = _context.UserCategories
                               .Include(x => x.Category)
                               .Include(x => x.ApplicationUser)
                               .FirstOrDefault(x => x.Category.Name == userRequest.Body && x.ApplicationUser.PhoneNumber == requestNumber);

            var budgetedAmount  = _context.UserCategories.Where(x => x.Category.Name == userRequest.Body).Sum(y => y.BudgetedAmount);
            var actualAmount    = _context.Transaction.Where(x => x.Category.Name == userRequest.Body && x.DateOccurred.Month.ToString() == currentMonth).Sum(y => y.Amount);
            var remainingAmount = budgetedAmount - actualAmount;

            if (userCategory != null)
            {
                response.Message("You have " + remainingAmount.ToString("c") + " remaining in your " + userCategory.Category.Name + " budget.");
            }
            else
            {
                response.Message("Sorry, you got the wrong number.");
            }

            return(TwiML(response));
        }
Пример #7
0
        public TwiMLResult Index()
        {
            var   requestBody = Request.Form["Body"];
            var   response    = new MessagingResponse();
            Regex wantBuy     = new Regex(@"I want to buy\s([\w\s]+)", RegexOptions.IgnoreCase);
            Regex message     = new Regex(@"Message\s(\w+)\s", RegexOptions.IgnoreCase);
            Regex wantSell    = new Regex(@"I want to sell\s([\w\s]+)/(\d+)/(\d+)", RegexOptions.IgnoreCase);
            Regex inArea      = new Regex(@"for sale near me", RegexOptions.IgnoreCase);

            switch ("")
            {
            case var val when wantBuy.IsMatch(requestBody):
                string item = wantBuy.Match(requestBody).Groups[1].Value;

                response.Message($"The best farmer in your area that sells {item} is Farmer Jim Bo!\n" +
                                 $"Reply Message JimBo <message> to arrange your purchase!");
                break;

            case var val when message.IsMatch(requestBody):
                string user = message.Match(requestBody).Groups[1].Value;

                response.Message($"Hi! This is {user}! I would love to sell to you, come to my farm to pick up at:\n" +
                                 $"1234 Street Ave Farmington, MN 55555");
                break;

            case var val when inArea.IsMatch(requestBody):
                string resp = "";

                using (var context = new Farmazon_dbEntities())
                {
                    IList <Inventory> myItems = context.Set <Inventory>().ToList();
                    foreach (Inventory itemDB in myItems)
                    {
                        resp += $"{itemDB.ProductName.Trim()} ({itemDB.Quantity}) - ${itemDB.Price}\n";
                    }
                }
                response.Message(resp);
                break;

            case var val when wantSell.IsMatch(requestBody):
                string itemList = wantSell.Match(requestBody).Groups[1].Value;

                string quant = wantSell.Match(requestBody).Groups[2].Value;
                string price = wantSell.Match(requestBody).Groups[3].Value;
                response.Message($"Your {quant} {itemList} for ${price} have been listed!");
                break;

            default:
                response.Message("Commands: \n" +
                                 "Message <user> <message>\n" +
                                 "I want to buy <item>\n" +
                                 "For sale near me\n" +
                                 "I want to sell <item>/<count>/<price>");
                break;
            }

            return(TwiML(response));
        }
Пример #8
0
    static void Main()
    {
        var response = new MessagingResponse();

        response.Message("This is message 1 of 2.");
        response.Message("This is message 2 of 2.");

        Console.WriteLine(response.ToString());;
    }
        private MessagingResponse GenerateResponse(string data, string message, string LuisApiKey, string LuisUrlBase, string LuisAppId)
        {
            var messagingResponse = new MessagingResponse();
            var client            = new HttpClient();
            var queryString       = new NameValueCollection();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", LuisApiKey);

            queryString["query"] = message;

            queryString["verbose"]          = "true";
            queryString["show-all-intents"] = "false";
            queryString["staging"]          = "false";
            queryString["timezoneOffset"]   = "0";

            var endpointUri = String.Format("https://{0}/luis/prediction/v3.0/apps/{1}/slots/production/predict?{2}", LuisUrlBase, LuisAppId, queryString);

            var response = client.GetAsync(endpointUri).Result;

            var strResponseContent = response.Content.ReadAsStringAsync().Result;

            var respuesta = JsonConvert.DeserializeObject <LUISResponse>(strResponseContent);

            if (respuesta != null && respuesta.prediction != null)
            {
                IntentResponse intentResponse = new IntentResponse(data, respuesta.prediction.topIntent);
                if (intentResponse != null)
                {
                    if (respuesta.prediction.sentiment != null && respuesta.prediction.sentiment.label == "negative" && intentResponse.NegativeFeelingResponse != null)
                    {
                        foreach (var botRespuesta in intentResponse.NegativeFeelingResponse)
                        {
                            messagingResponse.Message(botRespuesta);
                        }
                    }
                    else
                    {
                        foreach (var botRespuesta in intentResponse.NormalFeelingResponse)
                        {
                            messagingResponse.Message(botRespuesta);
                        }
                    }
                }
                else
                {
                    messagingResponse.Message("Sorry, I don't have an answer loaded for your request.");
                }
            }
            else
            {
                messagingResponse.Message("Sorry, I had an internal error. I will fix it soon.");
            }
            return(messagingResponse);
        }
Пример #10
0
        public IActionResult ReceiveSms()
        {
            // get text body
            string requestBody = Request.Form["Body"];
            // get user phone
            string inboundPhone = Request.Form["From"];
            // create new response
            var response = new MessagingResponse();

            var user = _userRepo.GetByPhoneNumber(inboundPhone);

            user.ContactMessage = requestBody;

            //logs inbound message in database
            UserMessage message = new UserMessage()
            {
                UserId  = user.Id,
                Message = requestBody
            };

            _messageRepo.Add(message);


            if (user == null)
            {
                response.Message("Sorry, but we don't have a user in our database with this number. If you are a user please check your Struggle Bus account.");
                return(TwiML(response));
            }

            switch (requestBody.ToUpper())
            {
            case "TEST":

                response.Message("Testing...1...2...3...");
                return(TwiML(response));

            case "OPTIONS":

                response.Message(@"Thanks for asking.
                        1) Send TEST any time you want to test connectivity.
                        2) Send OPTIONS to get this menu.
                        3) Send anything else to get a check in.");
                return(TwiML(response));;

            default:
                response.Message($"Thanks for reaching out {user.FirstName}. You've been heard, and we're passing along the word.");
                SendSms(user);
                return(TwiML(response));
            }
        }
Пример #11
0
        public async Task <TwiMLResult> Store()
        {
            var twilioConfig = _config.GetSection("Twilio");

            if (Request == null ||
                Request.Form == null ||
                !Request.Form.ContainsKey("AccountSID") ||
                Request.Form["AccountSID"] != twilioConfig["AccountSID"] ||
                !Request.Form.ContainsKey("From") ||
                !Request.Form.ContainsKey("Body"))
            {
                return(null);
            }


            var sender = Request.Form["From"].Single();
            var body   = Request.Form["Body"].Single();


            var message = MessageHelper.ParseMessage(body);

            var messagingResponse = new MessagingResponse();

            if (message == null)
            {
                messagingResponse.Message("Message has invalid format. Use {country},{license plate},{your message}");
                return(new TwiMLResult(messagingResponse));
            }

            message.SenderId = sender;

            // check country
            if (!PredefinedConstants.Countries.Contains(message.CountryCode))
            {
                messagingResponse.Message($"Country code {message.CountryCode} is either misformated or unsupported");
                return(new TwiMLResult(messagingResponse));
            }

            // check licensePlate
            if (PredefinedConstants.PlateRegex.ContainsKey(message.CountryCode) && !Regex.IsMatch(message.LicensePlate, PredefinedConstants.PlateRegex[message.CountryCode]))
            {
                messagingResponse.Message($"License plate {message.LicensePlate} is not a valid {message.CountryCode} plate.");
                return(new TwiMLResult(messagingResponse));
            }

            await _service.Store(message);

            return(new TwiMLResult());
        }
Пример #12
0
    public ActionResult Index()
    {
        const string requestBody = Request.Form["Body"];
        var          response    = new MessagingResponse();

        if (requestBody == "hello")
        {
            response.Message("Hi!");
        }
        else if (requestBody == "bye")
        {
            response.Message("Goodbye");
        }
        return(Content(response.ToString(), "text/xml"));
    }
Пример #13
0
        public ActionResult ReceiveSms()
        {
            var requestBody = Request.Form["body"];
            var response    = new MessagingResponse();

            if (requestBody == Request.Form["body"])
            {
                response.Message("Thanks for signing up!");
            }
            else
            {
                response.Message("Uncorrect code");
            }
            return(TwiML(response));
        }
Пример #14
0
        public IActionResult Index(string body)
        {
            var method = body.Split(' ')[0];

            switch (method.ToLower())
            {
            case "add":
                Database.ToDos.Add(body.Replace("add ", "").Replace("Add ", ""));
                break;

            case "remove":
                Database.ToDos.Remove(body.Replace("remove ", "").Replace("Remove ", ""));
                break;

            case "list":
                var sb = new StringBuilder();
                for (var i = 1; i <= Database.ToDos.Count; i++)
                {
                    sb.AppendLine($"{i} {Database.ToDos[i - 1]}");
                }

                var messagingResponse = new MessagingResponse();
                messagingResponse.Message(
                    sb.ToString(),
                    statusCallback: new Uri("http://3f52b400.ngrok.io/status"));
                return(TwiML(messagingResponse));
            }

            return(Ok());
        }
Пример #15
0
    public ActionResult Index()
    {
        var counter = Session["counter"] != null ? (int)Session["counter"] : 0;

        // increment it
        counter++;

        // save it
        Session["counter"] = counter;

        // make an associative array of senders we know, indexed by phone number
        var people = new Dictionary <string, string>()
        {
            { "+14158675308", "Curious George" },
            { "+12349013030", "Boots" },
            { "+12348134522", "Virgil" }
        };

        // if the sender is known, then greet them by name
        var name = people.ContainsKey(Request.Form["From"])
            ? people[Request.Form["From"]]
            : "Monkey";
        var to = Request.Form["To"];

        var response = new MessagingResponse();

        response.Message($"{name} has messaged {to} {counter} times");

        return(TwiML(response));
    }
Пример #16
0
        private TwiMLResult SendMessagingResponse(string message)
        {
            var messagingResponse = new MessagingResponse();

            messagingResponse.Message(message);
            return(TwiML(messagingResponse));
        }
Пример #17
0
        public ActionResult SendMessage(string message)
        {
            MessagingResponse Message = new MessagingResponse();

            Message.Message(message);
            return(TwiML(Message));
        }
Пример #18
0
        public ActionResult ReceiveSms()
        {
            var requestBody = Request.Form["Body"];
            var response    = new MessagingResponse();

            if (requestBody == "hello")
            {
                response.Message("Gracias por confirmar!");
            }
            else if (requestBody == "bye")
            {
                response.Message("Goodbye");
            }

            return(TwiML(response));
        }
Пример #19
0
        public TwiMLResult Index()
        {
            var response = new MessagingResponse();

            response.Message("Welcome!!!");
            return(TwiML(response));
        }
Пример #20
0
        public TwiMLResult ReceiveSMS(SmsRequest incomingMessage)
        {
            var messagingResponse = new MessagingResponse();

            messagingResponse.Message("The Magic 8 Ball has decided your question is worthy. To hear the answer, call +1PhoneNumber");
            return(TwiML(messagingResponse));
        }
Пример #21
0
        public TwiMLResult Index()
        {
            var messagingResponse = new MessagingResponse();

            messagingResponse.Message("This is an automated reply from an unmonitored number.");
            return(TwiML(messagingResponse));
        }
Пример #22
0
        public void TestMultipleMessages()
        {
            var m1 = new Message(to: "+11111111111", from: "+12222222222");

            m1.Body("foobar");
            m1.Body("barbaz");

            var m2 = new Message();

            m2.Body("barbaz2");

            var mr = new MessagingResponse();

            mr.Message(m1).Message(m2);
            Assert.AreEqual(
                mr.ToString(),
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
                "<Response>" + Environment.NewLine +
                "  <Message to=\"+11111111111\" from=\"+12222222222\">" + Environment.NewLine +
                "    <Body>foobar</Body>" + Environment.NewLine +
                "    <Body>barbaz</Body>" + Environment.NewLine +
                "  </Message>" + Environment.NewLine +
                "  <Message>" + Environment.NewLine +
                "    <Body>barbaz2</Body>" + Environment.NewLine +
                "  </Message>" + Environment.NewLine +
                "</Response>"
                );
        }
Пример #23
0
        public TwiMLResult Index(SmsRequest request)
        {
            var response = new MessagingResponse();

            response.Message("LA HACKS");
            return(TwiML(response));
        }
Пример #24
0
        public ActionResult RecieveSMSMessage(string From, string Body)
        {
            var responseMessage = new MessagingResponse();

            responseMessage.Message("Hi, Thank you for using waiter! We Apreciate your feedback :)");

            From = From.Remove(0, 2);

            TableVisit currentTableVisit = db.TableVisits
                                           .Where(r => r.DinerPhone == From)
                                           .OrderByDescending(r => r.TableVisitId)
                                           .FirstOrDefault();

            if (Body == "y")
            {
                currentTableVisit.IsSatisfied = true;
                db.SaveChanges();
                analytics.CalculateWaitRate(currentTableVisit);
            }
            if (Body == "n")
            {
                currentTableVisit.IsSatisfied = false;
                db.SaveChanges();
                analytics.CalculateWaitRate(currentTableVisit);
            }

            return(TwiML(responseMessage));
        }
        // TODO: external token/auth key - possibly
        public async Task <IActionResult> Api([Bind("ID,From,To,Body,AccountSid,ToCountry,ToState,SmsMessageSid,NumMedia,ToCity,FromZip,SmsSid,FromState,SmsStatus,FromCity,FromCountry,ToZip,NumSegments,MessageSid,ApiVersion")] IncomingMessage incomingMessage)
        {
            // default repsonse, in case no incoming POST data can be processed
            string textMessage = "Internal error. This is default fallback message.";

            // store incoming POST data bound to model object in context
            if (ModelState.IsValid)
            {
                // add incoming data as IncomingMessage record to database
                _context.Add(incomingMessage);
                await _context.SaveChangesAsync();

                // new Jumble - and internally construct MessageOut
                Jumble jumble = new Jumble(incomingMessage);
                _context.Add(jumble);
                await _context.SaveChangesAsync();

                // set response content
                textMessage = jumble.MessageOut;
            }

            // construct TwiML from to be returned message
            MessagingResponse twiml = new MessagingResponse();

            twiml.Message(textMessage);
            string twixml = twiml.ToString();

            // output TwiML xml or plain output format
            return(Content(textMessage));
        }
Пример #26
0
        public async Task <IActionResult> Get([FromQuery] string body)
        {
            var spotify = new SpotifyClient(SPOTIFY_ID, SPOTIFY_SECRET);
            var song    = await spotify.GetSong(body);

            var messagingResponse = new MessagingResponse();

            if (song == null)
            {
                messagingResponse.Message("Sending back a sample message since Spotify couldn't find our results!");
            }
            else
            {
                var stringBuilder = new StringBuilder();
                stringBuilder.AppendLine($"Artist: {song["artist"].ToString()}");
                stringBuilder.AppendLine($"Title: {song["title"].ToString()}");
                var previewUrl = song["previewUrl"].ToString();
                if (string.IsNullOrEmpty(previewUrl))
                {
                    stringBuilder.AppendLine("Sorry we couldn't find a preview. But try visiting Spotify to listen to the full track");
                }
                else
                {
                    stringBuilder.AppendLine($"Here's the preview: {previewUrl}");
                }
                var message = new Message();
                message.Body(stringBuilder.ToString());
                message.Media(new Uri(song["image"].ToString()));
                messagingResponse.Append(message);
            }

            return(new ContentResult {
                Content = messagingResponse.ToString(), ContentType = "application/xml"
            });
        }
Пример #27
0
        public async System.Threading.Tasks.Task <TwiMLResult> IndexAsync(SmsRequest incomingMessage)
        {
            var messagingResponse = new MessagingResponse();

            messagingResponse.Message("Thank you for using our rating system! You gave your event a " + incomingMessage.Body);
            return(TwiML(messagingResponse));
        }
Пример #28
0
        public TwiMLResult Index(SmsRequest request)
        {
            var response = new MessagingResponse();

            response.Message("Response received successfully");

            //You have to enable login from other timezone / ip for your google account.
            //to do this follow the link https://g.co/allowaccess and allow access by clicking the continue button.
            //And that's it. Here you go. Now you will be able to login from any of the computer and by any means of app to your google account.
            //https://www.google.com/settings/security/lesssecureapps
            //
            //
            var smtpClient = new SmtpClient("smtp.gmail.com")
            {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Host           = "smtp.gmail.com",
                Port           = 587,
                Credentials    = new NetworkCredential("*****@*****.**", "strongpassword"),
                EnableSsl      = true,
            };
            var mailMessage = new MailMessage
            {
                From       = new MailAddress("*****@*****.**"),
                Subject    = "Twilio WebHook " + DateTime.UtcNow.AddHours(-3),
                Body       = "<h3>SmsSid</h3><span>" + request.SmsSid + "</span></br><h3>From</h3><span>" + request.From + "</span></br><h3>Body</h3><span>" + request.Body + "</span></br><h3>OptOutType</h3><span>" + request.OptOutType + "</span></br>",
                IsBodyHtml = true,
            };

            mailMessage.To.Add("*****@*****.**");
            smtpClient.Send(mailMessage);

            return(TwiML(response));
        }
Пример #29
0
    public ActionResult Index()
    {
        const string requestBody = Request.Form["Body"];
        var          response    = new MessagingResponse();

        if (requestBody == "hello")
        {
            response.Message("Hi!");
        }
        else if (requestBody == "bye")
        {
            response.Message("Goodbye");
        }

        return(TwiML(response));
    }
Пример #30
0
        public MessagingResponse Handle(SmsRequest request)
        {
            var messagingResponse = new MessagingResponse();

            if (request.Body.ToUpper() == "UNSUBSCRIBE")
            {
                this.Unsubscribe(request.From);
                messagingResponse.Message("You have now been unsubscribed from any groups you previously subscribed to.");
            }
            else
            {
                this.Broadcast(request);
                messagingResponse.Message("Broadcast Sent");
            }
            return(messagingResponse);
        }