Advertisement
Guest User

Untitled

a guest
Aug 10th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.18 KB | None | 0 0
  1. // See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
  2. // for Dialogflow fulfillment library docs, samples, and to report issues
  3.  
  4. 'use strict';
  5.  
  6. const GIPHY_API_KEY = 'PnVMwRkKIwtQsTxEUruFJpPe8tYdySPP';
  7. const SEARCH_RESULTS_MORE = [
  8. 'Вот ещё пара гифок!',
  9. 'Надеюсь, эти тебе тоже понравятся.',
  10. 'На, лови еще парочку. Если что, у меня ещё есть 😉.',
  11. ];
  12. const SEARCH_RESULTS = [
  13. 'Хе-хе, сейчас покажу мои любимые.',
  14. 'Лови, отличная подборка гифок.',
  15. 'Смотри, что я нашел!',
  16. ];
  17.  
  18. // Import the Dialogflow module from the Actions on Google client library.
  19. const { dialogflow, Carousel, BrowseCarouselItem, BrowseCarousel, Suggestions, Image } = require('actions-on-google');
  20. // Import the firebase-functions package for deployment.
  21. const functions = require('firebase-functions');
  22. // Import the request-promise package for network requests.
  23. const request = require('request-promise');
  24.  
  25. // Instantiate the Dialogflow client.
  26. const app = dialogflow({ debug: true });
  27.  
  28. function getCarouselItems(data) {
  29. var carouselItems = [];
  30. data.slice(0, 10).forEach(function (gif) {
  31. carouselItems.push(new BrowseCarouselItem({
  32. title: gif.title || gif.id,
  33. url: gif.url,
  34. image: new Image({
  35. url: gif.images.downsized_medium.url,
  36. alt: gif.images.downsized_medium.url,
  37. }),
  38. }));
  39. });
  40. return carouselItems;
  41. }
  42.  
  43. function search(conv, query, offset) {
  44. // Send the GET request to GIPHY API.
  45. return request({
  46. method: 'GET',
  47. uri: 'https://api.giphy.com/v1/gifs/search',
  48. qs: {
  49. "api_key": GIPHY_API_KEY,
  50. 'q': query,
  51. 'limit': 10,
  52. 'offset': offset,
  53. 'lang': 'ru'
  54. },
  55. json: true,
  56. resolveWithFullResponse: true,
  57. }).then(function (responce) {
  58. // Handle the API call success.
  59. console.log(responce.statusCode + ': ' + responce.statusMessage);
  60. console.log(JSON.stringify(responce.body));
  61. // Obtain carousel items from the API call response.
  62. var carouselItems = getCarouselItems(responce.body.data);
  63. // Validate items count.
  64. if (carouselItems.length <= 10 && carouselItems.length >= 2) {
  65. conv.data.query = query;
  66. conv.data.offset = responce.body.pagination.count + responce.body.pagination.offset;
  67. conv.data.paginationCount = conv.data.paginationCount || 0;
  68. conv.data.searchCount = conv.data.searchCount || 0;
  69. // Show successful response.
  70. if (offset == 0) {
  71. conv.ask(SEARCH_RESULTS[conv.data.searchCount % SEARCH_RESULTS.length]);
  72. conv.data.searchCount++;
  73. } else {
  74. conv.ask(SEARCH_RESULTS_MORE[conv.data.paginationCount % SEARCH_RESULTS_MORE.length]);
  75. conv.data.paginationCount++;
  76. }
  77. conv.ask(new BrowseCarousel({ items: carouselItems }));
  78. conv.ask(new Suggestions(`Ещё`));
  79. } else {
  80. // Show alternative response.
  81. conv.ask('Ничего не смог найти по такому запросу, может поищем что-то другое?)');
  82. }
  83. }).catch(function (error) {
  84. // Handle the API call failure.
  85. console.log(error);
  86. conv.ask('Извини, кажется альбом с гифками потерялся 😩');
  87. });
  88. }
  89. // Handle the Dialogflow intent named 'Search Intent'.
  90. // The intent collects a parameter named 'query'.
  91. app.intent('Search Intent', (conv, { query }) => {
  92. return search(conv, query, 0);
  93. });
  94.  
  95. // Handle the Dialogflow intent named 'Search Intent - more'.
  96. app.intent('Search Intent - more', (conv) => {
  97. // Load more gifs from the privious search query
  98. return search(conv, conv.data.query, conv.data.offset);
  99. });
  100.  
  101. // Set the DialogflowApp object to handle the HTTPS POST request.
  102. exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement