360 Secure SkillHub
360 安全技能中心

ga4-analytics

该 Skill 使用 Google 服务账号,通过 Google Analytics 4、Search Console 和 Indexing API 读取单一属性和站点的流量、来源、页面、关键词、实时访客及索引状态,并生成表格与建议;查询为只读,重新收录按请求执行,移除索引必须显式确认。默认不写入磁盘,设置 SAVE_RESULTS=true 才保存结果。

分类:数据
adamkristopher
adamkristopher
热度 59.40
最近更新 2026-11-29 02:53:04

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add adamkristopher/ga4-analytics
兼容性
通用兼容
联网要求
需要联网
数据出网
必须出网
Metadata
name
ga4-analytics
description
Google Analytics 4, Search Console and Indexing API toolkit: site traffic, top pages, traffic sources, demographics, real-time visitors, search queries, SEO page performance, index status, re-index requests, and (only with explicit confirmation) requests to remove a URL from Google's index. Use when the user asks about their site's traffic, search queries or indexing. Uses the user's own Google service account from .env for one GA4 property and one Search Console site. Saves nothing to disk unless SAVE_RESULTS=true.
version
1.1.1
homepage
https://github.com/adamkristopher/clawhub-skills/tree/main/ga4-analytics
metadata
{"openclaw":{"homepage":"https://github.com/adamkristopher/clawhub-skills/tree/main/ga4-analytics","primaryEnv":"GA4_PRIVATE_KEY","requires":{"bins":["node","npm"],"env":["GA4_PROPERTY_ID","GA4_CLIENT_EMAIL","GA4_PRIVATE_KEY"]},"envVars":[{"name":"GA4_PROPERTY_ID","required":true,"description":"The GA4 property to read (numbers only)."},{"name":"GA4_CLIENT_EMAIL","required":true,"description":"Service account email. Give it Viewer on the GA4 property and access to the one Search Console site, nothing more."},{"name":"GA4_PRIVATE_KEY","required":true,"description":"The service account's private key. Used only to sign Google API requests; never sent anywhere else."},{"name":"SEARCH_CONSOLE_SITE_URL","required":false,"description":"Search Console site, e.g. https://example.com. Needed for Search Console and indexing functions."},{"name":"GA4_DEFAULT_DATE_RANGE","required":false,"description":"Default report range, e.g. 30d."},{"name":"SAVE_RESULTS","required":false,"description":"The only way to turn saving on - set to true to save results as JSON under ./results. Off by default. A call's save false can still skip saving."},{"name":"RESULTS_DIR","required":false,"description":"Where saved results go if SAVE_RESULTS is true. Default ./results in the working directory."}]}}

GA4 Analytics Toolkit

What this skill does with your data

  • Network: calls Google only: the Analytics Data API, Search Console API and Indexing API (*.googleapis.com).
  • Credentials: a Google Cloud service account from .env in the working directory. Use least privilege: Viewer on the one GA4 property, and access to the one Search Console site. The Indexing API scope is needed only for reindexUrls / requestIndexing. Keep .env out of version control.
  • What's sent: your property ID, site URL, date ranges, and any URLs you ask to inspect or re-index.
  • Changes it can make: reindexUrls asks Google to recrawl URLs. removeFromIndex asks Google to drop a URL from Search; it refuses unless called with { confirm: true }, and should only be used when the site owner asks to remove that exact URL. Everything else is read-only.
  • Files: nothing is written unless you set SAVE_RESULTS=true; no function argument can turn saving on. Saved files are readable only by you (0600) and can only go in the results/ folders listed below.

Setup

Install the pinned dependencies from the lockfile:

cd scripts && npm ci --ignore-scripts

Configure credentials by creating a .env file in the project root:

GA4_PROPERTY_ID=123456789
GA4_CLIENT_EMAIL=service-account@project.iam.gserviceaccount.com
GA4_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
SEARCH_CONSOLE_SITE_URL=https://your-domain.com
GA4_DEFAULT_DATE_RANGE=30d
# Optional: keep results on disk
# SAVE_RESULTS=true

Prerequisites: A Google Cloud project with the Analytics Data API, Search Console API, and Indexing API enabled. A service account with access to your GA4 property and Search Console.

Quick Start

User says Function to call
"Show me site traffic for the last 30 days" siteOverview("30d")
"What are my top search queries?" searchConsoleOverview("30d")
"Who's on the site right now?" liveSnapshot()
"Reindex these URLs" reindexUrls(["https://example.com/page1", ...])
"Compare this month vs last month" compareDateRanges({startDate: "30daysAgo", endDate: "today"}, {startDate: "60daysAgo", endDate: "31daysAgo"})
"What pages get the most traffic?" contentPerformance("30d")

Execute functions by importing from scripts/src/index.ts:

import { siteOverview, searchConsoleOverview } from './scripts/src/index.js';

const overview = await siteOverview('30d');

Or run it with the project's pinned tsx (installed by npm ci):

cd scripts && npm start

Workflow Pattern

Every analysis follows two phases:

1. Analyze

Run API functions. Each call hits the Google APIs and returns structured data to you. Nothing is written to disk.

2. Summarize

Summarize the returned data for the user: tables, trends and recommendations. Write a summary file only if the user asks for one.

Saving (opt-in): only with SAVE_RESULTS=true in .env are results also saved as timestamped JSON in results/{category}/ (YYYYMMDD_HHMMSS__operation__extra_info.json).

High-Level Functions

GA4 Analytics

Function Purpose What it gathers
siteOverview(dateRange?) Comprehensive site snapshot Page views, traffic sources, demographics, events
trafficAnalysis(dateRange?) Traffic deep-dive Sources, sessions by source/medium, new vs returning
contentPerformance(dateRange?) Top pages analysis Page views, landing pages, exit pages
userBehavior(dateRange?) Engagement patterns Demographics, events, daily engagement metrics
compareDateRanges(range1, range2) Period comparison Side-by-side metrics for two date ranges
liveSnapshot() Real-time data Active users, current pages, current events

Search Console

Function Purpose What it gathers
searchConsoleOverview(dateRange?) SEO snapshot Top queries, pages, device, country breakdown
keywordAnalysis(dateRange?) Keyword deep-dive Queries with device breakdown
seoPagePerformance(dateRange?) Page SEO metrics Top pages by clicks, country breakdown

Indexing

Function Purpose
reindexUrls(urls) Ask Google to recrawl multiple URLs
checkIndexStatus(urls) Check if URLs are indexed (read-only)

removeFromIndex(url, { confirm: true }) is available from the API module but is destructive: it asks Google to drop the URL from Search. Use it only when the site owner asks to remove that exact URL. See references/api-reference.md.

Utility

Function Purpose
getAvailableFields() List all available GA4 dimensions and metrics

Individual API Functions

For granular control, import specific functions from the API modules. See references/api-reference.md for the complete list of 30+ API functions with parameters, types, and examples.

Date Ranges

All functions accept flexible date range formats:

Format Example Description
Shorthand "7d", "30d", "90d" Days ago to today
Explicit {startDate: "2024-01-01", endDate: "2024-01-31"} Specific dates
GA4 relative {startDate: "30daysAgo", endDate: "today"} GA4 relative format

Default is "30d" (configurable via GA4_DEFAULT_DATE_RANGE in .env).

Results Storage (only if you opt in)

Off by default. Only with SAVE_RESULTS=true are results saved to results/ (or RESULTS_DIR) with this structure. Categories are fixed (reports, realtime, searchconsole, indexing, metadata, summaries): other names are refused, and loadResult only reads files inside results/.

results/
├── reports/          # GA4 standard reports
├── realtime/         # Real-time snapshots
├── searchconsole/    # Search Console data
├── indexing/         # Indexing API results
└── summaries/        # Human-readable markdown summaries

Managing Results

import { listResults, loadResult, getLatestResult } from './scripts/src/index.js';

// List recent results
const files = listResults('reports', 10);

// Load a specific result
const data = loadResult(files[0]);

// Get most recent result for an operation
const latest = getLatestResult('reports', 'site_overview');

Common Dimensions and Metrics

Dimensions

pagePath, pageTitle, sessionSource, sessionMedium, country, deviceCategory, browser, date, eventName, landingPage, newVsReturning

Metrics

screenPageViews, activeUsers, sessions, newUsers, bounceRate, averageSessionDuration, engagementRate, conversions, totalRevenue, eventCount

Tips

  1. Specify date ranges — "last 7 days" or "last 90 days" gives different insights than the default 30 days
  2. Request summaries — After pulling data, ask for a markdown summary with tables and insights (saved to results/summaries/ only if you ask)
  3. Compare periods — Use compareDateRanges() to spot trends (this month vs last month)
  4. Check real-time data — liveSnapshot() shows who's on the site right now
  5. Combine GA4 + Search Console — Traffic data plus search query data gives the full picture