Skip to content

Instantly share code, notes, and snippets.

@jt0in3e
Last active December 22, 2023 14:48
Show Gist options
  • Save jt0in3e/4e0d0bac2134f2b252538a39622f4124 to your computer and use it in GitHub Desktop.
Save jt0in3e/4e0d0bac2134f2b252538a39622f4124 to your computer and use it in GitHub Desktop.
Facebook Messenger APIs: Send multiple/bulk messages (batched requests) with Node.js
/*
There are a lot of examples on FB Messenger Dev Docs how to send multiple messages
using curl in command line (terminal).
This code demonstraits how to send these messages using Node.js
*/
"use strict"
const request = require("request");
const fs = require("fs");
//code runs from terminal (node send.js), so variables to be extracted from process.argv
const args = process.argv.slice(2);
const token = args[0];
const id = args[1];
const fbEnd = "https://graph.facebook.com";
//create form (i.e. multipart/form-data)
const r = request.post(fbEnd, (err, httpResponse, body) => {
if (err) {return console.error("batch send error: ", err)};
console.log("batch send successfull: ", body)
});
const form = r.form();
//create batch messages
const rec = "recipient=" + encodeURIComponent(JSON.stringify({"id": id})); //needs to be URLEncoded
const welcomText = "message=" + encodeURIComponent(JSON.stringify( //messages request also needs to be URLEncoded
{"text": "Hi there :) I'm a super bot, yeap\nLook at the picture"
}));
const picture = "message=" + encodeURIComponent(JSON.stringify({ //URLEncoded
"attachment": {"type": "image", "payload": {"attachment_id": "5146444383580061"}} //id of picture that was
//previously sent and got id
//see link below
}));
//name in batched messages is used to make dependance between messages, so they to be sent sequentially
//look at 'depends_on' parametr
const batchMessages = JSON.stringify([ //whole request need to be stringified to attach to form
{"method":"POST", "name": "senderAction", "relative_url":"v2.6/me/messages", "body": rec + "&" + "sender_action=typing_on"}, //to display typing on bubble :)
{"method":"POST", "name": "welcome", "depends_on":"senderAction", "relative_url":"v2.6/me/messages", "body": rec + "&" + welcomText},
{"method":"POST", "name": "picture", "depends_on": "welcome","relative_url":"v2.6/me/messages", "body": rec + "&" + picture}
]);
form.append("access_token", token);
form.append('batch', batchMessages);
/*
link to upload&send image with Node.JS
to Facebook Messenger
https://gist.github.com/yura321y/9af845522b4fea75c092f89c113f207d
*/
@Aram-Eli
Copy link

I have tried the Cucomm but it doesn't look right lots of risks to proceed Now where in 2023 do you have any ways to send bulk messages on messenger without getting flagged as spam or something similar?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment