Skip to content
This repository has been archived by the owner on Sep 20, 2024. It is now read-only.

Add Facebook attachment upload api #899

Merged
merged 8 commits into from
Jun 27, 2017
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions docs/readme-facebook.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Table of Contents
* [Simulate typing](#simulate-typing)
* [Silent and No Notifications](#silent-and-no-notifications)
* [Messenger code API](#messenger-code-api)
* [Attachment upload API](#attachment-upload-api)
* [Running Botkit with an Express server](#use-botkit-for-facebook-messenger-with-an-express-web-server)

## Getting Started
Expand Down Expand Up @@ -506,6 +507,38 @@ controller.api.messenger_profile.get_target_audience(function (err, data) {

```

## Attachment upload API

Attachment upload API allows you to upload an attachment that you may later send out to many users, without having to repeatedly upload the same data each time it is sent :


```js
var attachment = {
"type":"image",
"payload":{
"url":"https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png",
"is_reusable": true
}
};

controller.api.attachment_upload.upload(attachment, function (err, attachmentId) {
if(err) {
// Error
} else {
var image = {
"attachment":{
"type":"image",
"payload": {
"attachment_id": attachmentId
}
}
};
bot.reply(message, image);
}
});

```


## Use BotKit for Facebook Messenger with an Express web server
Instead of the web server generated with setupWebserver(), it is possible to use a different web server to receive webhooks, as well as serving web pages.
Expand Down
148 changes: 30 additions & 118 deletions examples/facebook_bot.js
Original file line number Diff line number Diff line change
@@ -1,137 +1,23 @@
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
______ ______ ______ __ __ __ ______
/\ == \ /\ __ \ /\__ _\ /\ \/ / /\ \ /\__ _\
\ \ __< \ \ \/\ \ \/_/\ \/ \ \ _"-. \ \ \ \/_/\ \/
\ \_____\ \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_\
\/_____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_/


This is a sample Facebook bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Facebook's Messenger APIs
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
for a user.

# RUN THE BOT:

Follow the instructions here to set up your Facebook app and page:

-> https://developers.facebook.com/docs/messenger-platform/implementation

Run your bot from the command line:

app_secret=<MY APP SECRET> page_token=<MY PAGE TOKEN> verify_token=<MY_VERIFY_TOKEN> node facebook_bot.js [--lt [--ltsubdomain LOCALTUNNEL_SUBDOMAIN]]

Use the --lt option to make your bot available on the web through localtunnel.me.

# USE THE BOT:

Find your bot inside Facebook to send it a direct message.

Say: "Hello"

The bot will reply "Hello!"

Say: "who are you?"

The bot will tell you its name, where it running, and for how long.

Say: "Call me <nickname>"

Tell the bot your nickname. Now you are friends.

Say: "who am I?"

The bot will tell you your nickname, if it knows one for you.

Say: "shutdown"

The bot will ask if you are sure, and then shut itself down.

Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

Botkit has many features for building cool and useful bots!

Read all about it here:

-> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}

if (!process.env.verify_token) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}

if (!process.env.app_secret) {
console.log('Error: Specify app_secret in environment');
process.exit(1);
}

var Botkit = require('../lib/Botkit.js');
var os = require('os');
var commandLineArgs = require('command-line-args');
var localtunnel = require('localtunnel');

const ops = commandLineArgs([
{name: 'lt', alias: 'l', args: 1, description: 'Use localtunnel.me to make your bot available on the web.',
type: Boolean, defaultValue: false},
{name: 'ltsubdomain', alias: 's', args: 1,
description: 'Custom subdomain for the localtunnel.me URL. This option can only be used together with --lt.',
type: String, defaultValue: null},
]);

if(ops.lt === false && ops.ltsubdomain !== null) {
console.log("error: --ltsubdomain can only be used together with --lt.");
process.exit();
}

var controller = Botkit.facebookbot({
debug: true,
log: true,
access_token: process.env.page_token,
verify_token: process.env.verify_token,
app_secret: process.env.app_secret,
access_token: 'EAAShWXeInZCcBAGD9z7ffW3Dmflwh2X8otTTH1R1OzBniNe6vQPyGduijVwk68Of3r1nZAVte76LdQ00P2qSCQip5hbnqxpaGZAFEibAiDZCHHd3JE0caYzD3cHP7U3rEnSSghMcTITCesrgsWWDhT6SyF7dl5HwJINvht0HFwZDZD',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hey @ouadie-lahdioui can you take out these actual keys?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something is wrong with examples/facebook_bot.js, i will clean it

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

verify_token: 'pass;1234',
app_secret: '197fc98968cd0197cd8c838e9b68e466',
validate_requests: true, // Refuse any requests that don't come from FB on your receive webhook, must provide FB_APP_SECRET in environment variables
});

var bot = controller.spawn({
});

controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
controller.setupWebserver(1337, function(err, webserver) {
controller.createWebhookEndpoints(webserver, bot, function() {
console.log('ONLINE!');
if(ops.lt) {
var tunnel = localtunnel(process.env.port || 3000, {subdomain: ops.ltsubdomain}, function(err, tunnel) {
if (err) {
console.log(err);
process.exit();
}
console.log("Your bot is available on the web at the following URL: " + tunnel.url + '/facebook/receive');
});

tunnel.on('close', function() {
console.log("Your bot is no longer available on the web at the localtunnnel.me URL.");
process.exit();
});
}
});
});


controller.api.messenger_profile.greeting('Hello! I\'m a Botkit bot!');
controller.api.messenger_profile.get_started('sample_get_started_payload');
controller.api.messenger_profile.menu([{
Expand Down Expand Up @@ -201,6 +87,32 @@ controller.hears(['code'], 'message_received,facebook_postback', function(bot, m
});
});

controller.hears(['attachment_upload'], 'message_received', function(bot, message) {
var attachment = {
"type":"image",
"payload":{
"url":"https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png",
"is_reusable": true
}
};

controller.api.attachment_upload.upload(attachment, function (err, attachmentId) {
if(err) {
// Error
} else {
var image = {
"attachment":{
"type":"image",
"payload": {
"attachment_id": attachmentId
}
}
};
bot.reply(message, image);
}
});
});

controller.hears(['quick'], 'message_received', function(bot, message) {

bot.reply(message, {
Expand Down
43 changes: 42 additions & 1 deletion lib/Facebook.js
Original file line number Diff line number Diff line change
Expand Up @@ -610,9 +610,50 @@ function Facebookbot(configuration) {
}
};

var attachment_upload_api = {
upload: function(attachment, cb) {
var message = {
message : {
attachment: attachment
}
};

request.post('https://' + api_host + '/v2.6/me/message_attachments?access_token=' + configuration.access_token,
{ form: message },
function(err, res, body) {
if (err) {
facebook_botkit.log('Could not upload attachment');
cb(err);
} else {

var results = null;
try {
results = JSON.parse(body);
} catch (err) {
facebook_botkit.log('ERROR in attachment upload API call: Could not parse JSON', err, body);
cb(err);
}

if (results) {
if (results.error) {
facebook_botkit.log('ERROR in attachment upload API call: ', results.error.message);
cb(results.error);
} else {
var attachment_id = results.attachment_id;
facebook_botkit.log('Successfully got attachment id ', attachment_id);
cb(null, attachment_id);
}
}
}
});
}

};

facebook_botkit.api = {
'messenger_profile': messenger_profile_api,
'thread_settings': messenger_profile_api
'thread_settings': messenger_profile_api,
'attachment_upload': attachment_upload_api
};

// Verifies the SHA1 signature of the raw request payload before bodyParser parses it
Expand Down
24 changes: 24 additions & 0 deletions npm-debug.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose stack Error: missing script: start
4 verbose stack at run (/usr/local/lib/node_modules/npm/lib/run-script.js:151:19)
4 verbose stack at /usr/local/lib/node_modules/npm/lib/run-script.js:61:5
4 verbose stack at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:356:5
4 verbose stack at checkBinReferences_ (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:320:45)
4 verbose stack at final (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:354:3)
4 verbose stack at then (/usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:124:5)
4 verbose stack at /usr/local/lib/node_modules/npm/node_modules/read-package-json/read-json.js:311:12
4 verbose stack at /usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:78:16
4 verbose stack at tryToString (fs.js:455:3)
4 verbose stack at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:442:12)
5 verbose cwd /Users/SOAT-OLA/works/projects/botkit
6 error Darwin 16.5.0
7 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
8 error node v6.9.1
9 error npm v3.10.8
10 error missing script: start
11 error If you need help, you may report this error at:
11 error <https://github.com/npm/npm/issues>
12 verbose exit [ 1, true ]