How to send PDF file object from Facebook messaging API

309 Views Asked by At

I have developed a facebook messenger app in Node.js.

I am using PDFKit to generate a PDF and send it to the user from the messenger bot. The problem I am facing is I am not able to send the generated file object.

generatePDF.js

require('dotenv').config("./env");
const getStream = require('get-stream')
const PDFDocument = require('pdfkit');
const fs = require('fs');


async function createPDF(name) {

    const doc = new PDFDocument({
        layout: 'landscape',
        size: 'A4',
    });
    doc.rect(0, 0, doc.page.width, doc.page.height).fill('#fff');
    ``
    doc.fontSize(10);

    doc.image('src/airtable/assets/corners.png', -1, 0, { scale: 0.585 }, { fit: [doc.page.width, doc.page.height], align: 'center' })
    
 doc
        .font('src/airtable/fonts/Pinyon Script 400.ttf')
        .fontSize(65)
        .fill('#125951')
        .text(`${name}`, 240, 240, {
            // width: 500,
            // align: 'center'
        });

    doc.end();
    return await getStream.buffer(doc)

}


module.exports = { createPDF}

Invoking the above function after receiving specific postback

main.js

const pdf= require('./generatePDF')

name = "John"
const generated_pdf = await pdf.createPDF(name)

sendMedia(sender_psid, generated_pdf )


async function sendMedia(sender_psid, file) {
    try {
         let response = {
            "attachment": {
                "type": "file",
                "payload": file

            }
        }
        }

        callSendAPI(sender_psid, response);

    }
    catch (e) {
        console.log("Error cert ", e)
    }
}

function callSendAPI(sender_psid, response) {
    // Construct the message body
    let request_body = {
        "recipient": {
            "id": sender_psid
        },
        "message": response
    };
    // Send the HTTP request to the Messenger Platform
    request({
        "uri": "https://graph.facebook.com/v7.0/me/messages",
        "qs": { "access_token": process.env.FB_PAGE_TOKEN },
        "method": "POST",
        "json": request_body
    }, (err, res, body) => {
        if (!err) {
            console.log('message sent!!!');
        } else {
            console.error("Unable to send message:" + err);
        }
    });
}

How can I send the file object without a URL and without fetching locally? any help or advice is appreciated!

1

There are 1 best solutions below

1
On

There is no such type ("application/pdf"), for sending attachments like a PDF you'd use the file type. Also, as stated in the docs, there is no "filedata" parameter, instead you'd use "payload".

Docs can be found here by the way:

https://developers.facebook.com/docs/messenger-platform/reference/send-api/