const fs = require('fs'); const path = require('path'); // Auto-load .env file if present const envPath = path.resolve(__dirname, '.env'); if (fs.existsSync(envPath)) { const envContent = fs.readFileSync(envPath, 'utf8'); envContent.split('\n').forEach(line => { const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)\s*$/); if (match) { const key = match[1]; let value = match[2].trim().replace(/^['"]|['"]$/g, ''); if (!process.env[key]) process.env[key] = value; } }); } const ACCESS_TOKEN = (process.env.META_ACCESS_TOKEN || '').replace(/\s+/g, ''); const PAGE_ID = (process.env.META_PAGE_ID || '1047354938453381').trim(); if (!ACCESS_TOKEN) { console.error('ERROR: META_ACCESS_TOKEN is missing in .env file or environment variables.'); process.exit(1); } async function publishPost(message, imageUrl = null) { if (!PAGE_ID) { throw new Error('META_PAGE_ID (Page ID) is required to publish a post.'); } const endpoint = imageUrl ? `${PAGE_ID}/photos` : `${PAGE_ID}/feed`; const url = new URL(`https://graph.facebook.com/v19.0/${endpoint}`); url.searchParams.append('access_token', ACCESS_TOKEN); const payload = imageUrl ? { caption: message, url: imageUrl } : { message }; const res = await fetch(url.toString(), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const data = await res.json(); if (data.error) { throw new Error(`Meta Graph API Error: ${data.error.message}`); } return data; } if (require.main === module) { const pageId = process.argv[2] || PAGE_ID; const msg = process.argv[3] || 'اختبار النشر التلقائي عبر Tripz AI Agent'; if (!pageId) { console.error('Please provide Page ID as first parameter: node scripts/publish-facebook-post.js "[Message]"'); process.exit(1); } publishPost(msg).then(res => console.log('Post published successfully:', res)).catch(err => console.error(err.message)); } module.exports = { publishPost };