GA4LN_icons.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from datetime import datetime
  2. import os
  3. import requests
  4. from google.analytics.data_v1beta import BetaAnalyticsDataClient
  5. from google.analytics.data_v1beta.types import (
  6. DateRange,
  7. Dimension,
  8. Metric,
  9. MetricType,
  10. RunReportRequest,
  11. )
  12. # IMPORTANT: Please set up GOOGLE_APPLICATION_CREDENTIALS through export (Bash) OR Environment Variables (Windows).
  13. # GOOGLE_APPLICATION_CREDENTIALS = "[path to credentials.json file]"
  14. # Insert PROPERTY IDs you want to track here.
  15. # Format: ["property_ID","property_name"]
  16. # KEEP THIS IN TUPLE FORM EVEN IF ONLY ONE DATA SOURCE IS USED !!
  17. os.environ['GOOGLE_APPLICATION_CREDENTIALS']="C:\/Users\/s1301\/Downloads\/corded-velocity-301807-b52c79741854.json"
  18. # property_id = [["336444388","Icons_EN"],["336427321","Icons_ZH"]] # CHANGE HERE
  19. property_id = [["336444388","Icons_EN"]] # CHANGE HERE
  20. # Insert PageView target here.
  21. pv_target = 800
  22. # Show whether target is achieved or not. Set to 1 to enable.
  23. show_target = 0
  24. # Enable/disable send to LINE Notify. Set to 1 to enable.
  25. send = 1
  26. # Insert destination LINE Group ID here.
  27. LINE_GROUP_ID = 'zRyvl5OGuQZWpZqRmRsBT23qZ4ID9Ev6I7Jbz2gtpRU'
  28. # LINE Notify Header
  29. headers = {
  30. "Authorization": "Bearer " + LINE_GROUP_ID,
  31. "Content-Type": "application/x-www-form-urlencoded"
  32. }
  33. def send_msg(msg):
  34. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  35. params = {"message": "Time: " + current_time + "\n" + msg}
  36. # r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  37. def run_report():
  38. client = BetaAnalyticsDataClient()
  39. total = 0
  40. message = ""
  41. for p in property_id:
  42. request = RunReportRequest(
  43. property=f"properties/{p[0]}",
  44. metrics=[Metric(name="screenPageViews")],
  45. date_ranges=[DateRange(start_date="today", end_date="today")],
  46. )
  47. response = client.run_report(request)
  48. for rowIdx, row in enumerate(response.rows):
  49. for i, metric_value in enumerate(row.metric_values):
  50. metric_name = response.metric_headers[i].name
  51. viewcount = metric_value.value
  52. message = message + (f"{p[1]} / {metric_name}: {viewcount}\n")
  53. total = total + int(viewcount)
  54. message = message + (f"Total views: {total}\n")
  55. if show_target == 1:
  56. if total >= pv_target:
  57. message = message + ("Target reached\n")
  58. else:
  59. message = message + ("Target not reached\n")
  60. print(message)
  61. if send == 1:
  62. send_msg(message)
  63. run_report()