Created
October 4, 2017 04:57
-
-
Save mikkipastel/37fa011e3aea7ebb9941fb3dab6f1186 to your computer and use it in GitHub Desktop.
facebook chatbot from cloud function in firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Reference from https://medium.com/@Astider/how-to-สร้าง-messenger-chatbot-แบบ-serverless-ด้วย-google-firebase-908c3eaba67e | |
const functions = require('firebase-functions'); | |
// The Firebase Admin SDK to access the Firebase Realtime Database. | |
const admin = require('firebase-admin'); | |
admin.initializeApp(functions.config().firebase); | |
// Create and Deploy Your First Cloud Functions | |
// https://firebase.google.com/docs/functions/write-firebase-functions | |
const VERIFIED_TOKEN = "YOUR_VERIFIED_TOKEN" | |
exports.bearService = functions.https.onRequest((request, response) => { | |
if(request.method == "GET") { | |
if (request.query['hub.mode'] === 'subscribe' && | |
request.query['hub.verify_token'] === "VERIFIED_TOKEN_BEAR") { | |
console.log("Validating webhook"); | |
response.status(200).send(request.query['hub.challenge']); | |
} | |
else { | |
console.error("Failed validation. Make sure the validation tokens match."); | |
response.sendStatus(403); | |
} | |
} else if(request.method == "POST") { | |
var data = request.body; | |
if (data.object === 'page') { | |
data.entry.forEach(entry => { | |
var pageID = entry.id; | |
var timeOfEvent = entry.time; | |
console.log('entry : ${JSON.stringify(entry)}') | |
entry.messaging.forEach(event => { | |
if (event.message) { | |
receivedMessage(event) | |
} else { | |
console.log("Webhook received unknown event: ", event) | |
} | |
}) | |
}) | |
response.sendStatus(200) | |
} | |
} | |
}); | |
function receivedMessage(event) { | |
let senderID = event.sender.id | |
let recipientID = event.recipient.id | |
let timeOfMessage = event.timestamp | |
let message = event.message | |
//ถ้าข้อความมาแล้ว log ตรงนี้จะเห็นข้อความเลยครับ | |
console.log("Received message for user %d and page %d at %d with message:", | |
senderID, recipientID, timeOfMessage) | |
console.log(JSON.stringify(message)) | |
let messageId = message.mid | |
let messageText = message.text | |
let messageAttachments = message.attachments | |
if (messageText) { | |
//ส่วนนี้ใช้ Switch case มาทำ rule-base คือดักคำมาทำงานแตกต่างกันไป | |
//เรียกได้ว่าเป็นวิธีที่ basic และง่ายสุดในการทำบอทก็ว่าได้ 555 | |
if (messageText.toLowerCase()) { | |
if (messageText.search('hello') >= 0) { | |
greeting(senderID) | |
} else { | |
sendTextMessage(senderID, messageText) | |
} | |
} | |
} else if (messageAttachments) { | |
sendTextMessage(senderID, "Message with attachment received"); | |
} | |
} | |
function greeting(recipientId) { | |
let messageData = { | |
recipient: { | |
id: recipientId | |
}, | |
message: { | |
text: "Hello" | |
} | |
} | |
callSendAPI(messageData) | |
} | |
function sendTextMessage(recipientId, messageText) { | |
//จัดข้อความที่จะส่งกลับในรูปแบบ object ตามที่ Messenger กำหนด | |
let messageData = { | |
recipient: { | |
id: recipientId | |
}, | |
message: { | |
text: messageText//, | |
//metadata: "DEVELOPER_DEFINED_METADATA" | |
} | |
} | |
callSendAPI(messageData) | |
} | |
const axios = require('axios') | |
function callSendAPI(messageData) { | |
console.log('message data : ${JSON.stringify(messageData)}'); | |
axios({ | |
method: 'POST', | |
url: 'https://graph.facebook.com/v2.6/me/messages', | |
params: { | |
'access_token': '<YOUR_FACEBOOK_PAGETOKEN>' | |
}, | |
data: messageData | |
}) | |
.then(response => { | |
if (response.status == 200) { | |
let body = response.data | |
let recipientId = body.recipient_id; | |
let messageId = body.message_id; | |
if (messageId) { | |
console.log("Successfully sent message with id %s to recipient %s", | |
messageId, recipientId); | |
} else { | |
console.log("Successfully called Send API for recipient %s", | |
recipientId); | |
} | |
} | |
else { | |
console.error("Failed calling Send API", response.status, | |
response.statusText, response.data.error); | |
} | |
}) | |
.catch(error => { | |
console.log('error : ${error}') | |
console.log('axios send message failed'); | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "functions", | |
"description": "Cloud Functions for Firebase", | |
"dependencies": { | |
"firebase-admin": "~5.2.1", | |
"firebase-functions": "^0.6.2", | |
"axios": "0.16.2" | |
}, | |
"private": true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mikkipastel and @ispiropoulos thanks for the code.
@ispiropoulos using your code, the variables not having same value.
request sh1 diggest sha1=2e3090b8af056d92c203073c1134de22d158f1c4
request hub signature sha1=1de52ebb68dc5c84962415acf39dc15da3a05773
You can help me to solve that?!
Thanks