GA4LN_icons.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from datetime import datetime, timedelta
  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. os.environ['GOOGLE_APPLICATION_CREDENTIALS']="C:\/Users\/s1301\/Downloads\/corded-velocity-301807-b52c79741854.json"
  15. # Insert PROPERTY IDs you want to track here.
  16. # Format: ["property_ID","property_name"]
  17. # KEEP THIS IN TUPLE FORM EVEN IF ONLY ONE DATA SOURCE IS USED !!
  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": "\nTime: " + 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. message = ""
  40. dailypvtotal = {}
  41. dailypvtotal[(datetime.now() - timedelta(days=1)).strftime('%Y%m%d')]=0
  42. dailypvtotal[datetime.now().strftime('%Y%m%d')]=0
  43. for p in property_id:
  44. message = message + p[1] + "\n"
  45. request = RunReportRequest(
  46. property=f"properties/{p[0]}",
  47. dimensions=[Dimension(name="date")],
  48. metrics=[Metric(name="screenPageViews")],
  49. date_ranges=[DateRange(start_date="yesterday", end_date="today")],
  50. )
  51. response = client.run_report(request)
  52. for rowIdx, row in enumerate(response.rows):
  53. for i, metric_value in enumerate(row.metric_values):
  54. for i, dimension_value in enumerate(row.dimension_values):
  55. date=dimension_value.value
  56. viewcount = metric_value.value
  57. message = message + (f"{date}: {viewcount}\n")
  58. dailypvtotal[date]=dailypvtotal[date]+int(viewcount)
  59. message = message + '\n'
  60. for d,v in dailypvtotal.items():
  61. message = message + (f"{d} Total views: {v} ")
  62. if show_target == 1:
  63. if v >= pv_target:
  64. message = message + ("(Target reached)\n")
  65. else:
  66. message = message + ("(Target not reached)\n")
  67. else:
  68. message = message + '\n'
  69. print(message)
  70. if send == 1:
  71. send_msg(message)
  72. run_report()