How to use session.send method in qawolf

Best JavaScript code snippet using qawolf

app.js

Source:app.js Github

copy

Full Screen

...35 var name = session.message.user.name.trim().toLowerCase().match(/^[\w]+/i);36 return name === '' ? def : name;37}38const bot = new UniversalBot(connector, function (session) {39 session.send("sorry %s, I didn't understand", parseName(session));40 session.beginDialog('ShowHelp');41});42const getSpotify = function(session, options) {43 var message = null;44 if (session.conversationData.spotifyToken && session.conversationData.spotifyUser) {45 return new Spotify(session.conversationData.spotifyToken, session.conversationData.spotifyUser);46 } else {47 message = 'okay before I do that, do you have a **premium** spotify account?'48 session.replaceDialog('AuthorizeSpotify', { message, options });49 }50}51const createTrackCard = function(session, track) {52 var artist = track.artists && track.artists.length > 0 ? track.artists[0].name : 'not sure who';53 var title = track.name;54 var album = track.album.name;55 var image = track.album.images[1];56 var url = track.external_urls.spotify;57 var date = new Date(null);58 date.setSeconds(track.duration_ms / 1000);59 var mins = date.toISOString().substr(14, 5);60 return new HeroCard(session)61 .title(artist + ' - ' + title)62 .subtitle(mins)63 .text(album)64 .images([ CardImage.create(session, image.url) ])65 .tap(CardAction.openUrl(session, url));66}67const createPlaylistCard = function(session, playlist, images = true) {68 var image = playlist.images[0];69 var url = playlist.external_urls.spotify;70 var card = new HeroCard(session)71 .title(playlist.name)72 .subtitle(playlist.tracks.total + ' tracks')73 .tap(CardAction.openUrl(session, url));74 if (images) {75 card.images([ CardImage.create(session, image.url) ]);76 }77 return card;78}79app.post('/api/messages', connector.listen());80app.get('/', function(req, res) {81 res.send('I\'m a bot... get out!');82});83app.get('/spotify/authorized', function(req, res) {84 if (req.query.code && req.query.state) {85 var state = JSON.parse(Buffer.from(req.query.state, 'base64'));86 res.send('<p>thanks, just close this window <3</p>');87 bot.beginDialog(state.address, 'SpotifyAuthorized', {88 authCode: req.query.code,89 dialog: state.dialog,90 dialogArgs: state.args91 });92 } else {93 res.status(500);94 res.send('<p>cannot authorize bot :(</p>');95 }96});97// install mention middleware. fixes #2530 and #241998bot.use({99 receive: (e, session, next) => {100 const mention = '@' + e.address.bot.name;101 if (e.type === 'message') {102 if (e.text.includes(mention)) {103 e.text = e.text.replace(mention, '').trim();104 }105 }106 next();107 }108});109// Enable Conversation Data persistence110bot.set('persistConversationData', true);111const recognizer = new LuisRecognizer(process.env.LOUIS_MODEL);112bot.recognizer(recognizer);113const playTrack = async function(session, spotify, track) {114 session.send('now playing. enjoy ' + emoji.get('musical_note'));115 session.sendTyping();116 var playback = null;117 if (session.conversationData.spotifyDevice) {118 try {119 playback = await spotify.play(track.uri, session.conversationData.spotifyDevice.id, session.conversationData.spotifyPlaylist.uri);120 } catch (err) {121 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));122 console.log(err);123 }124 if (playback) {125 var card = createTrackCard(session, track);126 var msg = new Message(session)127 .textFormat(TextFormat.markdown)128 .attachments([ card ]);129 session.send(msg);130 } else {131 session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one :)');132 }133 } else {134 session.send('device not set. say "show devices" to get started.');135 }136}137const playPlaylist = async function(session, spotify, playlist) {138 session.send('playing **%s** %s', playlist.name, emoji.get('musical_note'));139 session.sendTyping();140 var playback = null;141 if (session.conversationData.spotifyDevice) {142 try {143 playback = await spotify.play(null, session.conversationData.spotifyDevice.id, playlist.uri);144 session.conversationData.spotifyPlaylist = playlist;145 } catch (err) {146 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));147 console.log(err);148 }149 if (playback) {150 var card = createPlaylistCard(session, playlist);151 var msg = new Message(session)152 .textFormat(TextFormat.markdown)153 .attachments([ card ]);154 session.send(msg);155 } else {156 session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one');157 }158 } else {159 session.send('device not set. type "show devices" to get started.');160 }161}162const queueTrack = async function(session, spotify, query, message = true) {163 session.send('looking for **%s**...', query);164 session.sendTyping();165 try {166 var tracks = await spotify.search(query);167 if (tracks) {168 var track = tracks[0];169 var playback = await spotify.addTrackToPlaylist(track.uri, session.conversationData.spotifyBotPlaylist.id);170 if (message) {171 session.send('**%s** by **%s** added to **bot queue** (y)', track.name, track.artists[0].name);172 if (session.conversationData.spotifyBotPlaylist.id !== session.conversationData.spotifyPlaylist.id) {173 session.send('you\'re not under **bot queue**, type "browse" to select it ;)');174 }175 }176 return tracks;177 } else {178 session.endDialog('no music found, sorry.');179 return;180 }181 } catch (err) {182 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));183 console.log(err);184 }185}186const playTrackNumber = async function(session, spotify, number) {187 session.sendTyping();188 var data = await spotify.getPlaylistTracks(session.conversationData.spotifyPlaylist.owner.id, session.conversationData.spotifyPlaylist.id);189 if (data && data.length > 0) {190 var track = data[Math.max(1, number) - 1];191 if (track) {192 await playTrack(session, spotify, track);193 } else {194 session.send('track **#%s** not in queue. try to type "show queue" to get a list of tracks :)', number);195 }196 } else {197 session.send('track number not found :(');198 }199}200const playTrackQuery = async function(session, spotify, query, message = true) {201 session.send('looking for **%s**...', query);202 session.sendTyping();203 try {204 var tracks = await spotify.search(query);205 if (tracks) {206 var track = tracks[0];207 var playback = null;208 if (session.conversationData.spotifyDevice) {209 await spotify.addTrackToPlaylist(track.uri, session.conversationData.spotifyBotPlaylist.id);210 playback = await spotify.play(track.uri, session.conversationData.spotifyDevice.id, session.conversationData.spotifyBotPlaylist.uri);211 if (playback) {212 if (session.conversationData.spotifyPlaylist.id !== session.conversationData.spotifyBotPlaylist.id) {213 session.send('now playing on **bot\'s queue** ' + emoji.get('musical_note'));214 session.conversationData.spotifyPlaylist = session.conversationData.spotifyBotPlaylist;215 }216 if (message) {217 var card = createTrackCard(session, track);218 var msg = new Message(session)219 .textFormat(TextFormat.markdown)220 .attachments([ card ]);221 session.send(msg);222 }223 return tracks;224 } else {225 session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one');226 }227 } else {228 session.send('device not set. type "show devices" to get started.');229 }230 } else {231 session.endDialog('no music found, sorry.');232 return;233 }234 } catch (err) {235 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));236 console.log(err);237 }238}239bot.on('conversationUpdate', function (message) {240 // Check for group conversations241 if (message.address.conversation.isGroup) {242 // Send a hello message when bot is added243 if (message.membersAdded) {244 message.membersAdded.forEach(function (identity) {245 if (identity.id === message.address.bot.id) {246 var reply = new Message()247 .address(message.address)248 .text("hello everyone!");249 bot.send(reply);250 bot.beginDialog(message.address, 'ShowHelp');251 }252 });253 }254 // Send a goodbye message when bot is removed255 if (message.membersRemoved) {256 message.membersRemoved.forEach(function (identity) {257 if (identity.id === message.address.bot.id) {258 var reply = new Message()259 .address(message.address)260 .text("k bye");261 bot.send(reply);262 }263 });264 }265 }266});267bot.on('contactRelationUpdate', function (message) {268 if (message.action === 'add') {269 var reply = new Message()270 .address(message.address)271 .text("hello %s...", parseName({ message }));272 bot.send(reply);273 bot.beginDialog(message.address, 'ShowHelp');274 } else {275 bot.beginDialog(message.address, 'DeleteUserData', { message: 'k bye' });276 }277});278bot.on('deleteUserData', function (message) {279 bot.beginDialog(message.address, 'DeleteUserData', { message: 'got it' });280});281bot.dialog('Greeting', [282 function(session, args) {283 var greeting = EntityRecognizer.findEntity(args.intent.entities, 'greeting');284 var msg = new Message(session)285 .text([286 'hi %s',287 "what's up?",288 'yes?',289 'hello %s',290 'what can I do for you %s?',291 'you again %s?',292 'what do you want today %s?',293 'what is it that you want %s?',294 'what do you want?',295 'yoh',296 'hey %s',297 'hey'298 ], parseName(session));299 session.send(msg);300 Prompts.confirm(session, 'do you need help?')301 },302 function(session, results) {303 if (results.response) {304 session.send([305 'got it',306 'okay',307 'no problem',308 'sure'309 ]);310 session.beginDialog('ShowHelp');311 } else {312 session.endDialog([313 'kool',314 '(y)',315 ':)',316 'yep',317 'ok',318 'k',319 'got it'320 ]);321 }322 }323]).triggerAction({324 matches: 'Greeting'325});326bot.dialog('Compliment', function(session, args) {327 session.endDialog([328 'no problem %s!',329 '(y)',330 'okay %s',331 'sure %s',332 'anytime ;)'333 ], parseName(session));334}).triggerAction({335 matches: /^(?:\@[\w-_]+\s+)?(?:thanks|thank you)/i336});337bot.dialog('PlayerControl', function(session, args) {338 if (!args) return session.endDialog('use common playback words like "play", "pause", etc.');339 for (var i in Spotify.playbackCommands) {340 var command = Spotify.playbackCommands[i];341 var commandEntity = EntityRecognizer.findEntity(args.intent.entities, 'player_command::' + command);342 if (commandEntity) {343 var number = EntityRecognizer.findEntity(args.intent.entities, 'builtin.number');344 var time = EntityRecognizer.findEntity(args.intent.entities, 'builtin.datetime.time');345 var switchOn = EntityRecognizer.findEntity(args.intent.entities, 'switch::on');346 var switchOff = EntityRecognizer.findEntity(args.intent.entities, 'switch::off');347 return session.beginDialog('ApplyPlayerCommand', {348 number: number && number.entity,349 time: time && time.entity,350 switchOn,351 switchOff,352 command353 });354 }355 }356}).triggerAction({357 matches: 'PlayerControl'358});359bot.dialog('ApplyPlayerCommand', async function(session, args) {360 session.sendTyping();361 var spotify = getSpotify(session, {362 resumeDialog: 'ApplyPlayerCommand',363 dialogArgs: {364 ...args365 }366 });367 if (spotify) {368 try {369 if (session.conversationData.spotifyDevice) {370 var result = await spotify.playback(args, session.conversationData.spotifyDevice.id, (message) => {371 session.send('%s', message);372 });373 if (!result) {374 session.send('cannot connect to device. try to say "devices" to select one :)');375 }376 session.endDialogWithResult({ response: result })377 } else {378 session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one');379 session.endDialogWithResult();380 }381 } catch (err) {382 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));383 console.log(err);384 }385 }386});387bot.dialog('PlaylistControl', function(session, args) {388 if (!args) return session.endDialog('use command playlist words like "browse", "show", "clear", etc.');389 var create = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::create');390 var show = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::show');391 var browse = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::browse');392 var playlistquery = EntityRecognizer.findEntity(args.intent.entities, 'playlistquery');393 var clear = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::clear');394 var add = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::add');395 var songtitle = EntityRecognizer.findEntity(args.intent.entities, 'songtitle');396 var songartist = EntityRecognizer.findEntity(args.intent.entities, 'songartist');397 if (show) {398 if (/top|featured/i.test(session.message.text)) {399 session.send('you meant to **browse** playlist right? :)');400 session.beginDialog('BrowsePlaylists', { playlistquery: playlistquery && playlistquery.entity });401 } else {402 session.beginDialog('ShowPlaylistQueue');403 }404 } else if (clear) {405 session.beginDialog('ClearPlaylist');406 } else if (browse) {407 session.beginDialog('BrowsePlaylists', { playlistquery: playlistquery && playlistquery.entity });408 } else if (add || songtitle) {409 if (songtitle) {410 var trackQuery = songtitle.entity + (songartist ? ' artist:' + songartist.entity : '');411 session.beginDialog('AddMusic', {412 trackQuery413 });414 }415 } else {416 if (/playlist|queue/i.test(session.message.text)) {417 session.send('you meant to show queue right? :)');418 session.beginDialog('ShowPlaylistQueue');419 } else {420 session.endDialog('not sure what you mean there.');421 }422 }423}).triggerAction({424 matches: 'PlaylistControl'425}).cancelAction('cancelPlaylistControl', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });426const browseTypes = {427 '1. My Playlists' : 'user-playlists',428 '2. Featured' : 'featured-playlists',429 '3. Genres & Moods' : 'categories',430 '4. Charts' : 'charts',431 '5. Search' : 'search'432};433bot.dialog('BrowsePlaylists', [434 function(session, args, next) {435 if (args) {436 if (args.playlistquery) {437 next({438 response: {439 entity: Object.keys(browseTypes)[4],440 searchQuery: args.playlistquery441 }442 });443 return;444 } else if (args.selectedType) {445 next({446 response: {447 entity: args.selectedType448 }449 });450 return;451 }452 }453 Prompts.choice(session, 'pick one...', browseTypes, { listStyle: ListStyle['button'] });454 },455 async function (session, results, next) {456 if (results.response) {457 session.sendTyping();458 session.dialogData.selectedType = results.response.entity;459 var type = browseTypes[results.response.entity];460 if (type === 'categories') {461 var spotify = getSpotify(session, {462 resumeDialog: 'BrowsePlaylists',463 dialogArgs: {464 selectedType: results.response.entity465 }466 });467 if (spotify) {468 var categoriesData = await spotify.getBrowseCategories();469 if (categoriesData) {470 var categories = {};471 categoriesData.forEach((category) => {472 categories[category.name] = category.id;473 });474 session.dialogData.categories = categories;475 Prompts.choice(session, 'select your genre/mood...', categories, { listStyle: ListStyle['auto'] });476 }477 }478 } else if (type === 'search') {479 if (results.response.searchQuery) {480 session.send('searching for **%s**', results.response.searchQuery)481 next({ response: results.response.searchQuery })482 } else {483 Prompts.text(session, 'so what are you looking for?');484 }485 } else {486 next();487 }488 }489 },490 async function(session, results, next) {491 if (session.dialogData.selectedType) {492 var spotify = getSpotify(session, {493 resumeDialog: 'BrowsePlaylists',494 dialogArgs: {495 selectedType: session.dialogData.selectedType496 }497 });498 if (spotify) {499 var type = browseTypes[session.dialogData.selectedType];500 try {501 var options = {};502 if (type === 'categories') {503 if (results.response.entity) {504 options.categoryId = session.dialogData.categories[results.response.entity];505 options.shouldSearch = false; // should search for playlists506 } else {507 session.send('you must choose your mood :(');508 return session.endDialogWithResult({509 resumed: ResumeReason.notCompleted510 });511 }512 } else if (type === 'search') {513 if (results.response) {514 options.query = results.response;515 } else {516 session.send('you must be looking for something. try again later :)');517 return session.endDialogWithResult({518 resumed: ResumeReason.notCompleted519 });520 }521 }522 session.sendTyping();523 var data = await spotify.browsePlaylists(type, options);524 if (data && data.length > 0) {525 var playlists = {};526 data.forEach((playlist) => {527 playlists[playlist.name] = playlist;528 });529 session.dialogData.playlists = playlists;530 Prompts.choice(session, 'here\'s what I got. type the number or "cancel" ;)', playlists, { listStyle: ListStyle['auto'] });531 } else {532 session.send('nothing :(');533 session.endDialogWithResult();534 }535 } catch (err) {536 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));537 console.log(err);538 }539 }540 }541 },542 async function(session, results) {543 if (results.response) {544 if (results.response.entity && session.dialogData.playlists[results.response.entity]) {545 var playlist = session.dialogData.playlists[results.response.entity];546 var spotify = getSpotify(session);547 if (spotify) {548 try {549 await playPlaylist(session, spotify, playlist);550 } catch (err) {551 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));552 console.log(err);553 }554 }555 }556 }557 }558]).cancelAction('cancelBrowsePlaylists', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });559bot.dialog('ShowPlaylistQueue', [560 async function(session, args, next) {561 session.sendTyping();562 var spotify = getSpotify(session, {563 resumeDialog: 'ShowPlaylistQueue'564 });565 if (spotify) {566 try {567 var currentTrack = await spotify.getCurrentTrack();568 var data = await spotify.getPlaylistTracks(session.conversationData.spotifyPlaylist.owner.id, session.conversationData.spotifyPlaylist.id);569 if (data && data.length > 0) {570 var tracks = {};571 data.forEach((track) => {572 var text = currentTrack && currentTrack.id === track.id ?573 '**' + track.artists[0].name + ' - ' + track.name + '** ' + emoji.get('musical_note') :574 track.artists[0].name + ' - ' + track.name;575 tracks[text] = track;576 });577 session.dialogData.tracks = tracks;578 var card = createPlaylistCard(session, session.conversationData.spotifyPlaylist, false);579 var msg = new Message(session)580 .textFormat(TextFormat.markdown)581 .attachments([ card ]);582 session.send(msg);583 Prompts.choice(session, 'pick one or type "cancel" ;)', tracks, { listStyle: ListStyle['auto'] });584 } else {585 session.send('no tracks found in current playlist :(\n\nmaybe it\'s private. tsk.');586 session.endDialogWithResult();587 }588 } catch (err) {589 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));590 console.log(err);591 }592 }593 },594 async function(session, results, next) {595 if (results.response && results.response.entity) {596 var spotify = getSpotify(session, {597 resumeDialog: 'ShowPlaylistQueue'598 });599 if (spotify) {600 try {601 var track = session.dialogData.tracks[results.response.entity];602 await playTrack(session, spotify, track);603 session.endDialogWithResult();604 } catch (err) {605 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));606 console.log(err);607 }608 }609 }610 }611]).cancelAction('cancelShowPlaylistQueue', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });612bot.dialog('ClearPlaylist', [613 function(session, args) {614 Prompts.confirm(session, 'are you sure you want to clear our **bot queue**?');615 },616 async function(session, results) {617 session.sendTyping();618 var spotify = getSpotify(session, { resumeDialog: 'ClearPlaylist' });619 if (spotify) {620 if (results.response) {621 try {622 var result = await spotify.clearPlaylist(session.conversationData.spotifyBotPlaylist.id);623 if (result) {624 session.send('done (y)');625 } else {626 session.send('can\'t :(');627 }628 session.endDialogWithResult();629 } catch (err) {630 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));631 console.log(err);632 }633 } else {634 session.send('I thought so ;)');635 session.endDialogWithResult({636 resumed: ResumeReason.canceled637 });638 }639 }640 }641]);642bot.dialog('SongQuery', async function(session, args) {643 session.sendTyping();644 var spotify = getSpotify(session, { resumeDialog: 'SongQuery' });645 if (spotify) {646 try {647 const track = await spotify.getCurrentTrack();648 if (track) {649 session.send('here you go');650 var card = createTrackCard(session, track);651 var msg = new Message(session)652 .textFormat(TextFormat.markdown)653 .attachments([ card ]);654 session.send(msg);655 } else {656 session.send('nothing. try to say "play shape of you" ;)');657 }658 } catch (err) {659 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));660 console.log(err);661 }662 }663}).triggerAction({664 matches: 'SongQuery'665});666bot.dialog('ShowHelp', [667 function(session, args) {668 if (!session.conversationData.spotifyUser) {669 session.send('setup spotify by saying "init"');670 }671 if (!session.conversationData.spotifyDevice) {672 session.send('setup your device by saying "devices"');673 }674 var helps = [675 'browse',676 'play/queue shape of you',677 'play, pause, next, previous, etc.',678 'search for "top hits"',679 'show queue',680 'quit'681 ];682 session.send('command me by saying...\n\n- ' + helps.join('\n- '));683 Prompts.confirm(session, 'do you want more?');684 },685 function(session, results) {686 if (results.response) {687 var moreHelps = [688 'clear queue',689 'play track 5',690 'set volume 80%',691 'seek 2:00',692 'set repeat',693 'set shuffle',694 'what\'s playing?',695 'help'696 ];697 session.send('here\'s more I can do...\n\n- ' + moreHelps.join('\n- '));698 session.endDialogWithResult();699 } else {700 session.send([701 'I thought so ;)',702 'got it (y)',703 '(y)',704 ';)',705 'kool'706 ]);707 session.endDialogWithResult({708 resumed: ResumeReason.notCompleted709 });710 }711 }712]).triggerAction({713 matches: 'ShowHelp'714});715bot.dialog('PlayMusic', [716 async function(session, args, next) {717 if (!args) return session.endDialog();718 var trackQuery = null;719 var trackNumber = null;720 var playCommand = null;721 if (args.playTrackQuery) {722 trackQuery = args.playTrackQuery;723 } else if (args.playTrackNumber) {724 trackNumber = args.playTrackNumber;725 } else if (args.playCommand) {726 playCommand = args.playCommand;727 } else {728 if (args.intent) {729 var songtitle = EntityRecognizer.findEntity(args.intent.entities, 'songtitle');730 var songartist = EntityRecognizer.findEntity(args.intent.entities, 'songartist');731 var play = EntityRecognizer.findEntity(args.intent.entities, 'player_command::play');732 var number = EntityRecognizer.findEntity(args.intent.entities, 'builtin.number');733 if (songtitle) {734 trackQuery = songtitle.entity + (songartist ? ' artist:' + songartist.entity : '');735 } else if (play) {736 playCommand = true;737 trackNumber = number && number.entity;738 }739 }740 }741 var spotify = getSpotify(session, {742 resumeDialog: 'PlayMusic',743 dialogArgs: {744 playTrackQuery: trackQuery,745 playTrackNumber: trackNumber,746 playCommand: playCommand747 }748 });749 if (spotify) {750 try {751 if (trackQuery) {752 const tracks = await playTrackQuery(session, spotify, trackQuery);753 if (tracks && tracks.length > 1) {754 var artists = [];755 tracks.forEach((track) => {756 var artist = track.artists[0];757 var query = artist.name + ' - ' + track.name;758 if (artists.indexOf(query) === -1) {759 artists.push(query);760 }761 });762 Prompts.choice(session, 'found other versions too...', artists, { listStyle: ListStyle['button'] });763 }764 session.endDialog();765 } else {766 if (play) {767 if (trackNumber) {768 await playTrackNumber(session, spotify, parseInt(trackNumber));769 } else {770 var query = session.message.text.replace(play.entity, '').trim();771 if (query !== '') {772 session.dialogData.trackQuery = query;773 Prompts.confirm(session, 'are you looking for "' + query + '"?');774 } else {775 session.beginDialog('ApplyPlayerCommand', { command: 'play' });776 }777 }778 } else {779 session.endDialog();780 }781 }782 } catch (err) {783 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));784 console.log(err);785 }786 }787 },788 function(session, results) {789 if (results.response) {790 session.beginDialog('PlayMusic', { playTrackQuery: session.dialogData.trackQuery });791 }792 }793]).triggerAction({794 matches: 'PlayMusic'795});796bot.dialog('AddMusic', [797 async function(session, args) {798 if (!args) return session.endDialogWithResult();799 var trackQuery = args.trackQuery;800 if (trackQuery) {801 var spotify = getSpotify(session, {802 resumeDialog: 'AddMusic',803 dialogArgs: { queueTrack: trackQuery }804 });805 if (spotify) {806 try {807 var tracks = await queueTrack(session, spotify, trackQuery);808 if (tracks && tracks.length > 1) {809 var artists = [];810 tracks.forEach((track) => {811 var artist = track.artists[0];812 var query = artist.name + ' - ' + track.name;813 if (artists.indexOf(query) === -1) {814 artists.push(query);815 }816 });817 Prompts.choice(session, 'you might want to check some of these...', artists, { listStyle: ListStyle['auto'] });818 } else {819 session.endDialogWithResult();820 }821 } catch (err) {822 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));823 console.log(err);824 }825 }826 } else {827 session.endDialogWithResult();828 }829 },830 async function(session, results) {831 if (results.response) {832 if (results.response.entity) {833 var spotify = getSpotify(session);834 if (spotify) {835 try {836 await queueTrack(session, spotify, results.response.entity);837 session.send('(y)');838 } catch (err) {839 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));840 console.log(err);841 }842 session.endDialogWithResult();843 }844 } else {845 session.endDialogWithResult();846 }847 }848 }849]);850bot.dialog('SpotifySetDevice', [851 async function(session, args, next) {852 session.sendTyping();853 var spotify = getSpotify(session, {854 resumeDialog: 'SpotifySetDevice',855 dialogArgs: { playTrackQuery: args && args.playTrackQuery }856 });857 if (spotify) {858 var devices = {};859 try {860 var devicesData = await spotify.getDevices();861 if (devicesData && devicesData.length > 0) {862 devicesData.forEach((device) => {863 devices[device.type + ' - ' + device.name] = device;864 });865 session.dialogData.devices = devices;866 session.dialogData.playTrackQuery = args && args.playTrackQuery;867 if (devicesData.length > 1) {868 Prompts.choice(session, "which of these devices you want me use?", devices, { listStyle: ListStyle['button'] });869 } else {870 var defaultDevice = devicesData[0].type + ' - ' + devicesData[0].name;871 session.send('playing on device **%s**', defaultDevice);872 next({ response: { entity: defaultDevice } })873 }874 } else {875 session.send('no devices found. **open spotify** and try again :)');876 session.endDialogWithResult({877 resumed: ResumeReason.notCompleted878 });879 }880 } catch (err) {881 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));882 console.log(err);883 }884 }885 },886 async function(session, results) {887 session.sendTyping();888 if (results.response) {889 if (results.response.entity) {890 var device = session.dialogData.devices[results.response.entity];891 session.conversationData.spotifyDevice = device;892 session.send('(y)');893 var spotify = getSpotify(session, {894 resumeDialog: 'SpotifySetDevice',895 dialogArgs: { playTrackQuery: session.dialogData.playTrackQuery }896 });897 if (spotify) {898 try {899 await spotify.setDevice(device.id);900 if (session.dialogData.playTrackQuery) {901 await playTrackQuery(session, spotify, session.dialogData.playTrackQuery);902 }903 } catch (err) {904 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));905 console.log(err);906 }907 }908 session.endDialogWithResult();909 } else {910 session.send('no problem - going to use active device then ;)');911 session.endDialogWithResult();912 }913 }914 }915]).triggerAction({916 matches: /^(?:\@[\w-_]+\s+)?(?:show devices|list devices|devices|setup devices|setup device)/i917}).cancelAction('cancelSpotifySetDevice', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });;918bot.dialog('CreatePlaylist', [919 function(session, args, next) {920 if (args && args.name) {921 next({ response: args.name });922 } else {923 session.send('creating your playlist...');924 Prompts.text(session, 'what\'s the name?');925 }926 },927 async function(session, results) {928 session.sendTyping();929 var spotify = getSpotify(session, {930 resumeDialog: 'CreatePlaylist',931 dialogArgs: results.response932 });933 if (spotify) {934 if (results.response) {935 try {936 var playlist = await spotify.createPlaylist(results.response);937 if (playlist) {938 session.send('playlist **%s** created (y)', results.response);939 session.conversationData.spotifyBotPlaylist = playlist;940 if (!session.conversationData.spotifyPlaylist) {941 session.conversationData.spotifyPlaylist = playlist;942 }943 session.endDialogWithResult({944 response: { playlist }945 });946 } else {947 session.send('cannot create playlist :(');948 session.endDialogWithResult({949 resumed: ResumeReason.notCompleted950 });951 }952 } catch (err) {953 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));954 console.log(err);955 }956 }957 }958 }959]);960bot.dialog('SpotifyAuthorized', [961 async function(session, args, next) {962 session.sendTyping();963 try {964 // authorize spotify965 var tokenData = await Spotify.initToken(args.authCode);966 var data = await new Spotify(tokenData).init();967 if (data && tokenData) {968 session.send('thanks! just a moment...');969 session.conversationData.args = args;970 session.conversationData.spotifyUser = data.userData;971 session.conversationData.spotifyToken = tokenData;972 if (!data.playlist) {973 session.beginDialog('CreatePlaylist', { name: process.env.SPOTIFY_QUEUE_PLAYLIST_NAME });974 } else {975 session.conversationData.spotifyPlaylist = data.playlist;976 session.conversationData.spotifyBotPlaylist = data.playlist;977 next();978 }979 } else {980 session.send('something went wrong ;(... restarting over.');981 session.replaceDialog('AuthorizeSpotify');982 }983 } catch (err) {984 session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));985 console.log(err);986 }987 },988 function(session, results) {989 session.beginDialog('SpotifySetDevice');990 },991 async function(session, results) {992 var args = session.conversationData.args;993 if (args && args.dialog) {994 session.send('all set! now where were we...');995 session.beginDialog(args.dialog, args && args.dialogArgs);996 } else {997 session.endDialog('all set!');998 }999 }1000]);1001bot.dialog('AuthorizeSpotify', [1002 function(session, args) {1003 session.dialogData.resumeDialog = args.options && args.options.resumeDialog;1004 session.dialogData.dialogArgs = args.options && args.options.dialogArgs;1005 Prompts.confirm(session, args.message ? args.message : 'do you want me to use your spotify account to play music?');1006 },1007 function(session, results) {1008 if (results.response) {1009 var state = Buffer.from(JSON.stringify({1010 address: session.message.address,1011 dialog: session.dialogData.resumeDialog,1012 args: session.dialogData.dialogArgs1013 })).toString('base64');1014 session.send('good. click below to authorize me...');1015 var msg = new Message(session)1016 .attachments([1017 new HeroCard(session)1018 .title("accounts.spotify.com")1019 .subtitle("Authorize bot to play music, search and do some cool stuff.")1020 .tap(CardAction.openUrl(session, 'https://accounts.spotify.com/authorize?client_id=933adf0420af4eecb7d70cc8c7687d70&response_type=code&redirect_uri='+encodeURIComponent(process.env.SPOTIFY_REDIRECT_URI)+'&scope=user-read-playback-state+user-modify-playback-state+playlist-read-private+playlist-modify-public+user-library-read+user-read-private+user-read-email+user-follow-modify+playlist-read-collaborative+playlist-modify-private+user-library-modify+user-read-birthdate+user-follow-read+user-top-read&state=' + encodeURIComponent(state)))1021 ]);1022 session.endDialog(msg);1023 } else {1024 session.endDialog('k nvm');1025 }1026 }1027]).triggerAction({1028 matches: /^(?:\@[\w-_]+\s+)?(?:turn on|setup|init|start|load|reset)/i...

Full Screen

Full Screen

bot.js

Source:bot.js Github

copy

Full Screen

...695//=====================================================================//696// open the link towards seahorse rtbf prototype //697//=====================================================================//698function sendSeahorseCTA(session) {699 //session.send('After identification you are able to store your personal data setting.');700 var msg = new builder.Message(session).attachments([701 new builder.ThumbnailCard(session)702 .title('Identify yourself')703 .subtitle('After identification you are able to store your personal data setting.')704 .images([705 builder.CardImage.create(session, 'http://seahorse.alvis.io/files/seahorse_id.png')706 ])707 //.tap(builder.CardAction.openUrl(session, 'http://146.185.167.177:3000'))708 .tap(builder.CardAction.openUrl(session, 'http://localhost:4200'))709 ]);710 session.endDialog(msg);711}712//=========================================================713// Bots Dialogs714//=========================================================715bot.dialog('/',716 function (session, results) {717 var id = new Date().toLocaleString();718 var message = session.message;719 var messageText = session.message.text;720 var messageAttachments = session.message.attachments;721 var firsttimer_quotes = ['hello','hi','about','yo','wassa','hallo', 'get started'];722 var information_quotes = ['rtbf','information','more info','i want some information','need info','info','i am looking for information'];723 var help_quotes = ['help','what?','huh','help!','help?','/help'];724 var faul_quotes = ['nazi','fuck','bitch','idiot', 'nigger'];725 var thank_quotes = ['thanks','thank you', 'great','awesome', 'appreciated'];726 var bye_quotes = ['bye bye','bye','later','see ya'];727 var stop_quotes = ['stop','exit','quit','abort','cancel'];728 var datacontrolllers_quotes = ['google','apple','facebook','amazon','microsoft'];729 var explain_quotes = ['explain','explanation','explain this','explain please','explain this please'];730 var start_quotes = ['start','lets go','vamos','start process'];731 if (messageText != '') {732 // add url to perform api call GET733 if (messageText.toLowerCase() == 'test get') {734 session.send(sendThis('http://95.85.32.215:5000/rtbf/get'));735 }736 // if we capture that the payload contains such thing like "hello, hi, get started"737 else if (firsttimer_quotes.contains(messageText.toLowerCase())) {738 session.send('Welcome at Seahorse.')739 session.sendTyping();740 sleep(4000).then(function() {741 var replyMessage = quickReplyDefault(session)742 session.send(replyMessage);743 });744 }745 // if we capture that the payload contains the first "yes"746 else if (messageText.toLowerCase().startsWith('yes')) {747 session.send('Okay clear.')748 session.sendTyping();749 sleep(3000).then(function() {750 var replyMessage = quickReplyYes(session)751 session.send(replyMessage);752 });753 }754 // if we capture that the payload contains the first "no"755 else if (messageText.toLowerCase() == 'no') {756 session.sendTyping();757 sleep(3000).then(function() {758 var replyMessage = quickReplyNo(session)759 session.send(replyMessage)760 });761 }762 // if we capture that the payload contains the first "explain this"763 else if (explain_quotes.contains(messageText.toLowerCase())) {764 session.sendTyping();765 sleep(3000).then(function() {766 var replyMessage = quickReplyExplain(session)767 session.send(replyMessage)768 });769 }770 // if we capture that the payload contains the first "how"771 else if (messageText.toLowerCase() == 'how') {772 session.sendTyping();773 sleep(3000).then(function() {774 var replyMessage = quickReplyHow(session)775 session.send(replyMessage)776 });777 }778 // if we capture that the payload contains the first "why"779 else if (messageText.toLowerCase() == 'why') {780 session.sendTyping();781 sleep(3000).then(function() {782 var replyMessage = quickReplyWhy(session)783 session.send(replyMessage)784 });785 }786 // if we capture that the payload contains the first "process"787 else if (messageText.toLowerCase() == 'process') {788 session.sendTyping();789 sleep(3000).then(function() {790 var replyMessage = quickReplyProcess(session)791 session.send(replyMessage)792 });793 }794 // if we capture that the payload contains such thing like "Google or Facebook"?795 else if (start_quotes.contains(messageText.toLowerCase())) {796 session.sendTyping();797 sleep(2000).then(function() {798 var replyMessage = sendSeahorseCTA(session)799 session.send(replyMessage);800 });801 }802 // add url to perform api call ADD803 else if (messageText.toLowerCase() == 'test add') {804 session.send(addThis('http://95.85.32.215:5000/rtbf/add'));805 }806 // if faul language is send we caputure it and present this807 else if (faul_quotes.contains(messageText.toLowerCase())) {808 var msg = new builder.Message(session)809 .attachments([{810 contentType: "image/gif",811 contentUrl: "https://media.giphy.com/media/8yIngBRXYg8dq/giphy.gif"812 }]);813 session.endDialog(msg);814 session.send('I would like you not to use such language. This conversation has ended.')815 }816 // if people ask for "seahorse"817 else if (messageText.toLowerCase() == 'seahorse') {818 session.send('The seahorse crest is obvious ... why? Each and everyone will trust a Seahorse.');819 }820 // if people type answer about the "digital passport"?821 else if (messageText.toLowerCase().startsWith('digital passport?')) {822 session.sendTyping();823 sleep(6000).then(function() {824 //session.send('uPort: a self-sovereign identity system that allows people to own their identity, fully control the flow of their personal information, and authenticate themselves in various contexts - both on and off blockchain. We like to think of uport as our and the next mobile identity layer.')825 var replyMessage = quickReplyI(session)826 session.send(replyMessage);827 });828 }829 // if people type something which looks like to start the identification830 else if (messageText.toLowerCase().startsWith('start identification')) {831 session.sendTyping();832 sleep(2000).then(function() {833 //session.send('opening uPort ....... one moment')834 var replyMessage = sendSeahorseCTA(session);835 session.send(replyMessage);836 });837 }838 // if people type something which looks like a hashed string839 else if (messageText.toLowerCase().startsWith('0x')) {840 session.send('Thank you for entering the hash.')841 }842 // if we capture that the payload contains such thing like "thanks, thank you"843 else if (thank_quotes.contains(messageText.toLowerCase())) {844 session.sendTyping();845 sleep(2000).then(function() {846 session.send(':D')847 session.send('Much obliged. Thank you for using Seahorse - Right to be Forgotten service.')848 });849 }850 // if we capture that the payload contains such thing like "bye bye"851 else if (bye_quotes.contains(messageText.toLowerCase())) {852 session.sendTyping();853 sleep(2000).then(function() {854 session.send(':wave:, bye bye')855 });856 }857 // if we capture that the payload contains such thing like "/help or help"?858 else if (help_quotes.contains(messageText.toLowerCase())) {859 session.sendTyping();860 sleep(2000).then(function() {861 var replyMessage = helpButton(session)862 session.send(replyMessage)863 });864 }865 // if we capture that the payload contains such thing like "bye bye"866 else if (messageText.toLowerCase() == 'enter data policy') {867 session.sendTyping();868 sleep(2000).then(function() {869 var replyMessage = quickReplyDataControl(session)870 session.send(replyMessage)871 });872 }873 // if we capture that the payload contains such thing like "Google or Facebook"?874 else if (datacontrolllers_quotes.contains(messageText.toLowerCase())) {875 session.sendTyping();876 sleep(2000).then(function() {877 session.endDialog(quickReply(session))878 });879 }880 // if we capture that the payload contains such thing like "privacy"?881 else if (messageText.toLowerCase() == 'privacy') {882 session.sendTyping();883 sleep(3000).then(function() {884 session.send('Better data protection rules mean that you can be more confident about how your personal data is treated, particularly online.')885 session.send('These stronger data protection rules will help increase trust in online services.')886 var replyMessage = quickReplyA(session)887 session.send(replyMessage)888 });889 }890 // if we capture that the payload contains such thing like "privacy"?891 else if (messageText.toLowerCase() == 'gdpr') {892 session.sendTyping();893 // first894 sleep(4000).then(function() {895 session.send('GDPR are a set of EU regulations that enables the people to take control over there personal data.')896 // second897 session.sendTyping();898 sleep(5000).then(function() {899 session.send('It is hoped that these modernised and unified rules will allow businesses to make the most of the opportunities of the Digital Single Market by reducing regulation and benefiting from reinforced consumer trust.')900 // third901 session.sendTyping();902 sleep(3000).then(function() {903 var replyMessage = quickReplyA(session)904 session.send(replyMessage)905 });906 });907 });908 }909 // if we capture that the payload contains such thing like "data"?910 else if (messageText.toLowerCase() == 'personal data') {911 session.sendTyping();912 sleep(2000).then(function() {913 session.send('Increased responsibility and accountability for those processing personal data – through data protection risk assessments, data protection officers, and the principles of "data protection by design" and "data protection by default".')914 var replyMessage = quickReplyA(session)915 session.send(replyMessage)916 });917 }918 // if we capture that the payload contains such thing like "info or information"?919 else if (information_quotes.contains(messageText.toLowerCase())) {920 session.sendTyping();921 sleep(3000).then(function() {922 session.send('A right to be forgotten will help you manage data protection risks online. When you no longer want your data to be processed and there are no legitimate grounds for retaining it, the data will be deleted.')923 });924 sleep(8000).then(function() {925 session.send('The rules are about empowering individuals, not about erasing past events, re-writing history or restricting the freedom of the press.')926 session.send(quickReplyRTBF(session))927 });928 }929 // if we capture that the payload contains such thing like "what is this?"?930 else if (messageText.toLowerCase() == 'what is this?') {931 session.sendTyping();932 sleep(2000).then(function() {933 session.send('You can either upload an personal QR code (a barcode that represents you) or enter an personal hash. A hash is a string of characters (starting with 0x) also representing you.')934 var replyMessage = quickReplyC(session)935 session.send(replyMessage)936 });937 }938 // if we capture that the payload contains such thing like "what is seahorse?"?939 else if (messageText.toLowerCase() == 'what is seahorse?') {940 session.sendTyping();941 sleep(2000).then(function() {942 session.send('Seahorse is a simple and secure way to take control over your personal data. Seahorse stores your right to be forgotten setting in a vast ocean of vaults.')943 var replyMessage = quickReplyC(session)944 session.send(replyMessage)945 });946 }947 // if we capture that the payload contains such thing like "seahorse."?948 else if (messageText.toLowerCase() == 'seahorse.') {949 session.sendTyping();950 sleep(2000).then(function() {951 session.send('Seahorse is a simple and secure way to take control over your personal data. Seahorse stores your right to be forgotten setting in a vast ocean of vaults.')952 var replyMessage = quickReplyG(session)953 session.send(replyMessage)954 });955 }956 // if we capture that the payload contains such thing like "yes i do"957 else if (messageText.toLowerCase() == 'yes i do') {958 session.sendTyping();959 sleep(2000).then(function() {960 var replyMessage = quickReplyD(session)961 session.send(replyMessage)962 });963 }964 // if we capture that the payload contains such thing like "explain this please?"965 else if (messageText.toLowerCase() == 'explain this please') {966 session.sendTyping();967 sleep(2000).then(function() {968 session.send('Select the organisation (datacontroller) which will configured with the "Right to be Forgotten" setting. To use this configuration service you will need an QR code or Hash that has been obtained by an local government service.')969 session.sendTyping();970 });971 sleep(5000).then(function() {972 session.send('You will get an response in this channel when the setting has been activated.')973 session.sendTyping();974 var replyMessage = quickReplyDataControl(session)975 session.send(replyMessage)976 });977 }978 // if we capture that the payload contains such thing like "send qr code"979 else if (messageText.toLowerCase() == 'send qr code') {980 session.sendTyping();981 sleep(2000).then(function() {982 session.send('Excellent, please send us the QR image now. \n\nYou can do this by sending us an image (the actual QR code) from your device.')983 });984 }985 // if we capture that the payload contains such thing like "enter hash"986 else if (messageText.toLowerCase() == 'enter hash') {987 session.sendTyping();988 sleep(2000).then(function() {989 session.send('Awesome, please enter the hash string now. \n\nAn hash always starts with 0x')990 });991 }992 // if we capture that the payload contains such thing like "no please continue"993 else if (messageText.toLowerCase() == 'no please continue') {994 session.sendTyping();995 sleep(2000).then(function() {996 var replyMessage = quickReplyD(session)997 session.send(replyMessage)998 });999 }1000 // if we capture that the payload contains such thing like "no thanks"1001 else if (messageText.toLowerCase() == 'no thanks') {1002 session.sendTyping();1003 sleep(2000).then(function() {1004 var replyMessage = quickReplyE(session)1005 });1006 }1007 // if we capture that the payload contains such thing like stop we present this1008 else if (stop_quotes.contains(messageText.toLowerCase())) {1009 session.sendTyping();1010 sleep(2000).then(function() {1011 session.send(':wave: goodbye and have a nice day.')1012 });1013 }1014 // if we capture that the payload contains such thing like "other"1015 else if (messageText.toLowerCase() == 'other') {1016 session.sendTyping();1017 sleep(2000).then(function() {1018 session.send('We are very gratefull if you now enter the datacontroller that you want to configure with the "Right to be Forgotten".')1019 });1020 }1021 // if we capture that the payload contains such thing like "leo"1022 else if (messageText.toLowerCase() == 'leo') {1023 session.sendTyping();1024 sleep(2000).then(function() {1025 session.send('Got it. That is my master. Do you want to meet him ...')1026 });1027 }1028 // everything else that has been captured and not known will result in this response1029 else if (messageText != '') {1030 session.send('Sorry my NLP is not up to date. I am just a simple bot, please type /help')1031 }1032 } else {1033 //============================================================//1034 // get image //1035 // send towards external qrserver and read api //1036 // present data that comes from api //1037 //============================================================//1038 var URI = encodeURIComponent(message.attachments[0].contentUrl)1039 var data = JSON.parse(httpGet('http://api.qrserver.com/v1/read-qr-code/?fileurl=' + URI));1040 session.send('One moment please while we quickly process the QR code')1041 session.sendTyping();1042 sleep(5000).then(function() {1043 session.send('This is the hashed code you send us: ')1044 session.send(data[0].symbol[0].data);1045 session.send('Much obliged the attachment received and processed')1046 });1047 }1048 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...41 var userId = session.message.user.id;42 var question = session.message.text;43 if(question.indexOf('食堂')!=-1 || question.indexOf('餐厅')!=-1 || question.indexOf('餐饮')!=-1 || question.indexOf('吃')!=-1){44 var msg = cards.createCards["cardCanteen"](session); 45 session.send(msg);46 return;47 }else if(question.indexOf('校车')!=-1){48 var msg = cards.createCards["cardShuttle"](session); 49 session.send(msg);50 return;51 }else if(question.indexOf('巴士')!=-1){52 var msg = cards.createCards["cardBus"](session); 53 session.send(msg);54 return;55 }else if(question.indexOf('校歌')!=-1){56 var msg = cards.createCards["cardAnthem"](session); 57 session.send(msg);58 return;59 }else if(question.indexOf('你会')!=-1){60 var msg = cards.createCards["cardHelp"](session); 61 session.send(msg);62 return;63 }64 myio.write(question);65 if(userInfo[userId]==undefined) userInfo[userId] = new Array();66 var question_temp = question.split("#");67 userInfo[userId]['speakerName']='未知';68 if(question_temp.length>1){69 if(question_temp[1]!='未知'){70 userInfo[userId]['speakerName'] = question_temp[1];71 }72 }73 question = question_temp[0];74 var q_type = question.substring(0,4);75 // 仅仅用于测试76 if(q_type=='demo'){77 question = question.substring(4,question.length);78 QBH.askQnAMakerDemo(question,function(answers){79 var answer = answers[0].answer;80 if(userInfo[userId]['speakerName']!='未知'){81 answer = answer.replace('[人名]',userInfo[userId]['speakerName']);82 }else{83 answer = answer.replace('[人名]','');84 }85 if(answer=='No good match found in the KB')86 {87 QBH.askBing(question,function(webPages){88 var msg = cards.createCards["cardBing"](session,webPages); 89 session.send(msg);90 });91 return92 }93 console.log(answer)94 if(cards.isCard(answer)){95 var msg = cards.createCards[answer](session); 96 session.send(msg);97 }else if(answer=='From:上海交通大学闵行校区李政道图书馆;To:上海交通大学闵行校区软件学院'){98 session.send(answer);99 session.send('软件学院与李政道图书馆距离较远,建议乘坐校车!');100 }else if(answer=='我不知道'){101 session.send(answer);102 QBH.askBing(question,function(webPages){103 var msg = cards.createCards["cardBing"](session,webPages); 104 session.send(msg);105 });106 }else{107 session.send(answer);108 }109 });110 return;111 }112 if(ga.isHalfPhase(userInfo[userId]['PromptStatus'])){ //如果当前处于一半处问答113 var qentitiesold = userInfo[userId]['LastEntities'];114 var qrelation = userInfo[userId]['LastRelation'];115 var PromptStatus = userInfo[userId]['PromptStatus'];116 ga.getHalfAnswer(question,qentitiesold,qrelation,PromptStatus,117 function(answer){118 //问课程的回掉119 session.send(answer)120 },121 function(answer){122 //问考试的回掉123 session.send(answer)124 },125 function(answer){126 //问路程的回掉127 session.send(answer)128 },129 function(username){130 //Login的回调131 userInfo[userId]['PromptStatus'] = 'RegisterHalf';132 userInfo[userId]['Login'] = username;133 console.log('userName',username);134 session.send('Please input your pwd');135 },136 function(){137 //Register的回调138 session.send('你好: '+userInfo[userId]['Login']);139 userInfo[userId]['PromptStatus'] = 'Complete';140 // session.send('Your User Name is '+userInfo[userId]['Login']);141 if(userInfo[userId]['LastIntent']=='SearchCalendar'){142 var res = GAS.getCalendarData(userInfo[userId]['LastTimes'],userInfo[userId]['Login']);143 session.send(res);144 }else if(userInfo[userId]['LastIntent'] == 'AddCalendar'){145 GAS.addCalendarData(userInfo[userId]['LastTimes'],userInfo[userId]['Login'],userInfo[userId]['CalContent']);146 session.send('Add Calendar Success');147 }148 }149 );150 userInfo[userId]['PromptStatus'] = 'Complete';151 userInfo[userId]['LastRelation'] = '';152 userInfo[userId]['LastEntities'] = '';153 }else{154 ga.getAnswer(question,userInfo[userId]['LastQuestionEntity'],userInfo[userId]['LastEntity'],userInfo[userId]['LastRelation'],dataset,155 function(answer,qentities){156 //问Path的回掉157 if(answer == 'LackInfoPath'){158 userInfo[userId]['PromptStatus'] = 'PathHalf';159 userInfo[userId]['LastEntities'] = qentities;160 session.send('请完善您的出发点目的地信息');161 }else{162 session.send(answer);163 }164 },165 function(answer,qentities){166 // var answer = "cardShuttle";167 168 if(cards.isCard(answer)){169 var msg = cards.createCards[answer](session); // 返回card生成的msg170 session.send(msg);171 }else if(answer == 'i dont know'){172 QBH.askBing(question,function(webPages){173 var msg = cards.createCards["cardBing"](session,webPages);174 session.send(msg); 175 //session.send(webPages[0].name);176 //console.log('bing',webPages[0].name);177 }); 178 }else{179 session.send(answer);180 }181 userInfo[userId]['LastQuestionEntity'] = answer;182 },183 function(answer,qentities,qrelation){184 //AskLessonCallBack185 console.log(answer,qentities,qrelation);186 if(answer == 'LackInfoLesson'){187 userInfo[userId]['PromptStatus'] = 'LessonHalf';188 userInfo[userId]['LastEntities'] = qentities;189 userInfo[userId]['LastRelation'] = qrelation;190 session.send('缺少信息 需要任课教师和课程名');191 }else{192 session.send(answer);193 }194 },195 function(answer,qentities,qrelation){196 //AskExamCallBack197 console.log(answer,qentities,qrelation);198 console.log('exam');199 if(answer == 'LackInfoExam'){200 userInfo[userId]['PromptStatus'] = 'ExamHalf';201 userInfo[userId]['LastEntities'] = qentities;202 userInfo[userId]['LastRelation'] = qrelation;203 session.send('缺少考试信息 需要任课教师和课程名');204 }else{205 session.send(answer);206 }207 },208 function(answer){209 //AskQnaMaker 210 if(answer=='No good match found in the KB')211 {212 QBH.askBing(question,function(webPages){213 var msg = cards.createCards["cardBing"](session,webPages); 214 session.send(msg);215 });216 return217 }else{218 session.send(answer);219 }220 },221 function(){222 //Login223 userInfo[userId]['PromptStatus'] = 'LoginHalf';224 session.send('请输入用户名哦~');225 },226 function(){227 //Logout228 userInfo[userId]['Login'] = undefined;229 session.send('退出成功');230 },231 function(times){232 //SearchCalen233 if(userInfo[userId]['Login'] == undefined){234 session.send('请先登录并输入您的用户名哦');235 userInfo[userId]['PromptStatus'] = 'LoginHalf';236 userInfo[userId]['LastIntent'] = 'SearchCalendar';237 }else{238 var res = GAS.getCalendarData(times,userInfo[userId]['Login']);239 userInfo[userId]['LastTimes'] = times;240 session.send(res);241 }242 },243 function(times,content){244 //AddCalen245 if(userInfo[userId]['Login'] == undefined){246 session.send('请先登录并输入您的用户名哦');247 userInfo[userId]['PromptStatus'] = 'LoginHalf';248 userInfo[userId]['LastIntent'] = 'AddCalendar';249 userInfo[userId]['CalContent'] = content;250 userInfo[userId]['LastTimes'] = times;251 console.log(times);252 }else{253 GAS.addCalendarData(times,userInfo[userId]['Login'],content);254 session.send('添加行程成功');255 }256 },257 function(res){258 //查看小组自习室259 session.send(res);260 },261 function(res){262 //预约小组自习室263 if(userInfo[userId]['Login'] == undefined){264 session.send('请先登录并输入您的用户名哦');265 userInfo[userId]['PromptStatus'] = 'LoginHalf';266 }else{267 session.send(res);268 }269 },270 function(ans){271 //BingCallBack272 session.send('我们推荐来自Bing的结果'+ans);273 }274 );275 }276 277 }278]);279if (useEmulator) {280 var restify = require('restify');281 var server = restify.createServer();282 server.listen(3978, function() {283 console.log('test bot endpont at http://localhost:3978/api/messages');284 });285 server.post('/api/messages', connector.listen()); 286} else {...

Full Screen

Full Screen

nlp_recomm.js

Source:nlp_recomm.js Github

copy

Full Screen

...69// Handling the Greeting intent. 70dialog.matches('Welcome', function (session, args, next) {71 console.log ('in welcome intent'); 72 var username = session.message;73 session.send("Hello " +username.address.user.name+ ". " +WishMe());74 session.send("Can I help you in anything. Feel free to ask");75 session.userData.ocassion = "";76 session.endDialog();77})78dialog.matches('Vacation', function (session, args, next) {79 console.log ('in vacation intent ');80 var vacation = builder.EntityRecognizer.findEntity(args.entities, 'Vacation');81 var place = builder.EntityRecognizer.findEntity(args.entities, 'Vacation::country'); 82 session.userData = {83 vacation: vacation ? vacation.entity : "",84 place: place ? place.entity : "",85 ocassion: "vacation"86 };87 if(session.userData.vacation == ""){88 if(session.userData.place != ""){ session.userData.vacation = "vacation"; }}89 if(session.userData.place == ""){90 session.beginDialog("/Ask Place");91 }else {92 session.send(session.userData.place + " is a beautiful place to go for a " +session.userData.vacation+ ".");93 session.beginDialog("/RecommendVac");94 } 95})96 97dialog.matches('Office', function (session, args, next) {98 console.log ('in office intent ');99 var office = builder.EntityRecognizer.findEntity(args.entities, 'Office');100 var place = builder.EntityRecognizer.findEntity(args.entities, 'Vacation::country'); 101 session.userData = {102 office: office ? office.entity : "",103 place: place ? place.entity : "",104 ocassion: "office"105 };106 session.send("Cool, Dressing professionally is vital for success in an office. We will help you look formal in your " +session.userData.office+".");107 session.beginDialog("/Recommend");108})109dialog.matches('Sports', function (session, args, next) {110 console.log ('in sports intent ');111 var sports = builder.EntityRecognizer.findEntity(args.entities, 'Sports');112 var game = builder.EntityRecognizer.findEntity(args.entities, 'Sports::Games'); 113 session.userData = {114 sports: sports ? sports.entity : "",115 game: game ? game.entity : "",116 ocassion: "sports"117 };118 if(session.userData.sports == ""){119 if(session.userData.game != ""){ session.userData.sports = "sports"; }}120 if(session.userData.game == ""){121 session.beginDialog("/Ask Game");122 }123 session.send("Best of luck for the coming competiton. We know what are the required things for the "+session.userData.game+" competition.");124 session.beginDialog("/Recommend");125})126dialog.matches('Gym', function (session, args, next) {127 console.log ('in gym intent ');128 var gym = builder.EntityRecognizer.findEntity(args.entities, 'Gym');129 session.userData = {130 gym: gym ? gym.entity : "",131 ocassion: "gym"132 };133 session.send(session.userData.gym+" is a must to live a healthy and a long life.");134 session.beginDialog("/Recommend");135})136bot.dialog('/Recommend', function (session, args) {137 console.log("in recommend dialog");138 session.send("Would you like me to recommend some necessary things you will be needing?")139 session.endDialog();140});141bot.dialog('/RecommendVac', function (session, args) {142 console.log("in recommend dialog");143 weatherApi(session.userData.place, function(weather){144 var temp = parseInt(parseInt(weather.main.temp_max)-273);145 if(temp<=20){146 session.userData.temp = "cold";147 session.send(session.userData.place+ " is a very cold place. At this time in the year, there the temperature will be usually near to "+(parseInt(temp/10))*10 +'\xB0C');148 session.send("Would you like me to recommend some necessary things you will be needing?")149 }else if(temp>=25){150 session.userData.temp = "hot";151 session.send(session.userData.place+ " is a hot place. At this time in the year, there the temperature will be usually near to "+((parseInt((temp/10))*10)+10) +'\xB0C');152 session.send("Would you like me to recommend some necessary things you will be needing?")153 }154 155 });156 session.endDialog();157});158dialog.matches('Yes', function (session, args) {159 session.beginDialog('/' +session.userData.ocassion);160})161dialog.matches('No', function (session, args) {162 session.send('OK, What are you looking for?');163 session.endDialog();164})165bot.dialog('/Ask Place', function (session, args) {166 console.log("in Ask place dialog");167 session.send("A "+session.userData.ocassion);168 session.send("That's nice. Where are you going to?");169 session.endDialog();170});171bot.dialog('/Ask Game', function (session, args) {172 console.log("in Ask game dialog");173 session.send("Which "+session.UserData.sports+" are you going to play?");174 session.endDialog();175});176bot.dialog('/vacation', function (session, args) {177 session.send("Make your vacation more memorable and safe by taking all the items that are shown below");178 if(session.userData.temp == "cold"){179 session.send("1. Base layer shirt with long-sleeves");180 session.send("2. Winter Coat/Jacket, should be water resistant"); 181 session.send("3. Walking/Hiking Boots with Woollen Socks"); 182 session.send("4. Other accessories like gloves, a scarf and a hat");183 if(session.userData.vacation == "treking"){session.send("5. A Treking shoe");}184 session.endDialog();185 }else if(session.userData.temp == "hot"){186 session.send("1. Sun Glasses"); 187 session.send("2. Dress/Running Shoes and Sandals"); 188 session.send("3. Sun Hat with light/thin Scarf"); 189 session.send("4. Other accessories like Sunscreen, Insulated Water Bottle, A towel and Light material clothes");190 session.endDialog();191 }192})193bot.dialog('/office', function (session, args) {194 if((session.userData.office == "office")||(session.userData.office =="work")){195 session.send("If your office does not have written dress code, 'Business Casuals' is a better option for work. \nHave a look at these, just in case you might be needing");196 session.send("1. Shirts that have collars");197 session.send("2. Dress pants/ Khakis/ Trousers"); 198 session.send("3. Dress shoes with dress socks"); 199 session.send("4. Pairing Sweater vest"); 200 session.send("5. Other accessories like tie, belt and a watch");201 session.endDialog();202 }else if(session.userData.office == "conference"){203 session.send("Firstly Verify whether or not the conference you attend has any guidelines for dress. \nHere is the list of few things we are thinking that you might need.");204 session.send("1. Blazer / Sports Jacket");205 session.send("2. Dress Pants / Khakis"); 206 session.send("3. Collared shirt or Polo shirt"); 207 session.send("4. Dress Shoes with matching socks"); 208 session.send("5. Other accessories like tie, belt and a watch");209 session.endDialog();210 }211})212bot.dialog('/sports', function (session, args) {213 if((session.userData.office == "office")||(session.userData.office =="work")){214 session.send("If your office does not have written dress code, 'Business Casuals' is a better option for work. \nHave a look at these, just in case you might be needing");215 session.send("1. Shirts that have collars");216 session.send("2. Dress pants/ Khakis/ Trousers"); 217 session.send("3. Dress shoes with dress socks"); 218 session.send("4. Pairing Sweater vest"); 219 session.send("5. Other accessories like tie, belt and a watch");220 session.endDialog();221 }else if(session.userData.office == "conference"){222 session.send("Firstly Verify whether or not the conference you attend has any guidelines for dress. \nHere is the list of few things we are thinking that you might need.");223 session.send("1. Blazer / Sports Jacket");224 session.send("2. Dress Pants / Khakis"); 225 session.send("3. Collared shirt or Polo shirt"); 226 session.send("4. Dress Shoes with matching socks"); 227 session.send("5. Other accessories like tie, belt and a watch");228 session.endDialog();229 }230})231bot.dialog('/gym', function (session, args) {232 session.send("“It’s dangerous to go alone! Take this.”");233 session.send("1. Light weight and supportive shoe and socks. you may prefer lifting shoes to traditional cross-trainers or running shoes.");234 session.send("2. Some breathable, well-fitted clothing. Shorts and Tshirts"); 235 session.send("3. A gym bag"); 236 session.send("4. Music Headphones/ipod"); 237 session.send("5. Other accessories like water-bottle, Towel, Sweat bands etc., ");238 session.endDialog();239})240// Handling unrecognized conversations.241dialog.matches('None', function (session, args) {242 console.log ('in none intent'); 243 session.send("I am sorry! I am a bot, perhaps not programmed to understand this command");244 session.endDialog(); 245});246// Setup Restify Server247var server = restify.createServer();248server.post('/api/messages', connector.listen());249server.listen(process.env.port || 5000, function () {250 console.log('%s listening to %s', server.name, server.url); ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const { chromium } = require("playwright");3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await qawolf.register(page, "test");8 await page.click("input[name=\"q\"]");9 await page.fill("input[name=\"q\"]", "qawolf");10 await page.press("input[name=\"q\"]", "Enter");11 await page.click("text=QA Wolf: End-to-end Browser Testing for Developers");12 await qawolf.teardown(browser);13})();14const qawolf = require("qawolf");15describe("test", () => {16 let browser;17 let page;18 beforeAll(async () => {19 browser = await qawolf.launch();20 page = await qawolf.createPage(browser);21 });22 afterAll(async () => {23 await qawolf.stopVideos();24 await browser.close();25 });26 it("test", async () => {27 await page.click("input[name=\"q\"]");28 await page.fill("input[name=\"q\"]", "qawolf");29 await page.press("input[name=\"q\"]", "Enter");30 await page.click("text=QA Wolf: End-to-end Browser Testing for Developers");31 });32});33import { Browser, Page } from "playwright";34import qawolf from "qawolf";35describe("test", () => {36 let browser: Browser;37 let page: Page;38 beforeAll(async () => {39 browser = await qawolf.launch();40 page = await qawolf.createPage(browser);41 });42 afterAll(async () => {43 await qawolf.stopVideos();44 await browser.close();45 });46 it("test", async () => {47 await page.click("input[name=\"q\"]");48 await page.fill("input[name=\"q\"]", "qawolf");49 await page.press("input[name=\"q\"]", "Enter");50 await page.click("text=QA Wolf: End-to

Full Screen

Using AI Code Generation

copy

Full Screen

1const { send } = require("qawolf");2const { click } = require("qawolf");3const { type } = require("qawolf");4const { check } = require("qawolf");5const { waitFor } = require("qawolf");6const { press } = require("qawolf");7const { waitForNavigation } = require("qawolf");8const { waitForSelector } = require("qawolf");9const { uncheck } = require("qawolf");10const { select } = require("qawolf");11const { scrollTo } = require("qawolf");12const { dragAndDrop } = require("qawolf");13const { hover } = require("qawolf");14const { waitForFunction } = require("qawolf");15const { waitForResponse } = require("qawolf");16const qawolf = require("qawolf");17const session = qawolf.createSession();18const browser = session.browser();19const page = session.page();20const context = session.context();21const url = session.url();22const html = session.html();23const text = session.text();

Full Screen

Using AI Code Generation

copy

Full Screen

1await session.send({ type: 'keydown', keyCode: 'KeyA' });2await session.send({ type: 'keyup', keyCode: 'KeyA' });3await session.send({ type: 'keydown', keyCode: 'KeyB' });4await session.send({ type: 'keyup', keyCode: 'KeyB' });5await session.send({ type: 'keydown', keyCode: 'KeyC' });6await session.send({ type: 'keyup', keyCode: 'KeyC' });7await session.fill('input[type="text"]', 'abc');8await session.click('button');9await session.check('input[type="checkbox"]');10await session.uncheck('input[type="checkbox"]');11await session.select('select', '1');12await session.hover('button');13await session.focus('input[type="text"]');14const text = await session.evaluate(() => document.querySelector('button').textContent);15console.log(text);16await session.waitFor('button');17await session.waitForFunction(() => document.querySelector('button').textContent === 'abc');18await session.waitForNavigation();19await session.waitForSelector('button');20await session.waitForTimeout(1000);

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const { Browser, chromium } = require("playwright-chromium");3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 const qawolfPage = await qawolf.register(page);8 await qawolfPage.type('[name="q"]', "qawolf");9 await qawolfPage.click('input[value="Google Search"]');10 await qawolfPage.waitForSelector("text=QA Wolf: Test automation for web apps");11 await qawolfPage.click("text=QA Wolf: Test automation for web apps");12 await qawolfPage.waitForSelector("#home");13 await qawolfPage.click("text=Sign up");14 await qawolfPage.waitForSelector("#signup");15 await qawolfPage.type('[name="email"]', "

Full Screen

Using AI Code Generation

copy

Full Screen

1const { session } = require('qawolf');2const { test, expect } = require('@playwright/test');3test.describe('test', () => {4 test.beforeEach(async ({ page }) => {5 });6 test('test', async ({ page }) => {7 await page.fill('input[aria-label="Search"]', 'qawolf');8 await page.click('text=Google Search');9 await page.waitForSelector('.g');10 await session.record(page, 'test');11 });12});13const { session } = require('qawolf');14const { test, expect } = require('@playwright/test');15test.describe('test', () => {16 test.beforeEach(async ({ page }) => {17 });18 test('test', async ({ page }) => {19 await session.play(page, 'test');20 await page.click('text=QAWolf: QA Automation for Web Apps');21 });22});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run qawolf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful