Automate Facebook Page Posting Using Serverless, OpenAI & DynamoDB

Ever wondered how to keep your Facebook page active with fresh AI-generated content — without lifting a finger? This tutorial will walk you through setting up a serverless system to automatically generate images using OpenAI’s DALL·E and post them to a Facebook Page, all triggered daily based on entries in a DynamoDB table.

What You’ll Build

A Node.js-based AWS Lambda function that:

  1. Scans DynamoDB for today’s scheduled content,
  2. Generates an image using OpenAI’s DALL·E API,
  3. Uploads the image to your Facebook Page using the Facebook Graph API.

Let’s get to work.

Prerequisites

AWS Account with:

  • DynamoDB table (e.g., autopost)
  • IAM role with Lambda + DynamoDB permissions

Facebook Developer Account

  • Facebook Page & App set up
  • pages_read_engagement, pages_manage_posts permissions

OpenAI API Key with DALL·E access

Node.js + AWS SDK

Serverless Framework (optional but ideal)

DynamoDB Table Setup

Create a DynamoDB table named autopost with at least these fields:

FieldTypeDescription
postdateStringDate string in MM/DD/YYYY format
posttypeString'quote' or other types (e.g. 'image')
postStringPrompt for image generation

Facebook Page Access Token

To post to a page, you need a Page Access Token. Here’s how:

  • Go to Facebook Graph API Explorer
  • Select your app, generate a User Token with the pages_manage_posts permission
  • Use that token to retrieve a long-lived Page Access Token:

Note: The token you get for your page is "permanent" until manually revoked.

Generate Image with OpenAI

Install OpenAI SDK:

npm install openai

Generate an image like this:

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const image = await openai.images.generate({
  model: 'dall-e-3',
  prompt: 'A futuristic city skyline at sunset',
  n: 1,
  size: '1024x1024',
});
const imageUrl = image.data[0].url;

Post Image to Facebook Page

Use the Facebook Graph API to post:

const endpoint = `https://graph.facebook.com/v22.0/${PAGE_ID}/photos`;
const params = {
  url: imageUrl,
  access_token: pageAccessToken,
};

await axios.post(endpoint, null, { params });

Full Serverless Function (Node.js)

Here’s the complete code broken down:

main.js

const axios = require('axios');
const { OpenAI } = require("openai");
const moment = require('moment'); 
const AWS = require('aws-sdk');
const mydocumentClient = new AWS.DynamoDB.DocumentClient();

const PAGE_ID = process.env.PAGE_ID;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

const openai = new OpenAI({ apiKey: OPENAI_API_KEY });

async function getUserId(userAccessToken) {
  const response = await axios.get(`https://graph.facebook.com/v22.0/me?access_token=${userAccessToken}`);
  return response.data.id;
}

async function getPermanentPageToken() {
  const userId = await getUserId(ACCESS_TOKEN);
  const pageToken = await axios.get(`https://graph.facebook.com/v22.0/${userId}/accounts?access_token=${ACCESS_TOKEN}`);
  return pageToken.data.data[0].access_token;
}

async function generateImageWithOpenAI(prompt) {
  const image = await openai.images.generate({ model: 'dall-e-3', prompt, n: 1, size: "1024x1024" });
  return image.data[0].url;
}

async function postImageToPage(imageUrl, message) {
  const token = await getPermanentPageToken();
  const endpoint = `https://graph.facebook.com/v22.0/${PAGE_ID}/photos`;
  await axios.post(endpoint, null, {
    params: {
      url: imageUrl,
      access_token: token,
      caption: message,
    }
  });
}

async function main(prompt) {
  const imageUrl = await generateImageWithOpenAI(prompt);
  await postImageToPage(imageUrl, `Image Generated Using OpenAI`);
}

module.exports.run = async (event, context) => {
  const time = new Date();
  const params = {
    TableName : 'autopost',
    FilterExpression: 'postdate = :pdate',
    ExpressionAttributeValues: { ":pdate": moment(time).format('MM/DD/YYYY') },
  };
  const data = await mydocumentClient.scan(params).promise();

  if (data.Items[0]?.posttype === 'quote') {
    await main(data.Items[0].post);
  }

  console.log(`Function "${context.functionName}" executed at ${time}`);
};

Deploy with Serverless Framework

serverless.yml

service: autopost-facebook

provider:
  name: aws
  runtime: nodejs18.x
  environment:
    PAGE_ID: YOUR_PAGE_ID
    ACCESS_TOKEN: YOUR_USER_ACCESS_TOKEN
    OPENAI_API_KEY: YOUR_OPENAI_API_KEY
  region: ap-south-1

functions:
  autopost:
    handler: main.run
    events:
      - schedule: cron(0 5 * * ? *)  # 5 AM UTC daily

Results

You now have a fully automated social media poster that:

  • Reads a scheduled post from DynamoDB
  • Uses OpenAI to generate relevant imagery
  • Uploads the result to your Facebook Page

Perfect for businesses, content creators, or community pages that want a low-maintenance, high-impact presence!

Final Thoughts

This project is a glimpse into how serverless architecture + generative AI can automate content generation and delivery. You could easily extend it to:

  • Post to Twitter, Instagram, or LinkedIn
  • Generate text captions using GPT
  • Add approval workflows or audit trails