Skip to content

Instantly share code, notes, and snippets.

@khaschuluu
Created October 2, 2023 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khaschuluu/70b2672b82bf0a03a760094a9249df04 to your computer and use it in GitHub Desktop.
Save khaschuluu/70b2672b82bf0a03a760094a9249df04 to your computer and use it in GitHub Desktop.
Facebook chat bot sample on Google Cloud Functions
const request = require("request");
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore({keyFilename: './gcpkey.json'});
const callSendAPI = (sender_id, body) => {
let request_body = {
recipient: {
id: sender_id
},
message: body
}
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: 'SECRET_ACCESS_TOKEN' },
method: 'POST',
json: request_body
}, (err, resp, body) => {
if (err) {
console.error('Unable to send message:' + err);
} else {
if (resp.statusCode === 200) {
console.log('message sent!')
} else {
console.error(resp.statusCode, body)
}
}
});
}
// Webhook for facebook messenger
exports.webhook = (req, res) => {
if (req.method === 'GET') {
const VERIFY_TOKEN = 'I don\'t say bleeh bleh bleh';
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
if (mode && token) {
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
}
} else if (req.method === 'POST') {
let body = req.body;
if (body.object === 'page') {
body.entry.forEach((entry) => {
let webhook_event = entry.messaging[0];
if (webhook_event.postback) {
let payload = webhook_event.postback.payload;
if (payload === 'ping') {
const key = datastore.key(['reppergee', '5650385196810240']);
datastore.get(key).then((entity) => {
const balance = (entity && entity[0] && entity[0][webhook_event.sender.id]) || 0;
datastore.save({
key: key,
data: {
[webhook_event.sender.id]: balance + 10
}
}).then(() => {
callSendAPI(webhook_event.sender.id, { text: `Таны дансны үлдэгдэл амжилттай 10 оноогоор нэмэгдэж, нийтдээ ${balance + 10} оноо боллоо.` });
}).catch(console.error);
});
}
}
});
res.status(200).send('EVENT_RECEIVED');
} else {
res.sendStatus(404);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment