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:
- Scrapes comments from any Instagram Post or Reel.
- Feeds them into OpenAI (GPT-4o-mini).
- 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
Create your .env file:
SOCIAVAULT_API_KEY=your_sociavault_key
OPENAI_API_KEY=your_openai_key
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 [];
}
}
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);
}
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();
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.
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
- Get your SociaVault API Key.
- Get an OpenAI API Key.
- Start building!
Top comments (4)
We loved your post so we shared it on social.
Keep up the great work!
Thank you so much
You've got the basics down, but if you're actually trying to take this live, here's the real talk: first, you gotta handle SociaVault's rate limits (600 req/min) with exponential backoff - your current code will just crater under any real load, no cap. Then batch those comments up to 1,000+ per OpenAI call instead of running 50 at a time, which straight-up cuts your costs by like 80% Also throw in some basic spam and URL filtering before you even send stuff to the LLM - that alone saves you another 20-30% on tokens since you're not wasting money analyzing garbage comments anyway. If you're trying to actually sell this to agencies, toss a MongoDB database in there and set up Slack alerts when negative sentiment spikes. Suddenly you've got an actual product instead of just a neat demo, and competitors are literally charging $200-500/month for this exact thing. Real quick tho: Instagram's ToS says you gotta delete stored comments after 30 days unless people explicitly opted in, so build in an auto-cleanup job before you launch or you're asking for legal headachesGet all these pieces in place and you're looking at roughly $50-100/month to monitor 1M comments - that's legit profit margins if you can actually nail customer acquisition costs
Great insights. Thank you