質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Facebook Graph API

Facebook Graph APIとは Facebookのグラフデータベース用のAPIであり、対応言語はPHP、Perl、ActionScript、JavaScriptなどがあります。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

解決済

1回答

316閲覧

messenger botにて、entry.messaging がundefinedになってしまう

bes-how

総合スコア10

Facebook Graph API

Facebook Graph APIとは Facebookのグラフデータベース用のAPIであり、対応言語はPHP、Perl、ActionScript、JavaScriptなどがあります。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

0クリップ

投稿2018/11/07 06:28

編集2018/11/07 06:40

前提・実現したいこと

facebook messanger bot で、ようこそ画面でのスタートボタンを押したときのpostbackで、ボタンを含んだメッセージを送りたいです。

発生している問題・エラーメッセージ

TypeError: Cannot read property 'forEach' of undefined

該当のソースコード

node.js

1'use strict'; 2const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN; 3// Imports dependencies and set up http server 4const 5request = require('request'), 6 express = require('express'), 7 body_parser = require('body-parser'), 8 app = express().use(body_parser.json()); // creates express http server 9 10// Sets server port and logs message on success 11app.listen(process.env.PORT || 1337, () => console.log('webhook is listening')); 12 13// Accepts POST requests at /webhook endpoint 14app.post('/webhook', (req, res) => { 15 16 // Parse the request body from the POST 17 let body = req.body; 18 19 // Check the webhook event is from a Page subscription 20 if (body.object === 'page') { 21 22 body.entry.forEach(function(entry) { 23 24 entry.messaging.forEach(function(event) { // ここでmessagingがundefinedになる 25 // Get the sender PSID 26 let sender_psid = event.sender.id; 27 console.log('Sender ID: ' + sender_psid); 28 29 if (event.postback) { 30 handlePostback(event); 31 } 32 }); 33 34 }); 35 // Return a '200 OK' response to all events 36 res.status(200).send('EVENT_RECEIVED'); 37 38 } else { 39 // Return a '404 Not Found' if event is not from a page subscription 40 res.sendStatus(404); 41 } 42 43}); 44 45 // Accepts GET requests at the /webhook endpoint 46 app.get('/webhook', (req, res) => { 47 48 /** UPDATE YOUR VERIFY TOKEN **/ 49 const VERIFY_TOKEN = "alcyone0225"; 50 51 // Parse params from the webhook verification request 52 let mode = req.query['hub.mode']; 53 let token = req.query['hub.verify_token']; 54 let challenge = req.query['hub.challenge']; 55 56 // Check if a token and mode were sent 57 if (mode && token) { 58 59 // Check the mode and token sent are correct 60 if (mode === 'subscribe' && token === VERIFY_TOKEN) { 61 62 // Respond with 200 OK and challenge token from the request 63 console.log('WEBHOOK_VERIFIED'); 64 res.status(200).send(challenge); 65 66 } else { 67 // Responds with '403 Forbidden' if verify tokens do not match 68 res.sendStatus(403); 69 } 70 } 71 }); 72 73 function callSendAPI(sender_psid, response) { 74 // Construct the message body 75 let request_body = { 76 "recipient": { 77 "id": sender_psid 78 }, 79 "message": response 80 } 81 82 // Send the HTTP request to the Messenger Platform 83 request({ 84 "uri": "https://graph.facebook.com/v3.2/me/messages", 85 "qs": { "access_token": PAGE_ACCESS_TOKEN }, 86 "method": "POST", 87 "json": request_body 88 }, (err, res, body) => { 89 if (!err) { 90 console.log('message sent!') 91 } else { 92 console.error("Unable to send message:" + err); 93 94 } 95 }); 96 } 97 98 function handlePostback(event) { 99 let senderId = event.sender.id; 100 let payload = event.postback.payload; 101 102 if (payload === "Greeting") { 103 let messageData = { 104 "message":{ 105 "attachment":{ 106 "type":"template", 107 "payload": { 108 "template_type":"button", 109 "text":"何の教科がわからないのか教えてください! 一番始めに戻りたいときは はじめ と入力してください!", 110 "buttons":[{ 111 "type":"postback", 112 "title":"英語", 113 "payload":"English" 114 }] 115 } 116 } 117 } 118 } 119 callSendAPI(senderId, messageData); 120 } 121 } 122

試したこと

はじめは公式のドキュメントのようにwebhook_event を定義して、それにentry.messagint[0] を代入していたが、こちらでも

Type error: cannot read property '0' of undefined

のようなエラーが出ていたので、messaging が正しく定義されていない…?
すみません、教えてください…

追記
ボタンテンプレートのところ(handlePostbackのmessageData)を

"text":"任意のテキスト"

に変更したら、しっかり任意のテキストが送信されました。
ですが、依然としてmessagingはundefined のままです。
一体これはどういう現象なんでしょうか…

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

cannot read property の件は解決していませんが、ボタン付きのメッセージを送る方法はわかりました!

function callSendAPI(sender_psid, response) { // Construct the message body let request_body = { "recipient": { "id": sender_psid }, "message": response } // Send the HTTP request to the Messenger Platform request({ "uri": "https://graph.facebook.com/v3.2/me/messages", "qs": { "access_token": PAGE_ACCESS_TOKEN }, "method": "POST", "json": request_body }, (err, res, body) => { if (!err) { console.log('message sent!') } else { console.error("Unable to send message:" + err); } }); }

でもうmessageがあるのに、送るところでもmessageを定義していて

"message": { "message": { ...... } }

のようになっているのが原因でした…
あと少しで挫折するところだった…

投稿2018/11/11 11:54

bes-how

総合スコア10

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問