コード例 #1
0
        public LexResponse ModelResponse(LexEvent lexEvent)
        {
            var model = lexEvent.CurrentIntent.Slots[Model];

            var make = lexEvent.CurrentIntent.Slots[Make];
            var item = Items.First(x => string.Equals(make, x.Value, StringComparison.InvariantCultureIgnoreCase));

            var valid = item.Subs?.Any(x =>
                                       string.Equals(x.Value, model, StringComparison.InvariantCultureIgnoreCase) ||
                                       string.Equals(x.DisplayValue, model, StringComparison.InvariantCultureIgnoreCase)) ?? false;

            if (valid)
            {
                lexEvent.SessionAttributes[Step] = Model;
                return(Delegate(lexEvent.SessionAttributes, lexEvent.CurrentIntent.Slots));
            }

            lexEvent.CurrentIntent.Slots[Model] = null;
            return(ElicitSlot(lexEvent.SessionAttributes, lexEvent.CurrentIntent.Name, lexEvent.CurrentIntent.Slots,
                              Model, new LexResponse.LexMessage()
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = $"Can not find model {model}"
            }));
        }
コード例 #2
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            var slots             = lexEvent.CurrentIntent.Slots;
            var sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            JobCriteria jobCriteria = new JobCriteria
            {
                LocationInput = slots.ContainsKey(LOCATION_SLOT) ? slots[LOCATION_SLOT] : null,
                Profession    = slots.ContainsKey(PROFESSION_SLOT) ? slots[PROFESSION_SLOT] : null,
                Skills        = slots.ContainsKey(SKILLS_SLOT) ? slots[SKILLS_SLOT].Split(',').ToList() : null,
                PerfectJob    = slots.ContainsKey(PERFECT_JOB_SLOT) ? slots[PERFECT_JOB_SLOT] : null,
                KeyPhrases    = slots.ContainsKey(PERFECT_JOB_SLOT) ? GetKeyPhrases(slots[PERFECT_JOB_SLOT]) : null
            };

            if (slots.ContainsKey(LOCATION_SLOT))
            {
                var geoLocation = FuzzyGeoCode(slots[LOCATION_SLOT]).Result;
                if (geoLocation != null && geoLocation.Longitude != 0 && geoLocation.Latitude != 0)
                {
                    jobCriteria.Longitude     = geoLocation.Longitude;
                    jobCriteria.Latituede     = geoLocation.Latitude;
                    jobCriteria.LocationInput = geoLocation.FormattedLocation;
                }
            }
            else
            {
                var geoLocation = FuzzyGeoCode("aurora, co").Result;
                if (geoLocation != null && geoLocation.Longitude != 0 && geoLocation.Latitude != 0)
                {
                    jobCriteria.Longitude     = geoLocation.Longitude;
                    jobCriteria.Latituede     = geoLocation.Latitude;
                    jobCriteria.LocationInput = geoLocation.FormattedLocation;
                }
            }

            sessionAttributes[CURRENT_JOB_CRITERIA_SESSION_ATTRIBUTE] = SerializeJobCriteria(jobCriteria);

            var jobs    = SearchJobs(jobCriteria);
            var content = "DERP! I didn't find any jobs that are a fit for you right now.";

            if (jobs.ResultItems.Any())
            {
                var job         = jobs.ResultItems.FirstOrDefault();
                var desciption  = job.description.Substring(0, 500);
                var cutOffIndex = desciption.LastIndexOf(' ');
                content = string.Format("I found your next job. {0} located in {1}. {2}... To apply visit {3}",
                                        job.jobTitle, job.locationText, desciption.Remove(cutOffIndex).Replace("&nbsp;", string.Empty), job.jobUrl);
            }

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = content
            }
                       ));
        }
コード例 #3
0
 private void AddInitializedFlag(LexEvent request)
 {
     if (request.SessionAttributes == null)
     {
         request.SessionAttributes = new Dictionary <string, string>();
     }
     request.SessionAttributes.Add("Initialized", true.ToString());
 }
コード例 #4
0
        /// <summary>
        /// Performs dialog management and fulfillment for ordering flowers.
        ///
        /// Beyond fulfillment, the implementation for this intent demonstrates the following:
        /// 1) Use of elicitSlot in slot validation and re-prompting
        /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation
        /// </summary>
        /// <param name="lexEvent"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            var         slots             = lexEvent.CurrentIntent.Slots;
            var         sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();
            FlowerTypes type;

            if (slots.ContainsKey(TYPE_SLOT))
            {
                Enum.TryParse(slots[TYPE_SLOT], out type);
            }
            else
            {
                type = FlowerTypes.Null;
            }

            FlowerOrder order = new FlowerOrder
            {
                FlowerType = slots.ContainsKey(TYPE_SLOT) ? type : FlowerTypes.Null,
                PickUpDate = slots.ContainsKey(PICK_UP_DATE_SLOT) ? slots[PICK_UP_DATE_SLOT] : null,
                PickUpTime = slots.ContainsKey(PICK_UP_TIME_SLOT) ? slots[PICK_UP_TIME_SLOT] : null
            };

            // sessionAttributes[CURRENT_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(order);

            if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal))
            {
                var validateResult = Validate(order);
                // If any slots are invalid, re-elicit for their value
                if (!validateResult.IsValid)
                {
                    slots[validateResult.ViolationSlot] = null;
                    return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message));
                }


                // Pass the price of the flowers back through session attributes to be used in various prompts defined
                // on the bot model.
                if (order.FlowerType.Value != FlowerTypes.Null)
                {
                    sessionAttributes["Price"] = (order.FlowerType.Value.ToString().Length * 5).ToString();
                }


                return(Delegate(sessionAttributes, slots));
            }



            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = String.Format("Thanks, your order for {0} has been placed and will be ready for pickup by {1} on {2}.", order.FlowerType.ToString(), order.PickUpTime, order.PickUpDate)
            }
                       ));
        }
コード例 #5
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();
            IDictionary <string, string> requestAttributes = lexEvent.RequestAttributes ?? new Dictionary <string, string>();
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;

            LambdaLogger.Log("GetBin Intent Processor");
            LambdaLogger.Log("Bot Name =" + lexEvent.Bot.Name);
            LambdaLogger.Log("Bot Aliase =" + lexEvent.Bot.Alias);
            LambdaLogger.Log("Bot Version =" + lexEvent.Bot.Version);
            LambdaLogger.Log("user ID =" + lexEvent.UserId);
            LambdaLogger.Log("Transcription =" + lexEvent.InputTranscript);
            LambdaLogger.Log("Invocation Source =" + lexEvent.InvocationSource);
            LambdaLogger.Log("Output Dialog Mode =" + lexEvent.OutputDialogMode);

            foreach (KeyValuePair <string, string> entries in sessionAttributes)
            {
                LambdaLogger.Log(string.Format("Session Attribute = {0}, Value = {1}", entries.Key, entries.Value));
            }

            foreach (KeyValuePair <string, string> entries in requestAttributes)
            {
                LambdaLogger.Log(string.Format("Request Attribute = {0}, Value = {1}", entries.Key, entries.Value));
            }

            foreach (KeyValuePair <string, string> entries in slots)
            {
                LambdaLogger.Log(string.Format("Slot = {0}, Value = {1}", entries.Key, entries.Value));
            }

            String faqResponse = ReadObjectDataAsync(lexEvent.InputTranscript).Result;

            if (faqResponse.Equals(""))
            {
                return(Close(
                           sessionAttributes,
                           "Failed",
                           new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = String.Format("Please wait for one of my human colleagues to join this chat.")
                }));
            }
            else
            {
                return(Close(
                           sessionAttributes,
                           "Fulfilled",
                           new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = String.Format(faqResponse)
                }));
            }
        }
コード例 #6
0
        /// <summary>
        /// Performs dialog management and fulfillment for ordering flowers.
        ///
        /// Beyond fulfillment, the implementation for this intent demonstrates the following:
        /// 1) Use of elicitSlot in slot validation and re-prompting
        /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation
        /// </summary>
        /// <param name="lexEvent"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            //if all the values in the slots are empty return the delegate, theres nothing to validate or do.
            if (slots.All(x => x.Value == null))
            {
                return(Delegate(sessionAttributes, slots));
            }

            //if the deployment environment slot has a value, validate that it is contained within the enum list available.
            if (slots[ENVIRONMENT_SLOT] != null)
            {
                var validateDeploymentEnvironment = ValidateDeploymentEnvironment(slots[ENVIRONMENT_SLOT]);

                if (!validateDeploymentEnvironment.IsValid)
                {
                    slots[validateDeploymentEnvironment.ViolationSlot] = null;
                    return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateDeploymentEnvironment.ViolationSlot, validateDeploymentEnvironment.Message));
                }
            }

            //now that enum has been parsed and validated, create the deployment
            DeploymentInfo deploymentInfo = CreateDeployment(slots);

            if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal))
            {
                //validate the remaining slots.
                var validateResult = Validate(deploymentInfo);
                // If any slots are invalid, re-elicit for their value

                if (!validateResult.IsValid)
                {
                    slots[validateResult.ViolationSlot] = null;
                    return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message));
                }

                return(Delegate(sessionAttributes, slots));
            }

            Task.WaitAll(InvokePipeline());

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = String.Format("Alright, your deployment in {0} environment has been scheduled at {1} on {2}.", deploymentInfo.DeploymentEnvironment.ToString(), deploymentInfo.DeploymentTime, deploymentInfo.DeploymentDate)
            }
                       ));
        }
コード例 #7
0
ファイル: Function.cs プロジェクト: sriwantha/aws-lex
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent e, ILambdaContext context)
        {
            try
            {
                LexResponse r = new LexResponse();

                Guid g = Guid.Empty;

                if (e.InvocationSource == "FulfillmentCodeHook")
                {
                    g = Guid.NewGuid();
                    using (AmazonDynamoDBClient client = new AmazonDynamoDBClient())
                    {
                        Table    reservations = Table.LoadTable(client, "Lex_Reservation");
                        Document doc          = new Document();

                        doc["ReservationId"]   = g.ToString();
                        doc["ReservationDate"] = DateTime.Now.ToString("yyyy:MM:dd:HH:mm:ss");
                        if (e.CurrentIntent.Name == "BookHotel")
                        {
                            doc["Type"]        = "Hotel";
                            doc["Location"]    = e.CurrentIntent.Slots["Location"];
                            doc["CheckInDate"] = e.CurrentIntent.Slots["CheckInDate"];
                            doc["Nights"]      = e.CurrentIntent.Slots["Nights"];
                            doc["RoomType"]    = e.CurrentIntent.Slots["RoomType"];
                        }
                        if (e.CurrentIntent.Name == "BookCar")
                        {
                            doc["Type"]       = "Car";
                            doc["PickupCity"] = e.CurrentIntent.Slots["PickUpCity"];
                            doc["PickupDate"] = e.CurrentIntent.Slots["PickUpDate"];
                            doc["ReturnDate"] = e.CurrentIntent.Slots["ReturnDate"];
                            doc["DriverAge"]  = e.CurrentIntent.Slots["DriverAge"];
                            doc["CarType"]    = e.CurrentIntent.Slots["CarType"];
                        }


                        Task <Document> t = reservations.PutItemAsync(doc);
                        t.Wait();
                        //context.Logger.Log("Saved successfully!!!");
                        //r.DialogAction.Type = "Close";
                        //r.SessionAttributes.Add("RervervationGuid", g.ToString());
                    }
                }
                return(r);
            }
            catch (Exception ex)
            {
                context.Logger.Log(ex.ToString());
                throw;
            }
        }
コード例 #8
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            lexEvent.SessionAttributes[DateTime.Now.Millisecond.ToString()] = lexEvent.InputTranscript;

            if (!lexEvent.SessionAttributes.ContainsKey(Step))
            {
                lexEvent.CurrentIntent.Slots.TryGetValue(Make, out var make);
                return(string.IsNullOrEmpty(make)
                    ? Delegate(lexEvent.SessionAttributes, lexEvent.CurrentIntent.Slots)
                    : MakeResponse(lexEvent));
            }

            return(lexEvent.SessionAttributes[Step] == Make?ModelResponse(lexEvent) : FulfillResponse(lexEvent));
        }
コード例 #9
0
        /// <summary>
        /// Then entry point for the Lambda function that looks at the current intent and calls
        /// the appropriate intent process.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse LambdaFunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process = null;

            try
            {
                switch (lexEvent.CurrentIntent.Name)
                {
                case "StartServer":
                    process = new ServerIntentProcessor(IsLocalDebug, context);
                    break;

                case "DescribeInstances":
                    process = new DescribeIntentProcessor(IsLocalDebug, context);
                    break;

                case "Greetings":
                    process = new GreetingIntentProcessor(context);
                    break;

                case "Thanks":
                    process = new ThanksIntentProcessor(context);
                    break;

                case "Helper":
                    process = new HelperIntentProcessor(context);
                    break;

                case "LaunchInstance":
                    process = new LaunchIntentProcessor(IsLocalDebug, context);
                    break;

                default:
                    throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
                }
            }
            //14-04-2021 - Code added by Thilakar - Starts
            catch (ObjectDisposedException objDisposed)
            {
                context.Logger.LogLine($"ChatbotStartupProgram::LambdaFunctionHandler ObjDisposed exception message : {objDisposed.Message}");
                context.Logger.LogLine($"ChatbotStartupProgram::LambdaFunctionHandler ObjDisposed stacktrace : {objDisposed.StackTrace}");
            }
            //14-04-2021 - Code added by Thilakar - ends
            catch (Exception ex)
            {
                context.Logger.LogLine($"ChatbotStartupProgram::LambdaFunctionHandler exception message : {ex.Message}");
                context.Logger.LogLine($"ChatbotStartupProgram::LambdaFunctionHandler stacktrace : {ex.StackTrace}");
            }
            return(process.Process(lexEvent));
        }
コード例 #10
0
        public LexResponse MakeResponse(LexEvent lexEvent)
        {
            var make      = lexEvent.CurrentIntent.Slots[Make];
            var item      = Items.First(x => string.Equals(make, x.Value, StringComparison.InvariantCultureIgnoreCase));
            var topModels = item.Subs.OrderByDescending(x => x.Count).Take(3);

            lexEvent.SessionAttributes[Step] = Make;
            return(ElicitSlot(lexEvent.SessionAttributes, lexEvent.CurrentIntent.Name, lexEvent.CurrentIntent.Slots,
                              Model, new LexResponse.LexMessage()
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content =
                    $"Do you know what model you want? {string.Join(", ", topModels.Select(x => x.DisplayValue))}"
            }));
        }
コード例 #11
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            if (lexEvent.CurrentIntent.Name == "ComputerOrder")
            {
                process = new ComputerOrderIntentProcessor();
            }
            else
            {
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
            }

            return(process.Process(lexEvent, context));
        }
コード例 #12
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            //if all the values in the slots are empty return the delegate, theres nothing to validate or do.
            if (slots.All(x => x.Value == null))
            {
                return(Delegate(sessionAttributes, slots));
            }

            if (string.IsNullOrEmpty(slots[VERB]))
            {
                return(ElicitSlot(
                           sessionAttributes,
                           "SleepingIntent",
                           slots,
                           VERB,
                           new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = "Look at Marvin! What is he doing?"
                }
                           ));
            }

            switch (slots[VERB])
            {
            case "sleeping":
                return(SleepingVerbProcessor(sessionAttributes, slots));

            case "bed":
                return(BedProcessor(sessionAttributes, slots));

            default:
                return(ElicitSlot(
                           sessionAttributes,
                           "SleepingIntent",
                           slots,
                           VERB,
                           new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = "Look at Marvin! What is he doing?"
                }
                           ));
            }
        }
コード例 #13
0
        /// <summary>
        /// Then entry point for the Lambda function that looks at the current intent and calls
        /// the appropriate intent process.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            if (lexEvent.CurrentIntent.Name == "OrderFlowers" || lexEvent.CurrentIntent.Name == "TwitchFlowerBot")
            {
                process = new OrderFlowersIntentProcessor();
            }
            else
            {
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
            }


            return(process.Process(lexEvent, context));
        }
コード例 #14
0
        /// <summary>
        /// Then entry point for the Lambda function that looks at the current intent and calls
        /// the appropriate intent process.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            switch (lexEvent.CurrentIntent.Name)
            {
            case "SleepingIntent":
                process = new SleepIntentProcessor();
                break;

            default:
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
            }

            return(process.Process(lexEvent, context));
        }
コード例 #15
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            if (lexEvent.CurrentIntent.Name == "SetWakeUpTime")
            {
                process = new SetAlarm();
            }
            else
            {
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
            }


            return(process.Process(lexEvent, context));
        }
コード例 #16
0
        public override LexResponse Process(LexEvent lexEvent)
        {
            context.Logger.LogLine("Input Request: " + JsonConvert.SerializeObject(lexEvent));

            int index = new Random().Next() % 3;

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = Constants.MESSAGE_CONTENT_TYPE,
                Content = SampleData.SAMPLE_THANKS_RESPONSES[index]
            }
                       ));
        }
コード例 #17
0
    /// <summary>
    /// Performs dialog management and fulfillment for ordering flowers.
    ///
    /// Beyond fulfillment, the implementation for this intent demonstrates the following:
    /// 1) Use of elicitSlot in slot validation and re-prompting
    /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation
    /// </summary>
    /// <param name="lexEvent"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
    {
        IDictionary <string, string?> slots             = lexEvent.CurrentIntent.Slots ?? new Dictionary <string, string>();
        IDictionary <string, string>  sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

        //if all the values in the slots are empty return the delegate, theres nothing to validate or do.
        if (slots.All(x => x.Value == null))
        {
            return(Delegate(sessionAttributes, slots));
        }

        //if the flower slot has a value, validate that it is contained within the enum list available.
        if (slots[TYPE_SLOT] != null)
        {
            var validateFlowerType = ValidateFlowerType(slots[TYPE_SLOT]);

            if (!validateFlowerType.IsValid)
            {
                slots[validateFlowerType.ViolationSlot !] = null;
コード例 #18
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            if (slots.All(x => x.Value == null))
            {
                return(Delegate(sessionAttributes, slots));
            }

            Assignment assignment = CreateAssignment(slots, lexEvent.InputTranscript);

            if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal))
            {
                sessionAttributes["DONE"] = "FALSE";

                var validateResult = ValidateAssignment(ref assignment, ref slots);

                sessionAttributes["TRANSCRIPT"] = lexEvent.InputTranscript;

                if (!validateResult.IsValid)
                {
                    slots[validateResult.ViolationSlot] = null;
                    return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message));
                }

                sessionAttributes["CURRENT_OBJECT"] = SerializeObject(assignment);

                return(Delegate(sessionAttributes, slots));
            }

            sessionAttributes["DONE"] = "TRUE";

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = $"The assignment {assignment.Title} was sent to the mail list {assignment.MailList}, and its due on {assignment.DueDate}"
            }
                       ));
        }
コード例 #19
0
        /// <summary>
        /// Then entry point for the Lambda function that looks at the current intent and calls
        /// the appropriate intent process.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            switch (lexEvent.CurrentIntent.Name)
            {
            case "OrderFlowers":
                process = new OrderFlowersIntentProcessor();
                break;

            case "VirtualPlayCardIntent":
                process = new ResolvePlayCardIntentProcessor();
                break;

            default:
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
            }

            return(process.Process(lexEvent, context));
        }
コード例 #20
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            //var slots = lexEvent.CurrentIntent.Slots;

            var sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            //string confirmationStaus = lexEvent.CurrentIntent.ConfirmationStatus;



            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = String.Format("Welcome to SplitWise Bot")
            }
                       ));
        }
コード例 #21
0
ファイル: Function.cs プロジェクト: ByronCoder/CryptoBot
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            var date        = lexEvent.CurrentIntent.Slots["Date"];
            var price_close = CryptoPriceProcessor.GetBitCoinPrice(date);

            return(new LexResponse
            {
                SessionAttributes = lexEvent.SessionAttributes,
                DialogAction = new LexResponse.LexDialogAction
                {
                    Type = "Close",
                    FulfillmentState = "Fulfilled",
                    Message = new LexResponse.LexMessage
                    {
                        ContentType = "PlainText",
                        Content = String.Format("The price for bitcoin on date {0} was {1}", date, price_close)
                    }
                }
            });
        }
コード例 #22
0
ファイル: Function.cs プロジェクト: bbolek/APPizza
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent request, ILambdaContext context)
        {
            LambdaLogger.Log(JsonSerializer.Serialize(request));

            if (request.SessionAttributes == null || !request.SessionAttributes.ContainsKey("Initialized"))
            {
                var validationResult = new InitialValidation(request).HandleJob();
                if (validationResult.DialogAction.FulfillmentState == FulfillmentState.Failed.ToString())
                {
                    return(validationResult);
                }
            }

            IIntentHandler validator = null;

            switch (request.CurrentIntent.Name)
            {
            case "OrderPizza":
                switch (request.InvocationSource)
                {
                case "DialogCodeHook":
                    validator = new OrderPizzaIntentValidation(request);
                    break;

                case "FulfillmentCodeHook":
                    validator = new SaveOrder(request);
                    break;
                }

                break;

            case "QueryOrder":
                validator = new QueryOrder(request);
                break;

            default:
                return(new HandlerBase(request).DelegateToLex());
            }

            return(validator?.HandleJob());
        }
コード例 #23
0
ファイル: Function.cs プロジェクト: newcoder99/splitwisebot
        /// <summary>
        /// Then entry point for the Lambda function that looks at the current intent and calls
        /// the appropriate intent process.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            switch (lexEvent.CurrentIntent.Name)
            {
            case "BasicUserAddition":
                process = new BasicUserAdditionIntentProcessor();
                break;

            case "Welcome":
                process = new WelcomeIntentProcessor();
                break;

            default:
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported" + lexEvent.CurrentIntent.Name);
            }


            return(process.Process(lexEvent, context));
        }
コード例 #24
0
        public override LexResponse Process(LexEvent lexEvent)
        {
            context.Logger.LogLine("Input Request: " + JsonConvert.SerializeObject(lexEvent));

            List <InstanceRequest> instances = new List <InstanceRequest>();

            if (string.Equals(lexEvent.InvocationSource, "FulfillmentCodeHook", StringComparison.Ordinal))
            {
                instances = serverOperationsHelper.validEC2Instances();
            }

            var groupedInstances = instances.GroupBy(item => item.InstanceState)
                                   .Select(group => new { state = group.Key, items = group.ToList(), count = group.ToList().Count })
                                   .ToList()
                                   .ConvertAll(x => x.count > 1 ? $"{x.count} instances are in {x.state} state" : $"{x.count} instance is in {x.state} state");

            string responseMessage = string.Empty;

            if (instances.Count == 0)
            {
                responseMessage = "Currently , you donot have any instances in your AWS account.";
            }
            else
            {
                responseMessage = $"You have {instances.Count} instance(s) in your AWS account in total . \n Out of them " +
                                  $"{string.Join(" \n ", groupedInstances)}. \n" +
                                  $"The instances are as follows : \n {string.Join(" \n ", instances.ConvertAll(x => $"{x.InstanceName}({x.InstanceState})"))}";
            }

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = Constants.MESSAGE_CONTENT_TYPE,
                Content = responseMessage
            },
                       null
                       ));
        }
コード例 #25
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();
            IDictionary <string, string> requestAttributes = lexEvent.RequestAttributes ?? new Dictionary <string, string>();
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;

            LambdaLogger.Log("Debug Intent Processor");
            LambdaLogger.Log("Bot Name =" + lexEvent.Bot.Name);
            LambdaLogger.Log("Bot Aliase =" + lexEvent.Bot.Alias);
            LambdaLogger.Log("Bot Version =" + lexEvent.Bot.Version);
            LambdaLogger.Log("user ID =" + lexEvent.UserId);
            LambdaLogger.Log("Transcription =" + lexEvent.InputTranscript);
            LambdaLogger.Log("Invocation Source =" + lexEvent.InvocationSource);
            LambdaLogger.Log("Output Dialog Mode =" + lexEvent.OutputDialogMode);

            foreach (KeyValuePair <string, string> entries in sessionAttributes)
            {
                LambdaLogger.Log(string.Format("Session Attribute = {0}, Value = {1}", entries.Key, entries.Value));
            }

            foreach (KeyValuePair <string, string> entries in requestAttributes)
            {
                LambdaLogger.Log(string.Format("Request Attribute = {0}, Value = {1}", entries.Key, entries.Value));
            }

            foreach (KeyValuePair <string, string> entries in slots)
            {
                LambdaLogger.Log(string.Format("Slot = {0}, Value = {1}", entries.Key, entries.Value));
            }

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = String.Format("Norbot is responding. All debug messages written to log file.")
            }
                       ));
        }
コード例 #26
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            var slots = lexEvent.CurrentIntent.Slots;

            var    sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();
            string confirmationStaus = lexEvent.CurrentIntent.ConfirmationStatus;
            Dictionary <string, object> _lstUserInfoObject = slots.ToDictionary(pair => pair.Key, pair => (object)pair.Value);
            UserInfo userInfoObject = new UserInfo
            {
                Name        = slots.ContainsKey("Name") ? slots["Name"] : string.Empty,
                EmailId     = slots.ContainsKey("EmailId") ? slots["EmailId"] : string.Empty,
                PhoneNumber = slots.ContainsKey("PhoneNumber") ? slots["PhoneNumber"] : string.Empty,
            };

            try
            {
                ValidationResult validObject = Validate(_lstUserInfoObject);
                if (validObject.IsValid)
                {
                    return(Delegate(sessionAttributes, slots));
                }
                else
                {
                    return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validObject.ViolationSlot, new LexResponse.LexMessage
                    {
                        ContentType = MESSAGE_CONTENT_TYPE,
                        Content = validObject.Message.Content.ToString()
                    }));
                }
            }
            catch (Exception ex)
            {
                return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, "OrderNumber", new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = String.Format(ex.Message)
                }));
            }
        }
コード例 #27
0
        public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context)
        {
            IIntentProcessor process;

            switch (lexEvent.CurrentIntent.Name)
            {
            case "GetCollectionDetails":
                process = new GetBinIntentProcessor();
                break;

            case "Default":
                process = new DefaultIntentProcessor();
                break;

            case "Debug":
                process = new DebugIntentProcessor();
                break;

            default:
                throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported");
            }
            return(process.Process(lexEvent, context));
        }
コード例 #28
0
        public LexResponse FulfillResponse(LexEvent lexEvent)
        {
            var model = lexEvent.CurrentIntent.Slots[Model];

            var make = lexEvent.CurrentIntent.Slots[Make];
            var item = Items.First(x => string.Equals(make, x.Value, StringComparison.InvariantCultureIgnoreCase));

            var modelItem = item.Subs.FirstOrDefault(x =>
                                                     string.Equals(x.Value, model, StringComparison.InvariantCultureIgnoreCase) ||
                                                     string.Equals(x.DisplayValue, model, StringComparison.InvariantCultureIgnoreCase));

            return(Close(
                       lexEvent.SessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = modelItem == null
                        ? $"https://www.carsales.com.au/cars/results/"
                        : $"https://www.carsales.com.au/cars/results/?q={modelItem.Action}"
            }
                       ));
        }
コード例 #29
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            var slots             = lexEvent.CurrentIntent.Slots;
            var sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            var vendorClassification = new VendorClassification
            {
                Classification           = "Local",
                CanEvolveAroundMarket    = slots.ContainsKey(CAN_EVOLVE_AROUND_MARKET_SLOT) ? slots[CAN_EVOLVE_AROUND_MARKET_SLOT] : null,
                UnderstandsBusinessNeeds = slots.ContainsKey(UNDERSTANDS_BUSINESS_NEEDS_SLOT) ? slots[UNDERSTANDS_BUSINESS_NEEDS_SLOT] : null,
                HasExperienceInField     = slots.ContainsKey(HAS_EXPERIENCE_IN_FIELD_SLOT) ? slots[HAS_EXPERIENCE_IN_FIELD_SLOT] : null,
            };

            if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal))
            {
                var validationResult = Validate(vendorClassification);

                if (!validationResult.IsValid)
                {
                    slots[validationResult.ViolationSlot] = null;
                    return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots,
                                      validationResult.ViolationSlot, validationResult.Message));
                }

                return(Delegate(sessionAttributes, slots));
            }

            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = "Thanks, I have submitted your data for processing, enjoy the rest of your day."
            }
                       ));
        }
コード例 #30
0
ファイル: SetAlarm.cs プロジェクト: harsiddhP/DIYProject
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();

            //if slots are empty returns the delegate
            if (slots.All(x => x.Value == null))
            {
            }

            if (slots[TYPE_SLOT] != null)
            {
                var validateTimeType = ValidateTimeOfTheDay(slots[TYPE_SLOT]);
                if (!validateTimeType.IsValid)
                {
                    slots[validateTimeType.ViolationSlot] = null;
                    //return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateFlowerType.ViolationSlot, validateFlowerType.Message);
                }
            }

            SetAlarmTime setAlarmTime = SetValidedAlarm(slots);

            if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal))
            {
                //var validateResult = Validate(order);
            }
            return(Close(
                       sessionAttributes,
                       "Fulfilled",
                       new LexResponse.LexMessage
            {
                ContentType = MESSAGE_CONTENT_TYPE,
                Content = String.Format("Alarm is set for {0} {1}.", setAlarmTime.AlarmTime, setAlarmTime.TimeType.ToString())
            }
                       ));
        }