DEV Community

Cover image for Build an AI-Powered Instagram Sentiment Analyzer with Node.js
Olamide Olaniyan
Olamide Olaniyan

Posted on

Build an AI-Powered Instagram Sentiment Analyzer with Node.js

If you manage a brand account on Instagram, you know the struggle. You post a Reel, it goes viral, and suddenly you have 5,000 comments.

Are people loving it? Hating it? Asking for a refund?

Manually reading 5,000 comments is impossible. But with a little bit of code, we can automate this analysis in minutes.

In this tutorial, we’ll build a Sentiment Analyzer that:

  1. Scrapes comments from any Instagram Post or Reel.
  2. Feeds them into OpenAI (GPT-4o-mini).
  3. Returns a sentiment breakdown (e.g., "80% Positive, 10% Negative").

The Stack

  • Node.js: Runtime.
  • SociaVault API: To scrape the comments (no login required).
  • OpenAI API: To analyze the text.

Step 1: Setup

Initialize a new Node.js project:

mkdir insta-sentiment
cd insta-sentiment
npm init -y
npm install axios openai dotenv
Enter fullscreen mode Exit fullscreen mode

Create your .env file:

SOCIAVAULT_API_KEY=your_sociavault_key
OPENAI_API_KEY=your_openai_key
Enter fullscreen mode Exit fullscreen mode

Step 2: Get the Comments

First, we need a function to fetch comments. We'll use the v1/scrape/instagram/comments endpoint from SociaVault.

Create index.js:

require('dotenv').config();
const axios = require('axios');
const OpenAI = require('openai');

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

async function getComments(postUrl) {
  console.log('πŸ“₯ Fetching comments...');
  try {
    const response = await axios.get('https://api.sociavault.com/v1/scrape/instagram/comments', {
      params: { url: postUrl },
      headers: { 'Authorization': `Bearer ${process.env.SOCIAVAULT_API_KEY}` }
    });

    // The API returns a list of comment objects
    const comments = response.data.data.items || [];

    // We only need the text
    return comments.map(c => c.text);
  } catch (error) {
    console.error('Error fetching comments:', error.message);
    return [];
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Analyze with AI

Now, let's write a function that sends these comments to OpenAI. We'll use gpt-4o-mini because it's cheap and fast enough for this task.

async function analyzeSentiment(comments) {
  console.log(`πŸ€– Analyzing ${comments.length} comments with AI...`);

  // We'll batch them to save tokens and context window
  // For this demo, let's just take the first 50 comments
  const sample = comments.slice(0, 50);

  const prompt = `
    Analyze the sentiment of the following Instagram comments.
    Return a JSON object with the percentage of Positive, Negative, and Neutral sentiment.
    Also provide a 1-sentence summary of the general vibe.

    Comments:
    ${JSON.stringify(sample)}
  `;

  const completion = await openai.chat.completions.create({
    messages: [{ role: "user", content: prompt }],
    model: "gpt-4o-mini",
    response_format: { type: "json_object" },
  });

  return JSON.parse(completion.choices[0].message.content);
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Putting It Together

Now, let's combine them into a main function.

async function main() {
  // A viral reel URL (example)
  const postUrl = 'https://www.instagram.com/reel/C3xyz...'; 

  // 1. Get Comments
  const comments = await getComments(postUrl);

  if (comments.length === 0) {
    console.log('No comments found.');
    return;
  }

  console.log(`βœ… Found ${comments.length} comments.`);

  // 2. Analyze
  const result = await analyzeSentiment(comments);

  // 3. Output Results
  console.log('\nπŸ“Š Sentiment Analysis Report:');
  console.log('-----------------------------');
  console.log(`Positive: ${result.Positive || result.positive}%`);
  console.log(`Neutral:  ${result.Neutral || result.neutral}%`);
  console.log(`Negative: ${result.Negative || result.negative}%`);
  console.log('\nπŸ“ Summary:', result.summary || result.vibe);
}

main();
Enter fullscreen mode Exit fullscreen mode

The Result

When you run node index.js, you get instant insights:

πŸ“₯ Fetching comments...
βœ… Found 142 comments.
πŸ€– Analyzing 50 comments with AI...

πŸ“Š Sentiment Analysis Report:
-----------------------------
Positive: 75%
Neutral:  15%
Negative: 10%

πŸ“ Summary: Users are loving the new feature but some are confused about the pricing.
Enter fullscreen mode Exit fullscreen mode

Why This Matters

For a developer, this is a fun weekend project. For a marketing agency, this is a product.

Agencies pay hundreds of dollars a month for tools that do exactly this. With SociaVault and OpenAI, you just built the core engine in 50 lines of code.

You could expand this by:

  • Automating it to run every hour.
  • Sending a Slack alert if "Negative" sentiment spikes above 20%.
  • Building a frontend dashboard to visualize the trends over time.

Next Steps

Top comments (4)

Collapse
Β 
sloan profile image
Sloan the DEV Moderator β€’

We loved your post so we shared it on social.

Keep up the great work!

Collapse
Β 
olams profile image
Olamide Olaniyan β€’

Thank you so much

Some comments may only be visible to logged-in visitors. Sign in to view all comments.