benchmark-facebook-ads.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /**
  2. * benchmark-facebook-ads.js — Veille pubs Facebook
  3. *
  4. * Deux modes :
  5. * 1. **URLs publiques (par défaut)** — Génère des liens vers la Meta Ad Library publique.
  6. * - Si facebook_page_id dans competitors.json : URL par page (view_all_page_id)
  7. * - Sinon : recherche par mot-clé (nom du concurrent)
  8. *
  9. * 2. **API Meta (optionnel)** — Si META_AD_LIBRARY_TOKEN + facebook_page_id configurés,
  10. * récupère les pubs en JSON via l'API officielle.
  11. *
  12. * Usage :
  13. * node scripts/benchmark-facebook-ads.js [livinweb|livinia|all]
  14. *
  15. * Output : knowledge/benchmarks/benchmark-facebook-YYYY-WXX.md
  16. */
  17. require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
  18. const https = require('https');
  19. const fs = require('fs');
  20. const path = require('path');
  21. const TOKEN = process.env.META_AD_LIBRARY_TOKEN;
  22. const COMPETITORS_FILE = path.resolve(__dirname, '../knowledge/shared/competitors.json');
  23. const BENCHMARKS_DIR = path.resolve(__dirname, '../knowledge/benchmarks');
  24. const AD_LIBRARY_VERSION = 'v19.0';
  25. function getISOWeek(date) {
  26. const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  27. const dayNum = d.getUTCDay() || 7;
  28. d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  29. const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  30. return {
  31. year: d.getUTCFullYear(),
  32. week: Math.ceil((((d - yearStart) / 86400000) + 1) / 7),
  33. };
  34. }
  35. function httpsGet(url) {
  36. return new Promise((resolve, reject) => {
  37. https.get(url, (res) => {
  38. let data = '';
  39. res.on('data', (chunk) => { data += chunk; });
  40. res.on('end', () => {
  41. try { resolve(JSON.parse(data)); }
  42. catch (e) { reject(new Error(`Parsing JSON failed: ${data.slice(0, 200)}`)); }
  43. });
  44. }).on('error', reject);
  45. });
  46. }
  47. async function fetchAdsForPage(pageId, pageName, countries = ['FR']) {
  48. if (!TOKEN) {
  49. console.warn(`⚠️ META_AD_LIBRARY_TOKEN non défini dans .env — appel simulé pour ${pageName}`);
  50. return { data: [], simulated: true };
  51. }
  52. const params = new URLSearchParams({
  53. access_token: TOKEN,
  54. search_page_ids: pageId,
  55. ad_reached_countries: countries.join(','),
  56. ad_active_status: 'ACTIVE',
  57. limit: 20,
  58. fields: [
  59. 'id',
  60. 'page_name',
  61. 'ad_creation_time',
  62. 'ad_creative_bodies',
  63. 'ad_creative_link_titles',
  64. 'ad_creative_link_descriptions',
  65. 'ad_delivery_start_time',
  66. 'impressions',
  67. 'spend',
  68. 'publisher_platforms',
  69. 'ad_snapshot_url',
  70. ].join(','),
  71. });
  72. const url = `https://graph.facebook.com/${AD_LIBRARY_VERSION}/ads_archive?${params}`;
  73. try {
  74. const result = await httpsGet(url);
  75. if (result.error) {
  76. console.error(`❌ Erreur API Meta pour ${pageName} (${pageId}) :`, result.error.message);
  77. return { data: [], error: result.error.message };
  78. }
  79. return result;
  80. } catch (err) {
  81. console.error(`❌ Erreur réseau pour ${pageName} :`, err.message);
  82. return { data: [], error: err.message };
  83. }
  84. }
  85. /**
  86. * Génère l'URL de la Meta Ad Library publique (recherche par mot-clé).
  87. * @see https://www.facebook.com/ads/library/
  88. */
  89. function buildAdLibrarySearchUrl(keyword, country = 'FR') {
  90. const params = new URLSearchParams({
  91. active_status: 'active',
  92. ad_type: 'all',
  93. country,
  94. is_targeted_country: 'false',
  95. media_type: 'all',
  96. q: keyword,
  97. search_type: 'keyword_unordered',
  98. 'sort_data[mode]': 'total_impressions',
  99. 'sort_data[direction]': 'desc',
  100. });
  101. return `https://www.facebook.com/ads/library/?${params.toString()}`;
  102. }
  103. /**
  104. * Génère l'URL de la Meta Ad Library publique (recherche par page ID).
  105. * Plus précis que la recherche par mot-clé — affiche toutes les pubs de la page.
  106. * @see https://www.facebook.com/ads/library/
  107. */
  108. function buildAdLibraryPageUrl(pageId, country = 'FR') {
  109. const params = new URLSearchParams({
  110. active_status: 'all',
  111. ad_type: 'all',
  112. country,
  113. is_targeted_country: 'false',
  114. media_type: 'all',
  115. search_type: 'page',
  116. 'sort_data[direction]': 'desc',
  117. 'sort_data[mode]': 'total_impressions',
  118. source: 'fb-logo',
  119. view_all_page_id: pageId,
  120. });
  121. return `https://www.facebook.com/ads/library/?${params.toString()}`;
  122. }
  123. function formatAdForMarkdown(ad) {
  124. const lines = [];
  125. const date = ad.ad_delivery_start_time
  126. ? new Date(ad.ad_delivery_start_time).toLocaleDateString('fr-FR')
  127. : ad.ad_creation_time
  128. ? new Date(ad.ad_creation_time).toLocaleDateString('fr-FR')
  129. : 'date inconnue';
  130. const platforms = (ad.publisher_platforms || []).join(', ') || 'n/a';
  131. const body = (ad.ad_creative_bodies || []).join(' | ').slice(0, 300) || '_corps non disponible_';
  132. const title = (ad.ad_creative_link_titles || []).join(' | ').slice(0, 150) || '';
  133. const impressions = ad.impressions
  134. ? `${ad.impressions.lower_bound || '?'} – ${ad.impressions.upper_bound || '?'}`
  135. : 'n/a';
  136. const spend = ad.spend
  137. ? `${ad.spend.lower_bound || '?'} – ${ad.spend.upper_bound || '?'} ${ad.spend.currency || '€'}`
  138. : 'n/a';
  139. lines.push(`- **Date de lancement :** ${date}`);
  140. lines.push(`- **Plateformes :** ${platforms}`);
  141. if (title) lines.push(`- **Titre/Headline :** ${title}`);
  142. lines.push(`- **Corps :** ${body}`);
  143. lines.push(`- **Impressions :** ${impressions} | **Dépenses :** ${spend}`);
  144. if (ad.ad_snapshot_url) lines.push(`- **Aperçu :** [Voir la pub](${ad.ad_snapshot_url})`);
  145. return lines.join('\n');
  146. }
  147. async function run() {
  148. const brand = process.argv[2] || 'all';
  149. if (!fs.existsSync(COMPETITORS_FILE)) {
  150. console.error('❌ Fichier competitors.json introuvable. Remplir knowledge/shared/competitors.json d\'abord.');
  151. process.exit(1);
  152. }
  153. const competitors = JSON.parse(fs.readFileSync(COMPETITORS_FILE, 'utf8'));
  154. const { year, week } = getISOWeek(new Date());
  155. const weekLabel = `${year}-W${String(week).padStart(2, '0')}`;
  156. const outputFile = path.join(BENCHMARKS_DIR, `benchmark-facebook-${weekLabel}.md`);
  157. const brandsToProcess = brand === 'all'
  158. ? ['livinweb', 'livinia']
  159. : [brand];
  160. const lines = [
  161. `---`,
  162. `generated_date: "${new Date().toISOString().split('T')[0]}"`,
  163. `week: "${weekLabel}"`,
  164. `workflow: "benchmark-pub-facebook"`,
  165. `status: "draft"`,
  166. `---`,
  167. ``,
  168. `# Benchmark Facebook Ads — ${weekLabel}`,
  169. ``,
  170. `> Généré par \`benchmark-facebook-ads.js\` — [Meta Ad Library](https://www.facebook.com/ads/library/)`,
  171. `> Cliquer sur les liens ci-dessous pour consulter les pubs (par page ID ou mot-clé, France).`,
  172. ``,
  173. ];
  174. // Mots-clés sectoriels pour recherche additionnelle
  175. const sectorKeywords = {
  176. livinweb: ['excel application web', 'ERP PME', 'développement web sur mesure'],
  177. livinia: ['intelligence artificielle', 'IA entreprise', 'automatisation IA'],
  178. };
  179. for (const b of brandsToProcess) {
  180. const list = (competitors[b] || []).filter(c => c.active);
  181. lines.push(`## ${b.charAt(0).toUpperCase() + b.slice(1)}`);
  182. lines.push('');
  183. if (list.length === 0) {
  184. lines.push(`_Aucun concurrent actif configuré pour ${b}. Remplir competitors.json._`);
  185. lines.push('');
  186. continue;
  187. }
  188. // Recherches sectorielles
  189. const keywords = sectorKeywords[b] || [];
  190. if (keywords.length > 0) {
  191. lines.push('### Recherches sectorielles');
  192. lines.push('');
  193. keywords.forEach(kw => {
  194. lines.push(`- [${kw}](${buildAdLibrarySearchUrl(kw)})`);
  195. });
  196. lines.push('');
  197. }
  198. for (const competitor of list) {
  199. const searchKeyword = competitor.name.replace(/\s+/g, ' ').trim();
  200. const adLibraryUrl = competitor.facebook_page_id
  201. ? buildAdLibraryPageUrl(competitor.facebook_page_id)
  202. : buildAdLibrarySearchUrl(searchKeyword);
  203. lines.push(`### ${competitor.name}`);
  204. lines.push('');
  205. lines.push(`**🔗 [Voir les pubs actives sur Meta Ad Library](${adLibraryUrl})**`);
  206. lines.push('');
  207. lines.push(competitor.facebook_page_id
  208. ? `> Page ID : \`${competitor.facebook_page_id}\` | Pays : France | Tri : impressions décroissantes`
  209. : `> Recherche : \`${searchKeyword}\` | Pays : France | Tri : impressions décroissantes`);
  210. lines.push('');
  211. // API : uniquement si token + page_id configurés
  212. if (competitor.facebook_page_id && TOKEN) {
  213. console.log(`🔍 API : récupération des pubs pour ${competitor.name}...`);
  214. const result = await fetchAdsForPage(
  215. competitor.facebook_page_id,
  216. competitor.name
  217. );
  218. if (!result.error && result.data && result.data.length > 0) {
  219. lines.push(`**${result.data.length} pub(s) récupérée(s) via API :**`);
  220. lines.push('');
  221. result.data.forEach((ad, i) => {
  222. lines.push(`#### Pub ${i + 1}`);
  223. lines.push(formatAdForMarkdown(ad));
  224. lines.push('');
  225. });
  226. } else if (result.error) {
  227. lines.push(`> ⚠️ API : ${result.error}`);
  228. lines.push('');
  229. }
  230. } else {
  231. lines.push('_Consulter le lien ci-dessus pour analyser les pubs manuellement._');
  232. lines.push('');
  233. }
  234. }
  235. }
  236. lines.push('---');
  237. lines.push('');
  238. lines.push('## Analyse agent — À compléter');
  239. lines.push('');
  240. lines.push('> Section remplie par l\'agent benchmark-pub-facebook lors du workflow 6');
  241. lines.push('');
  242. lines.push('- **Angles créatifs dominants chez les concurrents :**');
  243. lines.push('- **Formats qui reviennent :**');
  244. lines.push('- **Offres poussées cette semaine :**');
  245. lines.push('- **Opportunités différenciantes pour Livinweb/Livinia :**');
  246. fs.mkdirSync(BENCHMARKS_DIR, { recursive: true });
  247. fs.writeFileSync(outputFile, lines.join('\n'), 'utf8');
  248. console.log(`\n✅ Rapport Facebook généré : ${outputFile}`);
  249. console.log(` Semaine : ${weekLabel}`);
  250. }
  251. run().catch(err => {
  252. console.error('❌ Erreur fatale :', err.message);
  253. process.exit(1);
  254. });