Misaliperver: Facebook Messenger Uygulaması


1- Facebook hesabınızla send messages adresine girerek sağ üstteki Get Started butonuna tıklıyoruz.

2- İlgili sayfa için bir uygulama oluşturuyoruz.

3- Burada 2 adet modül oldukça kritik öneme sahip; access_token ve webhook.
Webhook ile mesajlar uygulamanıza iletilecek, dizayn ettiğiniz kurguya göre yanıt vereceksiniz. Yanıt verirkende ürettiğiniz access_token'i kullanacaksınız.

Webhook tanımlanırken, sunucunuzdan facebook tarafına yapılacak request'lerin bot tarafından mı, yoksa bir insan tarafından mı yollanacağını soruyor. Ben live chat yapmayı düşündüğüm için 2. seçeneği işaretliyorum. Bot yazmayı düşünüyorsanız 1. seçeneği işaretleyip, kurgunuza ona göre devam edebilirsiniz.

4- İlk mesajımızı almak için webhook'umuzu Facebook'a kanıtlayalım.
Bu işlemi yapıyoruz çünkü facebook mesajları göndereceği adresin çalışır olduğundan emin olmak istiyor;

Bunun için url tanımlamanızı ve ona uydurma bir token adresi göndermenizi istiyor.

Ben denemelerimi; server side olarak nodejs ve sunucu olarak local'den sunacağım için ngrok ikilisini kullanacağım.  ngrok indirmek için tıklayınız
--> ./ngrok http 1337
bana verdiği tünel adresi;
--> https://62e069e7.ngrok.io

Aşağıdaki kod direk facebook sayfasından alınmıştır, anlatımda app.post kullanmanızı istiyor lakin ben hata mesajı aldım siz yinede app.use kullanın. Aslında direk gelen istekte geriye req.query['hub.challenge'] döndürebilirsiniz, ama döküman'dakine itaat ederek haret ediyorum :)

'use strict';

// Imports dependencies and set up http server
const
path = require('path'),
fetch = require('node-fetch'),
express = require('express'),
bodyParser = require('body-parser'),
app = express().use(bodyParser.json()), // creates express http server
URL_Facebook = "https://graph.facebook.com/v3.2/me/messages?access_token=",
PAGE_ACCESS_TOKEN = "APP_TOKEN_GIRINIZ";
app.use('/webhook', (req, res) => {

console.log('hi')

// Your verify token. Should be a random string.
let VERIFY_TOKEN = "UYDURMA_BİR_TOKEN_DEĞERİ"
// Parse the query params
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
// Checks if a token and mode is in the query string of the request
if (mode && token) {

// Checks the mode and token sent is correct
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
// Responds with the challenge token from the request
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}

});

// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));


Daha sonra sizde de aşağıdaki gibi gözükecek. Burada sayfa seçerek istediğiniz uygulamanıza geliştirdiğiniz eklentiyi bağlayabilirsiniz.


Benim verdiğim gibi Edit Events'ten messages, messaging_postbacks, message_reads özelliklerini bu uygulama için ekleyebilirsiniz. ( bold olarak yazdığım property'ler zaruri kullanılması gerekiyor.)

! Bu uygulama şuan develop mode'da olduğu için; sadece sizin hesabınız üzerinden gönderilen mesajlar Webhook adımı ile gönderilir. Ta ki, canlıya alana kadar..

Şimdi kodumuzun içeriğini değiştirelim, facebook tarafından gönderilen mesajları almak için /webhook request'i için tanımladığımız fonksiyonumuzu aşağıdaki gibi güncellediğimizde, gelen her mesajı tek tek yakalayabileceğiz.

app.post('/webhook', (req, res) => {
console.log('hi')
// Parse the request body from the POST
let body = req.body;

// Check the webhook event is from a Page subscription
if (body.object === 'page') {

// Iterate over each entry - there may be multiple if batched
body.entry.forEach(function(entry) {

// Get the webhook event. entry.messaging is an array, but
// will only ever contain one event, so we get index 0
let webhook_event = entry.messaging[0];
console.log(webhook_event);
io.emit('facebook-to-message', webhook_event);

});

// Return a '200 OK' response to all events
res.status(200).send('EVENT_RECEIVED');

} else {
// Return a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});

Ve yeni bir kod ekleyelim, bu kod sayesinde facebook'a bol bol mesaj atabileceğiz.


app.post('/response', async (req, res) => {
console.log('re hi')
let body = req.body;
console.log(body)
if(body.senderId && body.message){
// Parse the request body from the POST
let post_url = URL_Facebook + PAGE_ACCESS_TOKEN;
let post_header = {
"Content-Type": "application/json"
}
body = {
"messaging_type": "RESPONSE",
"recipient":{
"id": body.senderId
},
"message":{
"text": body.message
}
}
body = JSON.stringify(body);
var sentiments = await fetch(post_url, { method: "POST", headers: post_header, body: body });
console.log(sentiments)
res.status(200).json({
"success" : true,
"message" : sentiments
});

}else{
res.status(200).json({
"success" : false,
"message" : "Message format is not defined!"
});
}
});


Bu aşama için tüm kodlara github linkinden ulaşabilirsiniz.

Kodu çalıştırdığımızda facebook'tan safyamıza bir mesaj atalım, ve nodejs console'una gelen istekleri görüntüleyelim.


Burada ben kişisel hesabımdan Yazılım Entegrasyon isimli kişisel hesabıma bağlı Facebook sayfasına mesaj attım.

! Bu senaryoda; sender['id'] benim (mesela müşteri) , recipient['id'] dediği facebook sayfası (mesela şirket)
Bu bilgi uygulamayı geliştirdikçe daha önemli hale gelecek.


Şimdi buna karşılık bir cevap vermek lazım değil mi; POSTMAN uygulamasını çalıştırın ve bir post isteği yollayın.


yada curl ile terminalden istekte bulunun (url'i değiştirmeyi unutmayınız)


curl -X POST \
https://62e069e7.ngrok.io/response/ \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 093f5466-3a93-486f-b083-29f8b09f3193' \
-H 'cache-control: no-cache' \
-d '{
  "senderId" : "2194616027318530",
"message" : "Nasılsınız"
}'


Bu bölümde facebook messenger ile iletişimi basitçe anlatmaya çalıştım, Türkçe kaynak oluşturması açısından şöylece kenera bırakıyorum.

Merakı olan sebeplensin, ihtiyacı olan nasiplensin. :)



Yorumlar