(session, args, next) => __awaiter(this, void 0, void 0, function* () {
     let data = undefined;
     // Get Medication.Name, Language and Country entities
     if (args && args.intent) {
         let intent = args.intent;
         let medicationEntity = builder.EntityRecognizer.findEntity(intent.entities, 'Medication.Name');
         let languageEntity = builder.EntityRecognizer.findEntity(intent.entities, 'Language');
         let countryEntity = builder.EntityRecognizer.findEntity(intent.entities, 'Country');
         data = session.dialogData.drug = {
             name: medicationEntity ? medicationEntity.entity : undefined,
             language: languageEntity ? languageEntity.entity : undefined,
             languageCode: languageEntity ? languageEntity.resolution.values[0] : undefined,
             country: countryEntity ? countryEntity.entity : undefined,
             countryCode: undefined
         };
         // If we get a country, need to obtain the associated country code
         if (data.country) {
             let search = helper_countrydata_1.default.getCountryByName(data.country);
             if (search) {
                 session.dialogData.drug.countryCode = search.alpha2;
             }
         }
     }
     if (data && data.name) {
         if (next)
             return next();
     }
     else {
         // Prompt for a medication name
         return builder.Prompts.text(session, "medication_prompt");
     }
 }),
Пример #2
0
 function (session, args, next) {
     // initialize empty array that will be passed on until end that holds conversations
     var conversations = [];
     conversations.push({ who: "bot", text: "Hi, What is your name and can I take your order?", time: new Date().toLocaleString() });
     // store conversations
     session.dialogData.conversations = conversations;
     
     var name = builder.EntityRecognizer.findAllEntities(args.entities, 'Name');
     if( Array.isArray(name)) {
         name[0] = name[0].entity;
         name = name.reduce(function(a, b){ return a + b.entity});
     }
     session.dialogData.human_name = toTitleCase(name.trim());
     
     // get the size
     var size = builder.EntityRecognizer.findEntity(args.entities, 'Size');
     // store size
     session.dialogData.size = size.entity;
     
     // get the toppings
     var toppings = builder.EntityRecognizer.findAllEntities(args.entities, 'Toppings');
     if(Array.isArray(toppings)){
         toppings = toppings.map(function (a) { return a.entity });
     } else {
         toppings = [topping.entity];
     }
     // store toppings
     session.dialogData.toppings = toppings;
     session.dialogData.pizzas = [];
     session.dialogData.order = {};
     next();
 },
Пример #3
0
    function (session, args, next) {
        
        //reset values
        page = 1;
        pTitle = "";
        pWhere = "";
        pKeywords = "";
        pCompanyName = "";
        pDuration = "";
        currentlyDisplayedJobId = 0;

        // See if got the tasks jobtitle from our LUIS model.
        var title = builder.EntityRecognizer.findEntity(args.entities, 'Title');
        var where = builder.EntityRecognizer.findEntity(args.entities, 'builtin.geography.city');
        var keywords = builder.EntityRecognizer.findEntity(args.entities, 'Category');
        var companyName = builder.EntityRecognizer.findEntity(args.entities, 'Company');
        var duration = builder.EntityRecognizer.findEntity(args.entities, 'builtin.datetime.time');

        if (!title) {
            // Prompt user to enter title.
            //builder.Prompts.text(session, prompts.missingJobTitle);
            pTitle = "";
        } else {
            pTitle = title.entity;
        }

        if (!where) {
            pWhere = "";
        } else {
            pWhere = where.entity;
        }
        
        if (!keywords) {
            pKeywords = "";
        } else {
            pKeywords = where.entity;
        }
        
        if (!companyName) {
            pCompanyName = "";
        } else {
            pCompanyName = companyName.entity;
        }
        
        if (!duration) {
            pDuration = -1;
        } else {
            pDuration = 7; //duration.entity;
        }

        // Pass title to next step.
        next({
            title: pTitle,
            where: pWhere,
            keywords: pKeywords,
            companyName: pCompanyName,
            duration: pDuration
        });
    },
Пример #4
0
 .then((reminders) => {
   let which = builder.EntityRecognizer.parseNumber([builder.EntityRecognizer.findEntity(args.entities, 'builtin.number')]) - 1
   if (reminders[which]) {
     session.endDialog(`Got it, ${reminders[which].what} deleted`)
     return db.deleteReminder(reminders[which])
   } else {
     session.send('I could not find that reminder, here is the list.')
     session.beginDialog('/ListReminders')
   }
 })
Пример #5
0
  function(session, args, next) {
    const location = builder.EntityRecognizer.findEntity(args.entities, 'builtin.geography.city');
    const timeperiod = builder.EntityRecognizer.findEntity(args.entities, 'builtin.datetime.date');

    if (!location) {
      builder.Prompts.text(session, 'Where?');
    } else {
      next({
        location: location.entity,
        timeperiod: timeperiod
      });
    }
  },
Пример #6
0
dialog.on('WhenSubmit', function(session, args) {
    console.log('message:');
    console.log(session.message);

    var date = builder.EntityRecognizer.findEntity(args.entities, 'builtin.datetime.date');
    console.log('date:');
    console.log(date);
    
    var item = builder.EntityRecognizer.findEntity(args.entities, 'Item');
    var subject = builder.EntityRecognizer.findEntity(args.entities, 'Subject');

    session.send(item + 'を' + date.resolution.date + 'にするには' + subject + '?');
});
Пример #7
0
/**
 * Try really hard to parse for date entities. Dates don't seem to time zone offset
 * so there is a touchup there 
 * 
 * @param session - user session, look up the timezone here
 * @param entities - entities extracted from LUIS
 * @returns - a date or nothing
 */
function thoroughWhen (session, entities) {
  debug('processing dates', JSON.stringify(entities))
  let alterTimezone = (remiTime, suffix = 'Z') => {
    debug('date looks like this in UTC', remiTime)
    return moment.tz(`${remiTime.toISOString().substring(0, 19)}${suffix}`, `YYYY-MM-DDTHH:mm:ss${suffix}`, session.userData.identity.timezone)
  }
  // check first for a full phrase recognition
  let datetime = builder.EntityRecognizer.findEntity(entities, 'when::datetime')
  || builder.EntityRecognizer.findEntity(entities, 'when')
  || builder.EntityRecognizer.findEntity(entities, 'builtin.datetime.datetime')
  let date = builder.EntityRecognizer.findEntity(entities, 'builtin.datetime.date')
  let time = builder.EntityRecognizer.findEntity(entities, 'builtin.datetime.time')

  // this is effectively a kind of try/parse
  if (datetime) {
    return alterTimezone(builder.EntityRecognizer.recognizeTime(datetime.entity).resolution.start, '')
  }
  if (date && time) {
    return alterTimezone(builder.EntityRecognizer.recognizeTime(`${date.entity} ${time.entity}`).resolution.start, '')
  }
  if (date) {
    let utcResolvedTime = builder.EntityRecognizer.recognizeTime(date.entity).resolution.start
    if (utcResolvedTime) {
      let localResolvedTime = alterTimezone(utcResolvedTime, '')
      // when it is just a day, set it to local noon
      return localResolvedTime.set('hour', 12)
    }
  }
  if (time) {
    if (time.resolution.time) {
      try {
        return alterTimezone(moment(time.resolution.time, 'THH').toDate(), '')
      } catch (e) {
        console.error(e)
      }
    }
    let entity = builder.EntityRecognizer.recognizeTime(time.entity)
    let utcResolvedTime = entity.resolution.start
    if (utcResolvedTime) {
      return alterTimezone(utcResolvedTime, '')
    }
  }
  // the ultra backup case in case we totally missed it
  let utcResolvedTime = builder.EntityRecognizer.resolveTime(entities)
  if (utcResolvedTime) {
    return alterTimezone(utcResolvedTime, '')
  } else {
    return undefined
  }
}
Пример #8
0
 function (session, args, next) {
     // Resolve and store any entities passed from LUIS.
     var title = builder.EntityRecognizer.findEntity(args.entities, 'builtin.alarm.title');
     var time = builder.EntityRecognizer.resolveTime(args.entities);
     var alarm = session.dialogData.alarm = {
       title: title ? title.entity : null,
       timestamp: time ? time.getTime() : null  
     };
     
     // Prompt for title
     if (!alarm.title) {
         builder.Prompts.text(session, 'What would you like to call your alarm?');
     } else {
         next();
     }
 },
Пример #9
0
 function (session, results) {
     var alarm = session.dialogData.alarm;
     if (results.response) {
         var time = builder.EntityRecognizer.resolveTime([results.response]);
         alarm.timestamp = time ? time.getTime() : null;
     }
     
     // Set the alarm (if title or timestamp is blank the user said cancel)
     if (alarm.title && alarm.timestamp) {
         // Save address of who to notify and write to scheduler.
         alarm.to = session.message.from;
         alarm.from = session.message.to;
         alarms[alarm.title] = alarm;
         
         // Send confirmation to user
         var date = new Date(alarm.timestamp);
         var isAM = date.getHours() < 12;
         session.send('Creating alarm named "%s" for %d/%d/%d %d:%02d%s',
             alarm.title,
             date.getMonth() + 1, date.getDate(), date.getFullYear(),
             isAM ? date.getHours() : date.getHours() - 12, date.getMinutes(), isAM ? 'am' : 'pm');
     } else {
         session.send('Ok... no problem.');
     }
 }
Пример #10
0
 function (session, args, next) {
     // Resolve entities passed from LUIS.
     var title;
     var entity = builder.EntityRecognizer.findEntity(args.entities, 'builtin.alarm.title');
     if (entity) {
         // Verify its in our set of alarms.
         title = builder.EntityRecognizer.findBestMatch(alarms, entity.entity);
     }
     
     // Prompt for alarm name
     if (!title) {
         builder.Prompts.choice(session, 'Which alarm would you like to delete?', alarms);
     } else {
         next({ response: title });
     }
 },
Пример #11
0
xdialog.on('bot.stock', function (session, args) {
    var searchTerm = builder.EntityRecognizer.findEntity(args.entities, 'Search Term');
    
    if (!searchTerm){
        var stagedSearchTerm = helper.getQuoted(session.message.sourceText || session.message.text);
        if (stagedSearchTerm){
            searchTerm = {
                entity: stagedSearchTerm
            };
        }
    }
     
    if (!searchTerm) {
        sende(session, texting.get('stock__nosearchterm'), 'bot.stock__nosearchterm');
    } else {
        api.getStock(searchTerm.entity).then(function(data){
            //success:
            var id = data.hrefMobile.split('=')[1];
            attach(session, {
               contentType: 'image/png',
               contentUrl: sprintf('http://boerse.wiwo.de/3048/chartNG.gfn?chartType=0&instrumentId=%s&width=580&height=243&subProperty=20&highLow=1', id)   
            });
            sende(session, texting.get('stock__found',
                data.descriptionShort,
                data.lastPrice.replace('&euro;','€'),
                data.quoteTime,
                id
                ), 'bot.stock__nosearchterm');              
        }).catch(function(err){
            //error:
            sende(session, texting.get('stock__error', err.description), 'bot.stock__error');            
        });        
    }

});
Пример #12
0
  function (session, args) {
      var searchTerm = builder.EntityRecognizer.findEntity(args.entities, 'Search Term');
  
      if (!searchTerm){
          var stagedSearchTerm = helper.getQuoted(session.message.sourceText || session.message.text);
          if (stagedSearchTerm){
              searchTerm = {
                  entity: stagedSearchTerm
              };
          }
      }   
 
      console.log('Search Term', searchTerm);
      if (!searchTerm) {
          sende(session,
              texting.get('search__nosearchterm', session.message.text),
              'bot.search__nosearchterm');
      } else {
         search.doSearch(searchTerm.entity).then(function(data){
             console.log('search_result', data);
             if (data.length){                    
                  sende(session, formatter.toSearchResultsList(data, searchTerm.entity),'bot.search');
             } else {
                  sende(session, texting.get('search__noresult', searchTerm.entity),
                  'bot.search__noresult');
             }
         }).catch(function(err){
             sende(session,
                  texting.get('search__error', searchTerm.entity),
                  'bot.search__error');
         })
         
      }
  }
Пример #13
0
this._dialog.on("LogWork", [function (session, args, next) {
        let issueNumber = builder.EntityRecognizer.findEntity(args.entities, "issue_number");
        let duration = builder.EntityRecognizer.findEntity(args.entities, "builtin.datetime.duration");
        let logWorkObject = session.userData.logWorkObject = {
            issueNumber: issueNumber ? issueNumber.entity : session.userData.issueNumber ? session.userData.issueNumber : null,
            duration: duration ? duration.resolution.duration : null
        };
        if (!logWorkObject.issueNumber) {
            builder.Prompts.text(session, "Please enter an issue number.");
        }
        else if (!logWorkObject.duration) {
            builder.Prompts.text(session, "enter duration.");
        }
        else {
            next();
        }
    }, function (session, results, next) {
Пример #14
0
            builder.LuisDialog.recognize(results.response, modelUri, function (err, intents, entities) {                
                if (null != err) {
                    session.endDialog("Unexpected error while parsing your answer. Try again!");
                    return;
                }                 
                var time = builder.EntityRecognizer.resolveTime(entities, "builtin.datetime.date");
                if (null == time) {
                    session.endDialog("I dont understand your details..Please provide the date of journey again...?");
                    return;
                }
                else {
                    var month = (time.getMonth() + 1) < 10 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1);
                    var dt = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
                    session.userData.doj = time.getFullYear() + "" + month + "" + dt;

                    var key = "embct6154";

                    var Client = require('node-rest-client').Client;
                    var client = new Client();
                    // set content-type header and data as json in args parameter 
                    var options = {
                        headers: { "Content-Type": "application/json" }
                    };

                    var req = client.get("http://api.railwayapi.com/live/train/" + session.userData.trainNumber + "/doj/" + session.userData.doj + "/apikey/" + key + "/", options, function (data, response) {
                        // parsed response body as js object 
                        if (data) {
                            var stationInfo = "";
                            //session.send(data["response_code"]);
                            var routes = data["route"];
                            if (null != routes) {

                                stationInfo = stationInfo + "Point | Station | Arr. | Dep. | Date\n";
                                stationInfo = stationInfo + "------------ | ------------- | -------------| -------------| -------------\n";

                                for (var idx = 0; idx < routes.length; idx++) {
                                    var route = routes[idx];
                                    stationInfo = stationInfo + route["no"] + "|" + route["station_"]["name"] + "|" + route["actarr"] + "|" + route["actdep"] + "|" + route["actarr_date"] + "\n";
                                }
                                stationInfo = stationInfo + data["position"];
                            }
                            session.send(stationInfo);
                            delete session.userData.trainNumber;
                        }
                        else {
                            session.send("Sorry! Information not available...");
                            delete session.userData.pnrNumber;
                            delete session.userData.trainNumber;
                        }
                    });
                    req.on("error", function (err) {
                        session.send("Error:" + err);
                        delete session.userData.pnrNumber;
                        delete session.userData.trainNumber;
                    });

                }
            });
Пример #15
0
 function (session, args, next) {
     console.log("args :: \n" + JSON.stringify(args.entities));
     var symbol = builder.EntityRecognizer.findEntity(args.entities, 'company');
     if (!symbol) {
         builder.Prompts.text(session, "Which company stock you are intrested in?");
     }
     else {
         next({ response: symbol.entity });
     }
 },
Пример #16
0
    function (session, args, next) {
	var managedObject = builder.EntityRecognizer.findEntity(args.entities, 'managedObject');
	if(managedObject) {
	    builder.DialogAction.send("Here are the current %s.", managedObject.entity);
	    next({ response: managedObject.entity });
	}
	else {
	    builder.DialogAction.send("Sorry, I can't find the managedEntity");
	}
    },
Пример #17
0
    function (session, args, next) {
        session.send('Welcome to the Hotels finder! We are analyzing your message: \'%s\'', session.message.text);

        // try extracting entities
        var cityEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'builtin.geography.city');
        var airportEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'AirportCode');
        if (cityEntity) {
            // city entity detected, continue to next step
            session.dialogData.searchType = 'city';
            next({ response: cityEntity.entity });
        } else if (airportEntity) {
            // airport entity detected, continue to next step
            session.dialogData.searchType = 'airport';
            next({ response: airportEntity.entity });
        } else {
            // no entities detected, ask user for a destination
            builder.Prompts.text(session, 'Please enter your destination');
        }
    },
Пример #18
0
    function (session, args, next) {
        
        var reqTitle = builder.EntityRecognizer.findEntity(args.entities, 'Title');
        var reqWhere = builder.EntityRecognizer.findEntity(args.entities, 'builtin.geography.city');
        //var reqKeywords = builder.EntityRecognizer.findEntity(args.entities, 'Category');

        var respMessage = 'Seems like you are looking to hire ';
        
        if (reqTitle) {
            respMessage += 'a ' + reqTitle.entity;
        } else {
            respMessage += 'someone';
        }
        
        if (reqWhere) {
            respMessage += ' in ' + reqWhere.entity;
        }

        respMessage += '. Please take a look at http://hiring.monster.com how we can help you.';
        
        session.send(respMessage);
        
        //// Do we have any tasks?
        //if (session.userData.tasks && session.userData.tasks.length > 0) {
        //    // See if got the tasks title from our LUIS model.
        //    var topTask;
        //    var title = builder.EntityRecognizer.findEntity(args.entities, 'TaskTitle');
        //    if (title) {
        //        // Find it in our list of tasks
        //        topTask = builder.EntityRecognizer.findBestMatch(session.userData.tasks, title.entity);
        //    }
            
        //    // Prompt user if task missing or not found
        //    if (!topTask) {
        //        builder.Prompts.choice(session, prompts.finishTaskMissing, session.userData.tasks);
        //    } else {
        //        next({ response: topTask });
        //    }
        //} else {
        //    session.send(prompts.listNoTasks);
        //}
    }
Пример #19
0
 function (session, args) {
     var author = builder.EntityRecognizer.findEntity(args.entities, 'Author');
     //console.log('Author', author);
     if (!author) {
         sende(session, texting.get('special.feed.author.recent__noauthor', session.message.text),
              'bot.special.feed.author.recent__noauthor');
     } else {
         sende(session, texting.get('special.feed.author.recent', author.entity), 'bot.special.feed.author.recent');
         //TODO: Add query for author RSS feed
     }
 }
Пример #20
0
 function (session, args) {
     delete session.userData.trainNumber;
     var entity = builder.EntityRecognizer.findEntity(args.entities, 'train-number');
     if (null != entity) {
         var trainNumber = entity.entity;
         if (null != trainNumber) {
             session.userData.trainNumber = trainNumber;
             builder.Prompts.text(session, "Can i have the date of journey...?");
         }
     }
 },
Пример #21
0
  function(session, args, next) {
    const location = builder.EntityRecognizer.findEntity(args.entities, 'builtin.geography.city');

    if (!location) {
      builder.Prompts.text(session, 'Where?');
    } else {
      next({
        response: location.entity
      });
    }
  },
 (session, args, next) => __awaiter(this, void 0, void 0, function* () {
     let data = undefined;
     // Get the Medication entity
     if (args && args.intent) {
         let intent = args.intent;
         let medicationEntity = builder.EntityRecognizer.findEntity(intent.entities, 'Medication.Name');
         let typeEntity = builder.EntityRecognizer.findEntity(intent.entities, 'Medication.Type');
         data = session.dialogData.drug = {
             name: medicationEntity ? medicationEntity.entity : undefined,
             type: typeEntity ? typeEntity.resolution : undefined
         };
     }
     if (data && data.name) {
         if (next)
             return next();
     }
     else {
         session.send("drugs_help_tip_image");
         return builder.Prompts.text(session, "medication_prompt");
     }
 }),
Пример #23
0
 function (session, args, next) {
     // See if got the PatientId from our LUIS model.
     var PatientId = builder.EntityRecognizer.findEntity(args.entities, 'PatientId');
     if (!PatientId) {
         // Prompt user to enter PatientId.
         builder.Prompts.text(session, "Enter a patient Id.");
     }
     else {
         // Pass PatientId to next step.
         next({ response: PatientId.entity });
     }
 },
Пример #24
0
 function (session, args, next) {
     // See if got the tasks title from our LUIS model.
     var title = builder.EntityRecognizer.findEntity(args.entities, 'TaskTitle');
     if (!title) {
         // Prompt user to enter title.
         builder.Prompts.text(session, prompts.saveTaskMissing);
     }
     else {
         // Pass title to next step.
         next({ response: title.entity });
     }
 },
Пример #25
0
    function (session, args, next) {

        var task = builder.EntityRecognizer.findEntity(args.entities, 'kids');
        if (task) {
          downloadOffersForCategory(session, 1);
        }

        var task = builder.EntityRecognizer.findEntity(args.entities, 'esk');
        if (task) {
          downloadOffersForCategory(session, 69);
        }

        var task = builder.EntityRecognizer.findEntity(args.entities, 'outdoors');
        if (task) {
          downloadOffersForCategory(session, 109);
        }

        var task = builder.EntityRecognizer.findEntity(args.entities, 'seniors');
        if (task) {
          downloadOffersForCategory(session, 111);
        }

        var task = builder.EntityRecognizer.findEntity(args.entities, 'everyone');
        if (task) {
          downloadOffersForCategory(session, 287);
        }

        var task = builder.EntityRecognizer.findEntity(args.entities, 'adults');
        if (task) {
          downloadOffersForCategory(session, 253);
        }
    }
Пример #26
0
 function (session, args, next) {
     // Do we have any tasks?
     if (session.userData.tasks && session.userData.tasks.length > 0) {
         // See if got the tasks title from our LUIS model.
         var topTask;
         var title = builder.EntityRecognizer.findEntity(args.entities, 'TaskTitle');
         if (title) {
             // Find it in our list of tasks
             topTask = builder.EntityRecognizer.findBestMatch(session.userData.tasks, title.entity);
         }
         // Prompt user if task missing or not found
         if (!topTask) {
             builder.Prompts.choice(session, prompts.finishTaskMissing, session.userData.tasks);
         }
         else {
             next({ response: topTask });
         }
     }
     else {
         session.send(prompts.listNoTasks);
     }
 },
Пример #27
0
Файл: app.js Проект: morsh/bots
    function (session, args, next) {

        logging.trackCustomEvent('Try.This', { prop: 'val' }, session);
        logging.trackEvent({ prop: 'val' }, session);
        console.log('setting alarm...');
        logging.startTransaction(session, 'create alarm');

        // Resolve and store any entities passed from LUIS.
        var title = builder.EntityRecognizer.findEntity(args.entities, 'AlarmName');
        var timeEntity = builder.EntityRecognizer.recognizeTime(session.message.text);
        var time = timeEntity && builder.EntityRecognizer.resolveTime([timeEntity]);
        var alarm = session.dialogData.alarm = {
          title: title ? title.entity : null,
          timestamp: time ? time.getTime() : null  
        };
        
        // Prompt for title
        if (!alarm.title) {
            builder.Prompts.text(session, 'What would you like to call your alarm?');
        } else {
            next();
        }
    },
Пример #28
0
bot.dialog('ShowHotelsReviews', function (session, args) {
    // retrieve hotel name from matched entities
    var hotelEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'Hotel');
    if (hotelEntity) {
        session.send('Looking for reviews of \'%s\'...', hotelEntity.entity);
        Store.searchHotelReviews(hotelEntity.entity)
            .then(function (reviews) {
                var message = new builder.Message()
                    .attachmentLayout(builder.AttachmentLayout.carousel)
                    .attachments(reviews.map(reviewAsAttachment));
                session.endDialog(message);
            });
    }
}).triggerAction({
Пример #29
0
    function (session, args, next) {

        console.log('** SetPowerState Called');

        // See if we got the power state from our LUIS model.
        var powerState = builder.EntityRecognizer.findEntity(args.entities, 'powerState');

        if (!!powerState) {
            // act
            session.send(prompts.powerState());
        }
        else {
            session.send(prompts.notUnderstood())
        }
    }
Пример #30
0
dialog.on('what_day', function(session, args) {
    console.log('message:');
    console.log(session.message);

    var date = builder.EntityRecognizer.findEntity(args.entities, 'builtin.datetime.date');
    console.log('date:');
    console.log(date);

    if (date != undefined && date.resolution != undefined) {
        var d = new Date(date.resolution.date);
        var day = '日月火水木金土'[d.getDay()];
        session.send('その日は「' + day + '曜日」です。');
    } else {
        session.send('日付を取得できませんでした。');
    }
});