138 lines
5.1 KiB
JavaScript
138 lines
5.1 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Autonomous Gemini AI Post Generator & Facebook Publisher for Tripz
|
|
* Analyzes topic / prompt + marketing playbook rules and generates & publishes posts live!
|
|
*/
|
|
|
|
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 META_ACCESS_TOKEN = (process.env.META_ACCESS_TOKEN || '').replace(/\s+/g, '');
|
|
const META_PAGE_ID = (process.env.META_PAGE_ID || '1047354938453381').trim();
|
|
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
|
|
const GEMINI_MODEL = process.env.GEMINI_MODEL || 'gemini-2.0-flash';
|
|
|
|
if (!META_ACCESS_TOKEN) {
|
|
console.error('ERROR: META_ACCESS_TOKEN is missing in .env environment file.');
|
|
process.exit(1);
|
|
}
|
|
|
|
if (!GEMINI_API_KEY) {
|
|
console.error('ERROR: GEMINI_API_KEY is missing in .env environment file.');
|
|
process.exit(1);
|
|
}
|
|
|
|
/**
|
|
* Generate Post Content using Gemini API
|
|
*/
|
|
async function generatePostWithGemini(topic = 'منشور تعريفي عن منصة Tripz ومزايا التملك والشفافية والتوفير') {
|
|
console.log(`Generating AI post content with Gemini (${GEMINI_MODEL}) for topic: "${topic}"...`);
|
|
|
|
const systemInstruction = `أنت مدير تسويق ومحرر إعلاني محترف لمنصة Tripz (منصة SaaS عالمية لإطلاق تطبيقات نقل الركاب وإدارة أساطيل التكسي بعلامة المشغّل التجارية).
|
|
قواعد التسويق الحاكمة (من docs/32):
|
|
1. الملكية: علامتك أنت، وتطبيقك باسمك وشعارك، وبياناتك تبقى لك بعقد تصدير مكتوب.
|
|
2. الشفافية: أسعارنا معلنة بالكامل دون أسرار ولا مفاجآت في الفاتورة.
|
|
3. السرعة: إطلاق خلال 30 يوماً من التوقيع على آبل وجوجل.
|
|
4. الإثبات: محرك مجرّب منذ 2019 يخدم أكثر من 6,000 سائق نشط.
|
|
5. دعوة للإجراء (CTA): رابط حاسبة التوفير (https://tripz-egypt.com/apps/) ورابط واتساب المباشر (https://wa.me/962798583052).
|
|
|
|
اكتب منشوراً جذاباً جداً باللغة العربية، منسقاً بالإيموجيات والعناوين والنقاط الواضحة والهاشتاغات المناسبة.`;
|
|
|
|
const url = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`;
|
|
|
|
const res = await fetch(url, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
contents: [
|
|
{
|
|
role: 'user',
|
|
parts: [{ text: `${systemInstruction}\n\nالموضوع المطلوب كتابة منشور عنه:\n${topic}` }]
|
|
}
|
|
]
|
|
})
|
|
});
|
|
|
|
const data = await res.json();
|
|
if (data.error) {
|
|
throw new Error(`Gemini API Error: ${data.error.message}`);
|
|
}
|
|
|
|
const generatedText = data.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
if (!generatedText) {
|
|
throw new Error('Gemini API returned an empty response.');
|
|
}
|
|
|
|
return generatedText.trim();
|
|
}
|
|
|
|
/**
|
|
* Publish generated post to Meta Facebook Page (supports optional image)
|
|
*/
|
|
async function publishToFacebook(message, imageUrl = null) {
|
|
console.log(`Publishing generated post to Facebook Page ID: ${META_PAGE_ID}...`);
|
|
|
|
const endpoint = imageUrl ? `${META_PAGE_ID}/photos` : `${META_PAGE_ID}/feed`;
|
|
const url = `https://graph.facebook.com/v19.0/${endpoint}`;
|
|
|
|
const payload = imageUrl
|
|
? { access_token: META_ACCESS_TOKEN, caption: message, url: imageUrl }
|
|
: { access_token: META_ACCESS_TOKEN, message: message };
|
|
|
|
const res = await fetch(url, {
|
|
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.code}]: ${data.error.message}`);
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
async function main() {
|
|
const topic = process.argv[2] || 'منشور تعريفي عن منصة Tripz ومزايا التملك والشفافية والتوفير وحاسبة الأرباح';
|
|
const imageUrl = process.argv[3] || null;
|
|
|
|
try {
|
|
const postContent = await generatePostWithGemini(topic);
|
|
console.log('\n--- Generated Post Content ---\n');
|
|
console.log(postContent);
|
|
console.log('\n------------------------------\n');
|
|
|
|
if (imageUrl) {
|
|
console.log('Attached Image Creative URL:', imageUrl);
|
|
}
|
|
|
|
const result = await publishToFacebook(postContent, imageUrl);
|
|
console.log('🎉 Post Published Successfully to Facebook!');
|
|
console.log('Meta Post ID:', result.id || result.post_id);
|
|
} catch (err) {
|
|
console.error('❌ Error:', err.message);
|
|
}
|
|
}
|
|
|
|
if (require.main === module) {
|
|
main();
|
|
}
|
|
|
|
module.exports = { generatePostWithGemini, publishToFacebook };
|