A Node.js application for scheduling and automating social media posts to Facebook and Instagram using Meta's Graph API.
- π Smart Scheduling: Schedule posts using cron expressions or specific dates with timezone support
- π€ AI-Powered Captions: Automatic caption generation using OpenAI for alumni photos and events
- π― Intelligent Schedule Generation: AI-driven natural posting schedules from image directories
- πΌοΈ Content Processing: Automatic content optimization for Facebook and Instagram
- π± Meta Integration: Direct posting to Facebook Pages and Instagram via Graph API
- π Comprehensive Logging: Detailed logging with daily rotation and multiple log streams
- β Validation: Content, image, and schedule validation before posting
- π Timezone Aware: Global timezone support with optimal posting time suggestions
- π Retry Logic: Intelligent retry mechanisms for failed posts
- π Health Monitoring: Built-in health checks and metrics endpoints
- π Schedule Management: JSON-based schedule configuration with templates
social-scheduler/
βββ package.json # Dependencies and npm scripts
βββ .env # Environment variables (template)
βββ .gitignore # Git ignore rules
βββ README.md # Project documentation
βββ src/
β βββ app.js # Main application entry point
β βββ config/
β β βββ meta-api.js # Meta API endpoints, limits, and error codes
β β βββ scheduler.js # Scheduler settings and cron patterns
β βββ services/
β β βββ caption-generator.js # OpenAI-powered caption generation
β β βββ content-processor.js # Content optimization and validation
β β βββ file-reader.js # File and schedule configuration reading
β β βββ meta-client.js # Facebook & Instagram API client
β β βββ schedule-generator.js # AI-driven schedule generation
β βββ utils/
β βββ batch-caption.js # Batch caption generation utility
β βββ generate-schedule.js # Schedule generation CLI tool
β βββ logger.js # Winston logging with daily rotation
β βββ validators.js # Comprehensive validation utilities
βββ content/
β βββ posts/ # Text content files (.txt, .md, .json)
β βββ images/ # Image files for posting
β β βββ processed/ # Platform-optimized images (auto-generated)
β βββ captions/ # AI-generated captions with metadata
β βββ schedule.json # Main schedule configuration
βββ logs/ # Application logs (auto-created)
-
Clone the repository
git clone <repository-url> cd social-scheduler
-
Install dependencies
npm install
-
Configure environment variables
cp .env .env.local # Edit .env.local with your Meta API credentials -
Set up Meta API credentials
- Create a Facebook App at developers.facebook.com
- Get Page access token for Facebook posting
- Get Instagram Business account access token
- Add credentials to your
.envfile
# Meta API Credentials
FACEBOOK_ACCESS_TOKEN=your_page_access_token
FACEBOOK_PAGE_ID=your_facebook_page_id
INSTAGRAM_ACCESS_TOKEN=your_instagram_access_token
# OpenAI Integration (for AI features)
OPENAI_API_KEY=your_openai_api_key
# Application Settings
NODE_ENV=development
PORT=3000
LOG_LEVEL=info
TIMEZONE=Europe/NicosiaCreate or modify content/schedule.json:
{
"settings": {
"timezone": "Europe/Nicosia",
"retryAttempts": 3,
"enableNotifications": true
},
"posts": [
{
"id": "morning_post",
"content": "Good morning! π
",
"platforms": ["facebook", "instagram"],
"scheduledTime": "2024-12-15T09:00:00",
"images": ["content/images/morning.jpg"],
"priority": "high"
},
{
"id": "alumni_auto_caption",
"generateCaption": true,
"metadata": {
"year": "1985",
"event": "class photograph",
"location": "main hall"
},
"platforms": ["facebook", "instagram"],
"scheduledTime": "2024-12-16T14:30:00",
"images": ["content/images/class_1985.jpg"]
}
]
}# Production mode
npm start
# Development mode (with debug logging)
npm run dev
# Direct execution
node src/app.jsThe application provides several HTTP endpoints:
http://localhost:3000/health- Basic health statushttp://localhost:3000/status- Detailed application statehttp://localhost:3000/metrics- Performance metrics
# Interactive caption generation
npm run batch-caption
# Generate captions for all images in schedule
npm run batch-caption:schedule
# Generate with configuration file
npm run batch-caption:config# Interactive schedule generation
npm run generate-schedule
# Automated generation with defaults
npm run generate-schedule:auto
# Preview what would be generated
npm run generate-schedule:dry-run- Text Content: Place
.txtor.mdfiles incontent/posts/ - Images: Place image files in
content/images/ - AI Captions: Generated captions saved in
content/captions/with metadata - Scheduling: Configure posts in
content/schedule.json - AI Generation: Use npm scripts for automated caption and schedule creation
content/posts/sample_post.txt
π Exciting news! We're launching our new feature today.
β¨ What's new:
β’ Advanced scheduling
β’ Better analytics
β’ Improved UI
#ProductLaunch #Innovation
- Facebook Graph API v18.0 integration
- Instagram Basic Display API support
- Rate limiting and error handling
- Image upload and post publishing
- OpenAI GPT-4o-mini integration for alumni-focused captions
- Contextual metadata processing for school events (year, event, location)
- Batch processing with cost estimation and rate limiting
- Alumni association writing style with engagement prompts
- Automatic caption saving with generation metadata
- AI-powered natural posting schedule creation
- Intelligent time distribution (10am-8pm constraint)
- Metadata extraction from image filenames
- Cost estimation and validation safeguards
- Platform-specific content optimization
- Auto-caption integration
- Image processing and validation
- Hashtag and mention handling
- Text length and format validation
- Reads text content from files
- Validates image files
- Parses schedule.json configuration
- Provides structured data for processing
- Multiple log streams (API, scheduler, performance)
- Daily log rotation with 14-day retention
- Structured logging with metadata
- Console and file output
- Schedule configuration validation
- Content and image validation
- DateTime and timezone validation
- Meta API response validation
- AI generation option validation
- Text: Up to 63,206 characters
- Images: JPEG, PNG, GIF, WebP (max 100MB)
- Hashtags: Up to 30 recommended
- Rate Limits: 200 requests/hour
- Text: Up to 2,200 characters
- Images: JPEG, PNG (max 30MB, requires at least one image)
- Hashtags: Up to 30 recommended
- Aspect Ratios: 0.8 - 1.91 (4:5 to 16:9)
- Rate Limits: 200 requests/hour
The application uses Winston with daily rotation:
logs/combined-YYYY-MM-DD.log- All log levelslogs/error-YYYY-MM-DD.log- Error-only logslogs/api-YYYY-MM-DD.log- API operation logslogs/scheduler-YYYY-MM-DD.log- Job execution logslogs/performance-YYYY-MM-DD.log- Performance metrics
Log files are compressed after rotation and kept for 14 days.
- New Platforms: Extend
meta-client.jswith new API integrations - Content Types: Add processors to
content-processor.js - AI Features: Enhance
caption-generator.jsorschedule-generator.js - Validators: Add validation rules to
validators.js - Scheduling: Modify cron patterns in
config/scheduler.js
src/config/meta-api.js: API endpoints, limits, error codessrc/config/scheduler.js: Cron patterns, retry policies, queue settings
# Check application health
curl http://localhost:3000/health
# View detailed status
curl http://localhost:3000/status
# Monitor metrics
curl http://localhost:3000/metrics- Set
NODE_ENV=production - Configure proper timezone
- Set up log rotation monitoring
- Configure process manager (PM2, systemd, etc.)
- Set up health check monitoring
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]- API Authentication: Ensure tokens have proper permissions
- Rate Limits: Monitor
/metricsendpoint for usage - Image Formats: Check platform-specific requirements
- Timezone Issues: Validate timezone strings in configuration
- Schedule Validation: Check
schedule.jsonformat
The application maps Meta API error codes to actionable messages:
- 190: Invalid access token - refresh credentials
- 613: Rate limit exceeded - wait and retry
- 368: Content rejected - review content guidelines
- API credentials stored in environment variables
- No sensitive data in logs
- Rate limiting to prevent API abuse
- Input validation and sanitization
- Error handling without data exposure
ISC
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes following the coding standards
- Add tests if applicable
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
For issues and questions:
- Check the troubleshooting section
- Review application logs in
logs/directory - Check health endpoints for system status
- Open an issue with detailed error information