12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- from datetime import datetime
- import os
- import requests
- from google.analytics.data_v1beta import BetaAnalyticsDataClient
- from google.analytics.data_v1beta.types import (
- DateRange,
- Dimension,
- Metric,
- MetricType,
- RunReportRequest,
- )
- # IMPORTANT: Please set up GOOGLE_APPLICATION_CREDENTIALS through export (Bash) OR Environment Variables (Windows).
- # GOOGLE_APPLICATION_CREDENTIALS = "[path to credentials.json file]"
- # Insert PROPERTY IDs you want to track here.
- # Format: ["property_ID","property_name"]
- # KEEP THIS IN TUPLE FORM EVEN IF ONLY ONE DATA SOURCE IS USED !!
- os.environ['GOOGLE_APPLICATION_CREDENTIALS']="C:\/Users\/s1301\/Downloads\/corded-velocity-301807-b52c79741854.json"
- # property_id = [["336444388","Icons_EN"],["336427321","Icons_ZH"]] # CHANGE HERE
- property_id = [["336444388","Icons_EN"]] # CHANGE HERE
- # Insert PageView target here.
- pv_target = 800
- # Show whether target is achieved or not. Set to 1 to enable.
- show_target = 0
- # Enable/disable send to LINE Notify. Set to 1 to enable.
- send = 1
- # Insert destination LINE Group ID here.
- LINE_GROUP_ID = 'zRyvl5OGuQZWpZqRmRsBT23qZ4ID9Ev6I7Jbz2gtpRU'
- # LINE Notify Header
- headers = {
- "Authorization": "Bearer " + LINE_GROUP_ID,
- "Content-Type": "application/x-www-form-urlencoded"
- }
- def send_msg(msg):
- current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- params = {"message": "Time: " + current_time + "\n" + msg}
- # r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
- def run_report():
- client = BetaAnalyticsDataClient()
- total = 0
- message = ""
-
- for p in property_id:
- request = RunReportRequest(
- property=f"properties/{p[0]}",
- metrics=[Metric(name="screenPageViews")],
- date_ranges=[DateRange(start_date="today", end_date="today")],
- )
- response = client.run_report(request)
- for rowIdx, row in enumerate(response.rows):
- for i, metric_value in enumerate(row.metric_values):
- metric_name = response.metric_headers[i].name
- viewcount = metric_value.value
- message = message + (f"{p[1]} / {metric_name}: {viewcount}\n")
- total = total + int(viewcount)
- message = message + (f"Total views: {total}\n")
- if show_target == 1:
- if total >= pv_target:
- message = message + ("Target reached\n")
- else:
- message = message + ("Target not reached\n")
- print(message)
- if send == 1:
- send_msg(message)
- run_report()
|