Guest User

Untitled

a guest
Apr 24th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. 'use strict';
  2.  
  3. require('dotenv').config();
  4. const line = require('@line/bot-sdk');
  5. const Datastore = require('@google-cloud/datastore');
  6.  
  7. const config = {
  8. channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
  9. channelSecret: process.env.CHANNEL_SECRET,
  10. };
  11.  
  12. const datastore = Datastore();
  13. const client = new line.Client(config);
  14.  
  15. function handleEvent(event) {
  16. console.log(event);
  17. var message = '';
  18.  
  19. const query = datastore.createQuery(event.message.type);
  20. return datastore.runQuery(query).then((results) => {
  21. const messages = results[0];
  22. message = messages[Math.floor(Math.random() * messages.length)].text;
  23.  
  24. const echo = { type: 'text', text: message };
  25. return client.replyMessage(event.replyToken, echo);
  26. });
  27. }
  28.  
  29. exports.handler = function echoBot (req, res) {
  30. const signature = req.get('x-line-signature');
  31.  
  32. if (!signature) {
  33. throw new line.SignatureValidationFailed("no signature");
  34. }
  35.  
  36. if (!line.validateSignature(req.rawBody, config.channelSecret, signature)) {
  37. throw new line.SignatureValidationFailed("signature validation failed", signature);
  38. }
  39.  
  40. Promise
  41. .all(req.body.events.map(handleEvent))
  42. .then(result => res.status(200).send(`Success: ${result}`))
  43. .catch(err => res.status(400).send(err.toString()));
  44. };
Add Comment
Please, Sign In to add comment