| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285 |
- /**
- * benchmark-facebook-ads.js — Veille pubs Facebook
- *
- * Deux modes :
- * 1. **URLs publiques (par défaut)** — Génère des liens vers la Meta Ad Library publique.
- * - Si facebook_page_id dans competitors.json : URL par page (view_all_page_id)
- * - Sinon : recherche par mot-clé (nom du concurrent)
- *
- * 2. **API Meta (optionnel)** — Si META_AD_LIBRARY_TOKEN + facebook_page_id configurés,
- * récupère les pubs en JSON via l'API officielle.
- *
- * Usage :
- * node scripts/benchmark-facebook-ads.js [livinweb|livinia|all]
- *
- * Output : knowledge/benchmarks/benchmark-facebook-YYYY-WXX.md
- */
- require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
- const https = require('https');
- const fs = require('fs');
- const path = require('path');
- const TOKEN = process.env.META_AD_LIBRARY_TOKEN;
- const COMPETITORS_FILE = path.resolve(__dirname, '../knowledge/shared/competitors.json');
- const BENCHMARKS_DIR = path.resolve(__dirname, '../knowledge/benchmarks');
- const AD_LIBRARY_VERSION = 'v19.0';
- function getISOWeek(date) {
- const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
- const dayNum = d.getUTCDay() || 7;
- d.setUTCDate(d.getUTCDate() + 4 - dayNum);
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
- return {
- year: d.getUTCFullYear(),
- week: Math.ceil((((d - yearStart) / 86400000) + 1) / 7),
- };
- }
- function httpsGet(url) {
- return new Promise((resolve, reject) => {
- https.get(url, (res) => {
- let data = '';
- res.on('data', (chunk) => { data += chunk; });
- res.on('end', () => {
- try { resolve(JSON.parse(data)); }
- catch (e) { reject(new Error(`Parsing JSON failed: ${data.slice(0, 200)}`)); }
- });
- }).on('error', reject);
- });
- }
- async function fetchAdsForPage(pageId, pageName, countries = ['FR']) {
- if (!TOKEN) {
- console.warn(`⚠️ META_AD_LIBRARY_TOKEN non défini dans .env — appel simulé pour ${pageName}`);
- return { data: [], simulated: true };
- }
- const params = new URLSearchParams({
- access_token: TOKEN,
- search_page_ids: pageId,
- ad_reached_countries: countries.join(','),
- ad_active_status: 'ACTIVE',
- limit: 20,
- fields: [
- 'id',
- 'page_name',
- 'ad_creation_time',
- 'ad_creative_bodies',
- 'ad_creative_link_titles',
- 'ad_creative_link_descriptions',
- 'ad_delivery_start_time',
- 'impressions',
- 'spend',
- 'publisher_platforms',
- 'ad_snapshot_url',
- ].join(','),
- });
- const url = `https://graph.facebook.com/${AD_LIBRARY_VERSION}/ads_archive?${params}`;
- try {
- const result = await httpsGet(url);
- if (result.error) {
- console.error(`❌ Erreur API Meta pour ${pageName} (${pageId}) :`, result.error.message);
- return { data: [], error: result.error.message };
- }
- return result;
- } catch (err) {
- console.error(`❌ Erreur réseau pour ${pageName} :`, err.message);
- return { data: [], error: err.message };
- }
- }
- /**
- * Génère l'URL de la Meta Ad Library publique (recherche par mot-clé).
- * @see https://www.facebook.com/ads/library/
- */
- function buildAdLibrarySearchUrl(keyword, country = 'FR') {
- const params = new URLSearchParams({
- active_status: 'active',
- ad_type: 'all',
- country,
- is_targeted_country: 'false',
- media_type: 'all',
- q: keyword,
- search_type: 'keyword_unordered',
- 'sort_data[mode]': 'total_impressions',
- 'sort_data[direction]': 'desc',
- });
- return `https://www.facebook.com/ads/library/?${params.toString()}`;
- }
- /**
- * Génère l'URL de la Meta Ad Library publique (recherche par page ID).
- * Plus précis que la recherche par mot-clé — affiche toutes les pubs de la page.
- * @see https://www.facebook.com/ads/library/
- */
- function buildAdLibraryPageUrl(pageId, country = 'FR') {
- const params = new URLSearchParams({
- active_status: 'all',
- ad_type: 'all',
- country,
- is_targeted_country: 'false',
- media_type: 'all',
- search_type: 'page',
- 'sort_data[direction]': 'desc',
- 'sort_data[mode]': 'total_impressions',
- source: 'fb-logo',
- view_all_page_id: pageId,
- });
- return `https://www.facebook.com/ads/library/?${params.toString()}`;
- }
- function formatAdForMarkdown(ad) {
- const lines = [];
- const date = ad.ad_delivery_start_time
- ? new Date(ad.ad_delivery_start_time).toLocaleDateString('fr-FR')
- : ad.ad_creation_time
- ? new Date(ad.ad_creation_time).toLocaleDateString('fr-FR')
- : 'date inconnue';
- const platforms = (ad.publisher_platforms || []).join(', ') || 'n/a';
- const body = (ad.ad_creative_bodies || []).join(' | ').slice(0, 300) || '_corps non disponible_';
- const title = (ad.ad_creative_link_titles || []).join(' | ').slice(0, 150) || '';
- const impressions = ad.impressions
- ? `${ad.impressions.lower_bound || '?'} – ${ad.impressions.upper_bound || '?'}`
- : 'n/a';
- const spend = ad.spend
- ? `${ad.spend.lower_bound || '?'} – ${ad.spend.upper_bound || '?'} ${ad.spend.currency || '€'}`
- : 'n/a';
- lines.push(`- **Date de lancement :** ${date}`);
- lines.push(`- **Plateformes :** ${platforms}`);
- if (title) lines.push(`- **Titre/Headline :** ${title}`);
- lines.push(`- **Corps :** ${body}`);
- lines.push(`- **Impressions :** ${impressions} | **Dépenses :** ${spend}`);
- if (ad.ad_snapshot_url) lines.push(`- **Aperçu :** [Voir la pub](${ad.ad_snapshot_url})`);
- return lines.join('\n');
- }
- async function run() {
- const brand = process.argv[2] || 'all';
- if (!fs.existsSync(COMPETITORS_FILE)) {
- console.error('❌ Fichier competitors.json introuvable. Remplir knowledge/shared/competitors.json d\'abord.');
- process.exit(1);
- }
- const competitors = JSON.parse(fs.readFileSync(COMPETITORS_FILE, 'utf8'));
- const { year, week } = getISOWeek(new Date());
- const weekLabel = `${year}-W${String(week).padStart(2, '0')}`;
- const outputFile = path.join(BENCHMARKS_DIR, `benchmark-facebook-${weekLabel}.md`);
- const brandsToProcess = brand === 'all'
- ? ['livinweb', 'livinia']
- : [brand];
- const lines = [
- `---`,
- `generated_date: "${new Date().toISOString().split('T')[0]}"`,
- `week: "${weekLabel}"`,
- `workflow: "benchmark-pub-facebook"`,
- `status: "draft"`,
- `---`,
- ``,
- `# Benchmark Facebook Ads — ${weekLabel}`,
- ``,
- `> Généré par \`benchmark-facebook-ads.js\` — [Meta Ad Library](https://www.facebook.com/ads/library/)`,
- `> Cliquer sur les liens ci-dessous pour consulter les pubs (par page ID ou mot-clé, France).`,
- ``,
- ];
- // Mots-clés sectoriels pour recherche additionnelle
- const sectorKeywords = {
- livinweb: ['excel application web', 'ERP PME', 'développement web sur mesure'],
- livinia: ['intelligence artificielle', 'IA entreprise', 'automatisation IA'],
- };
- for (const b of brandsToProcess) {
- const list = (competitors[b] || []).filter(c => c.active);
- lines.push(`## ${b.charAt(0).toUpperCase() + b.slice(1)}`);
- lines.push('');
- if (list.length === 0) {
- lines.push(`_Aucun concurrent actif configuré pour ${b}. Remplir competitors.json._`);
- lines.push('');
- continue;
- }
- // Recherches sectorielles
- const keywords = sectorKeywords[b] || [];
- if (keywords.length > 0) {
- lines.push('### Recherches sectorielles');
- lines.push('');
- keywords.forEach(kw => {
- lines.push(`- [${kw}](${buildAdLibrarySearchUrl(kw)})`);
- });
- lines.push('');
- }
- for (const competitor of list) {
- const searchKeyword = competitor.name.replace(/\s+/g, ' ').trim();
- const adLibraryUrl = competitor.facebook_page_id
- ? buildAdLibraryPageUrl(competitor.facebook_page_id)
- : buildAdLibrarySearchUrl(searchKeyword);
- lines.push(`### ${competitor.name}`);
- lines.push('');
- lines.push(`**🔗 [Voir les pubs actives sur Meta Ad Library](${adLibraryUrl})**`);
- lines.push('');
- lines.push(competitor.facebook_page_id
- ? `> Page ID : \`${competitor.facebook_page_id}\` | Pays : France | Tri : impressions décroissantes`
- : `> Recherche : \`${searchKeyword}\` | Pays : France | Tri : impressions décroissantes`);
- lines.push('');
- // API : uniquement si token + page_id configurés
- if (competitor.facebook_page_id && TOKEN) {
- console.log(`🔍 API : récupération des pubs pour ${competitor.name}...`);
- const result = await fetchAdsForPage(
- competitor.facebook_page_id,
- competitor.name
- );
- if (!result.error && result.data && result.data.length > 0) {
- lines.push(`**${result.data.length} pub(s) récupérée(s) via API :**`);
- lines.push('');
- result.data.forEach((ad, i) => {
- lines.push(`#### Pub ${i + 1}`);
- lines.push(formatAdForMarkdown(ad));
- lines.push('');
- });
- } else if (result.error) {
- lines.push(`> ⚠️ API : ${result.error}`);
- lines.push('');
- }
- } else {
- lines.push('_Consulter le lien ci-dessus pour analyser les pubs manuellement._');
- lines.push('');
- }
- }
- }
- lines.push('---');
- lines.push('');
- lines.push('## Analyse agent — À compléter');
- lines.push('');
- lines.push('> Section remplie par l\'agent benchmark-pub-facebook lors du workflow 6');
- lines.push('');
- lines.push('- **Angles créatifs dominants chez les concurrents :**');
- lines.push('- **Formats qui reviennent :**');
- lines.push('- **Offres poussées cette semaine :**');
- lines.push('- **Opportunités différenciantes pour Livinweb/Livinia :**');
- fs.mkdirSync(BENCHMARKS_DIR, { recursive: true });
- fs.writeFileSync(outputFile, lines.join('\n'), 'utf8');
- console.log(`\n✅ Rapport Facebook généré : ${outputFile}`);
- console.log(` Semaine : ${weekLabel}`);
- }
- run().catch(err => {
- console.error('❌ Erreur fatale :', err.message);
- process.exit(1);
- });
|