← back to Norma
agents/facebook-agent/skills/monitor.js
92 lines
/**
* Facebook Monitor Skill
*
* Checks Facebook Page insights (reach, engagement, impressions).
* Runs in simulation mode when FB_PAGE_ACCESS_TOKEN is not set.
*
* Real endpoint:
* GET https://graph.facebook.com/v19.0/{page_id}/insights
* Params: metric=page_impressions,page_engaged_users,page_fan_adds&period=day&access_token=TOKEN
*/
const AGENT = 'facebook-agent';
const PLATFORM = 'facebook';
function hasCredentials() {
return !!(process.env.FB_PAGE_ID && process.env.FB_PAGE_ACCESS_TOKEN);
}
/**
* @param {Object} params - Request body
* @param {string} [params.period=day] - Insights period (day, week, days_28)
* @param {boolean} [params.push_to_pulse=true] - Push results to Pulse
* @returns {Promise<Object>}
*/
module.exports = async function monitor(params) {
const period = params.period || 'day';
const simulated = !hasCredentials();
console.log(`[${AGENT}] Monitor skill invoked — simulation=${simulated}, period=${period}`);
if (simulated) {
// --- Simulation mode: return realistic-looking insights ---
const insights = {
reach: Math.floor(Math.random() * 5000) + 500,
impressions: Math.floor(Math.random() * 10000) + 1000,
engaged_users: Math.floor(Math.random() * 800) + 100,
new_fans: Math.floor(Math.random() * 50) + 5,
post_engagements: Math.floor(Math.random() * 300) + 50,
page_views: Math.floor(Math.random() * 2000) + 200,
};
console.log(`[${AGENT}] SIMULATED monitor: reach=${insights.reach}, engaged=${insights.engaged_users}`);
return {
insights,
period,
simulated: true,
platform: PLATFORM,
checked_at: new Date().toISOString(),
};
}
// --- Real API call (commented out until credentials are configured) ---
//
// const pageId = process.env.FB_PAGE_ID;
// const accessToken = process.env.FB_PAGE_ACCESS_TOKEN;
//
// const metrics = [
// 'page_impressions',
// 'page_engaged_users',
// 'page_fan_adds',
// 'page_post_engagements',
// 'page_views_total',
// ].join(',');
//
// const url = `https://graph.facebook.com/v19.0/${pageId}/insights?metric=${metrics}&period=${period}&access_token=${accessToken}`;
//
// const response = await fetch(url);
// const data = await response.json();
//
// if (data.error) {
// throw new Error(`Facebook API error: ${data.error.message}`);
// }
//
// const insights = {};
// for (const entry of data.data) {
// const value = entry.values?.[entry.values.length - 1]?.value || 0;
// insights[entry.name] = value;
// }
//
// return {
// insights,
// period,
// raw: data.data,
// simulated: false,
// platform: PLATFORM,
// checked_at: new Date().toISOString(),
// };
return { error: 'Real API call not yet enabled. Uncomment the code above.' };
};