Skip to content

Instantly share code, notes, and snippets.

@stripethree
Created November 1, 2016 18:17
Show Gist options
  • Save stripethree/ae6c2f48b63ad4ebd560759eddc9170b to your computer and use it in GitHub Desktop.
Save stripethree/ae6c2f48b63ad4ebd560759eddc9170b to your computer and use it in GitHub Desktop.
/*
Example Facebook Messenger app that pulls the user's public profile and echoes back any messages sent
with the user's first and last name. This one uses BotKit.
So if I sent the bot "Good morning!" it will reply to me with "Echoing message from Jeff Israel: Good morning!"
*/
const reqPromise = require('request-promise');
const graphApiUrl = 'https://graph.facebook.com/v2.6';
if (!process.env.MESSENGER_PAGE_ACCESS_TOKEN) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.MESSENGER_VALIDATION_TOKEN) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}
const Botkit = require('botkit');
const crypto = require("crypto");
const os = require('os');
const controller = Botkit.facebookbot({
debug: false,
access_token: process.env.MESSENGER_PAGE_ACCESS_TOKEN,
verify_token: process.env.MESSENGER_VALIDATION_TOKEN,
});
const bot = controller.spawn({});
controller.setupWebserver(process.env.PORT || 3000, (err, webserver) => {
controller.createWebhookEndpoints(webserver, bot, () => {
console.log('ONLINE!');
});
});
// webserver is an express instance, why not use it!
controller.webserver.get('/', (req, res) => {
res.send('Hello!');
});
// to supress the debug messages
controller.on('tick', (bot, event) => {});
controller.on('message_received', (bot, message) => {
if (message.text.startsWith('Echoing message from ')) {
// hack to ignore our echoed messages
return false;
}
// setup options for call to Graph API for public profile
const options = {
qs: {
access_token: process.env.MESSENGER_PAGE_ACCESS_TOKEN,
fields: 'first_name,last_name,profile_pic,locale,timezone,gender'
},
url: `${graphApiUrl}/${message.user}`
};
// call the Graph API!
reqPromise(options)
.then((jsonString) => {
const jsonObj = JSON.parse(jsonString);
const reply = `Echoing message from ${jsonObj.first_name} ${jsonObj.last_name}: ${message.text}`;
bot.reply(message, reply);
})
.catch((err) => {
// this will throw a 400 when called on echo messages
// it will try to lookup the FB profile for the page, which is not a valid action
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment