ga_daily_test.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/python3
  2. import sys
  3. import codecs
  4. import traceback
  5. import requests
  6. import re
  7. import pandas as pd
  8. import random
  9. import urllib
  10. import json
  11. import gspread
  12. import datetime
  13. from gspread_pandas import Spread, Client
  14. from oauth2client.service_account import ServiceAccountCredentials
  15. import os
  16. import threading
  17. from googleapiclient.discovery import build
  18. from oauth2client.service_account import ServiceAccountCredentials
  19. import dataset
  20. from datetime import datetime
  21. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  22. db.query('delete from ga_pagepath')
  23. db.begin()
  24. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  25. KEY_FILE_LOCATION = '/root/src/kw_tools/monitor/choozmo-ga-beee24b7a4c1.json' #'c:\\keys\\choozmo-ga-beee24b7a4c1.json'
  26. VIEW_ID = '188916214'
  27. # line notify header
  28. headers = {
  29. "Authorization": "Bearer " + "WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD",
  30. "Content-Type": "application/x-www-form-urlencoded"
  31. }
  32. com_table = []
  33. def send_msg(kw):
  34. # line notify send message
  35. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #現在時間
  36. hour = datetime.now().strftime('%H')
  37. # 判斷是否達標
  38. complet="否"
  39. for i in range(0,25):
  40. if int(hour)+1==com_table[i][0]:
  41. print(i)
  42. if int(kw) > com_table[i][1] :
  43. complet="是"
  44. elif int(hour) == 24:
  45. if int(kw) > 70000 :
  46. complet="是"
  47. params = {"message": "\n現在時間: " + current_time + "\n當前pageViews: "+kw + "\n是否達標: " + complet}
  48. print(params)
  49. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  50. print(r.text)
  51. def initialize_analyticsreporting():
  52. """Initializes an Analytics Reporting API V4 service object.
  53. Returns:
  54. An authorized Analytics Reporting API V4 service object.
  55. """
  56. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  57. KEY_FILE_LOCATION, SCOPES)
  58. # Build the service object.
  59. analytics = build('analyticsreporting', 'v4', credentials=credentials)
  60. return analytics
  61. def get_report(analytics,body):
  62. """Queries the Analytics Reporting API V4.
  63. Args:
  64. analytics: An authorized Analytics Reporting API V4 service object.
  65. Returns:
  66. The Analytics Reporting API V4 response.
  67. """
  68. return analytics.reports().batchGet(
  69. body={
  70. 'reportRequests':body
  71. }
  72. ).execute()
  73. def print_response(response):
  74. """Parses and prints the Analytics Reporting API V4 response.
  75. Args:
  76. response: An Analytics Reporting API V4 response.
  77. """
  78. result=[]
  79. for report in response.get('reports', []):
  80. columnHeader = report.get('columnHeader', {})
  81. dimensionHeaders = columnHeader.get('dimensions', [])
  82. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  83. for row in report.get('data', {}).get('rows', []):
  84. dimensions = row.get('dimensions', [])
  85. dateRangeValues = row.get('metrics', [])
  86. ga_dict={}
  87. for header, dimension in zip(dimensionHeaders, dimensions):
  88. # print(header + ': ', dimension)
  89. ga_dict[header]=dimension
  90. for i, values in enumerate(dateRangeValues):
  91. # print('Date range:', str(i))
  92. for metricHeader, value in zip(metricHeaders, values.get('values')):
  93. ga_dict[metricHeader.get('name')]=value
  94. # print(metricHeader.get('name') + ':', value)
  95. result.append(ga_dict)
  96. return result
  97. # print(ga_dict)
  98. def main():
  99. analytics = initialize_analyticsreporting()
  100. #(FB_|facebook|IG_|LINE_|LINEMP_|qsear.ch)
  101. current_time = datetime.now().strftime('%Y-%m-%d') #現在時間
  102. body=[{ 'viewId': VIEW_ID,
  103. 'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
  104. 'metrics': [{'expression': 'ga:users'},{'expression': 'ga:newusers'},{'expression': 'ga:sessions'},{'expression': 'ga:pageviews'},{'expression': 'ga:bounceRate'},{'expression': 'ga:pageviewsPerSession'}],
  105. # 'dimensions': [{'name': 'ga:pagePath'}],
  106. # 'orderBys':[{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],
  107. 'pageSize': '100'
  108. }]
  109. response = get_report(analytics,body)
  110. ga_dict=print_response(response)
  111. result=[]
  112. for elmt in ga_dict:
  113. print(elmt)
  114. hour = datetime.now().strftime('%H')
  115. if int(hour)+1 > 8 :
  116. send_msg(elmt['ga:pageviews'])
  117. print('inserting.....')
  118. if __name__ == '__main__':
  119. # creat_table()
  120. main()