123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- from datetime import datetime, timedelta
- 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]"
- os.environ['GOOGLE_APPLICATION_CREDENTIALS']="C:\/Users\/s1301\/Downloads\/corded-velocity-301807-b52c79741854.json"
- # 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 !!
- # 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": "\nTime: " + current_time + "\n" + msg}
- r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
- def run_report():
- client = BetaAnalyticsDataClient()
- message = ""
- dailypvtotal = {}
- dailypvtotal[(datetime.now() - timedelta(days=1)).strftime('%Y%m%d')]=0
- dailypvtotal[datetime.now().strftime('%Y%m%d')]=0
- for p in property_id:
- message = message + p[1] + "\n"
- request = RunReportRequest(
- property=f"properties/{p[0]}",
- dimensions=[Dimension(name="date")],
- metrics=[Metric(name="screenPageViews")],
- date_ranges=[DateRange(start_date="yesterday", end_date="today")],
- )
- response = client.run_report(request)
- for rowIdx, row in enumerate(response.rows):
- for i, metric_value in enumerate(row.metric_values):
- for i, dimension_value in enumerate(row.dimension_values):
- date=dimension_value.value
- viewcount = metric_value.value
- message = message + (f"{date}: {viewcount}\n")
- dailypvtotal[date]=dailypvtotal[date]+int(viewcount)
- message = message + '\n'
- for d,v in dailypvtotal.items():
- message = message + (f"{d} Total views: {v} ")
- if show_target == 1:
- if v >= pv_target:
- message = message + ("(Target reached)\n")
- else:
- message = message + ("(Target not reached)\n")
- else:
- message = message + '\n'
- print(message)
- if send == 1:
- send_msg(message)
- run_report()
|