###前提・実現したいこと
LINEBOTでユーザが入力する言葉によって異なる返答を実装しようとしています。
参考サイト
###発生している問題・エラーメッセージ
以下のようなソースコードで実装してみると返答がこないという状況が発生しています。
###該当のソースコード
javascript
1'use strict'; 2 3const http = require('http'); 4const https = require('https'); 5const crypto = require('crypto'); 6 7const HOST = 'api.line.me'; 8const REPLY_PATH = '/v2/bot/message/reply';//リプライ用 9const CH_SECRET = 'xxxxxxxx'; //Channel Secretを指定 10const CH_ACCESS_TOKEN = 'xxxxxx'; //Channel Access Tokenを指定 11const SIGNATURE = crypto.createHmac('sha256', CH_SECRET); 12const PORT = 3000; 13 14/** 15 * httpリクエスト部分 16 */ 17const client = (replyToken, SendMessageObject) => { 18 let postDataStr = JSON.stringify({ replyToken: replyToken, messages: SendMessageObject }); 19 let options = { 20 host: HOST, 21 port: 443, 22 path: REPLY_PATH, 23 method: 'POST', 24 headers: { 25 'Content-Type': 'application/json; charset=UTF-8', 26 'X-Line-Signature': SIGNATURE, 27 'Authorization': `Bearer ${CH_ACCESS_TOKEN}`, 28 'Content-Length': Buffer.byteLength(postDataStr) 29 } 30 }; 31 32 return new Promise((resolve, reject) => { 33 let req = https.request(options, (res) => { 34 let body = ''; 35 res.setEncoding('utf8'); 36 res.on('data', (chunk) => { 37 body += chunk; 38 }); 39 res.on('end', () => { 40 resolve(body); 41 }); 42 }); 43 44 req.on('error', (e) => { 45 reject(e); 46 }); 47 req.write(postDataStr); 48 req.end(); 49 }); 50}; 51 52http.createServer((req, res) => { 53 if(req.url !== '/' || req.method !== 'POST'){ 54 res.writeHead(200, {'Content-Type': 'text/plain'}); 55 res.end('こんにちは'); 56 } 57 58 let body = ''; 59 req.on('data', (chunk) => { 60 body += chunk; 61 }); 62 req.on('end', () => { 63 if(body === ''){ 64 console.log('bodyが空です。'); 65 return; 66 } 67 68 let WebhookEventObject = JSON.parse(body).events[0]; 69 console.log(WebhookEventObject); 70 //メッセージが送られて来た場合 71 //「今日の天気は」と聞かれた時のみ返答をする 72 if(WebhookEventObject.type === 'message'){ 73 let SendMessageObject; 74 if(WebhookEventObject.message.type === 'text'){ 75 if(WebhookEventObject == "今日の天気は"){ 76 SendMessageObject = [{ 77 type: 'text', 78 text: WebhookEventObject.message.text 79 }]; 80 } 81 client(WebhookEventObject.replyToken, SendMessageObject) 82 .then((body)=>{ 83 console.log(body); 84 },(e)=>{console.log(e)}); 85 } 86 87 res.writeHead(200, {'Content-Type': 'text/plain'}); 88 res.end('su'); 89 } 90 }); 91 92}).listen(PORT); 93 94console.log(`Server running at ${PORT}`);
回答1件
あなたの回答
tips
プレビュー