GA_all.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 datetime
  12. import os
  13. import threading
  14. from googleapiclient.discovery import build
  15. from oauth2client.service_account import ServiceAccountCredentials
  16. import dataset
  17. import pymysql
  18. pymysql.install_as_MySQLdb()
  19. from datetime import datetime
  20. import platform
  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. table = db['ga_pagepath']
  25. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  26. platform_now = platform.system().lower()
  27. # KEY_FILE_LOCATION = 'c:\gitlab\kw_tools\monitor\corded-velocity-301807-a3e3d5420aba.json'
  28. KEY_FILE_LOCATION = '/Users/zooeytsai/Downloads/corded-velocity-301807-a3e3d5420aba.json'
  29. # line notify header
  30. headers = {
  31. "Authorization": "Bearer " + "QCAM5upFjeBVp54PGqT4eMZSXPU0y4vYk1e1CoASa2P",
  32. "Content-Type": "application/x-www-form-urlencoded"
  33. }
  34. com_table = []
  35. def creat_table():
  36. for i in range(0, 24):
  37. com_table.append([i, 6000])
  38. # com_table.append([24,70000])
  39. def send_msg_pg(viewid, pv):
  40. # line notify send message
  41. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 現在時間
  42. hour = datetime.now().strftime('%H')
  43. # 判斷是否達標
  44. complet = "否"
  45. # for i in range(0,25):
  46. # if int(hour)+1==com_table[i][0]:
  47. # print(i)
  48. # if int(kw) > com_table[i][1] :
  49. # complet="是"
  50. # elif int(hour) == 24:
  51. # if int(kw) > 70000 :
  52. # complet="是"
  53. print('網頁瀏覽量', pv)
  54. if viewid == '208868237':
  55. if int(pv) > 2000:
  56. complet = "是"
  57. else:
  58. complet = '否'
  59. else:
  60. if int(pv) > 2300:
  61. complet = "是"
  62. else:
  63. complet = "否"
  64. params = {"message": "\n現在時間: " + current_time + "\n當前pageViews: " + pv + "\n是否達標: " + complet}
  65. print(params)
  66. return params
  67. r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=params)
  68. print(r)
  69. def initialize_analyticsreporting(key_file):
  70. """Initializes an Analytics Reporting API V4 service object.
  71. Returns:
  72. An authorized Analytics Reporting API V4 service object.
  73. """
  74. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  75. key_file, SCOPES)
  76. # Build the service object.
  77. analytics = build('analyticsreporting', 'v4', credentials=credentials)
  78. return analytics
  79. def get_report(analytics, body):
  80. """Queries the Analytics Reporting API V4.
  81. Args:
  82. analytics: An authorized Analytics Reporting API V4 service object.
  83. Returns:
  84. The Analytics Reporting API V4 response.
  85. """
  86. return analytics.reports().batchGet(
  87. body={
  88. 'reportRequests': body
  89. }
  90. ).execute()
  91. def print_response(response):
  92. """Parses and prints the Analytics Reporting API V4 response.
  93. Args:
  94. response: An Analytics Reporting API V4 response.
  95. """
  96. result = []
  97. for report in response.get('reports', []):
  98. columnHeader = report.get('columnHeader', {})
  99. dimensionHeaders = columnHeader.get('dimensions', [])
  100. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  101. for row in report.get('data', {}).get('rows', []):
  102. dimensions = row.get('dimensions', [])
  103. dateRangeValues = row.get('metrics', [])
  104. ga_dict = {}
  105. for header, dimension in zip(dimensionHeaders, dimensions):
  106. # print(header + ': ', dimension)
  107. ga_dict[header] = dimension
  108. for i, values in enumerate(dateRangeValues):
  109. # print('Date range:', str(i))
  110. for metricHeader, value in zip(metricHeaders, values.get('values')):
  111. ga_dict[metricHeader.get('name')] = value
  112. # print(metricHeader.get('name') + ':', value)
  113. result.append(ga_dict)
  114. return result
  115. # print(ga_dict)
  116. def main(viewid, key_file):
  117. creat_table()
  118. analytics = initialize_analyticsreporting(key_file)
  119. current_time = datetime.now().strftime('%Y-%m-%d') # 現在時間
  120. body = [{'viewId': viewid,
  121. 'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
  122. 'metrics': [{'expression': 'ga:users'}, {'expression': 'ga:newusers'}, {'expression': 'ga:sessions'},
  123. {'expression': 'ga:pageviews'}, {'expression': 'ga:bounceRate'},
  124. {'expression': 'ga:pageviewsPerSession'}],
  125. # 'dimensions': [{'name': 'ga:pagePath'}],
  126. # 'orderBys':[{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],
  127. 'pageSize': '100'
  128. }]
  129. response = get_report(analytics, body)
  130. ga_dict = print_response(response)
  131. result = []
  132. for elmt in ga_dict:
  133. print(elmt)
  134. hour = datetime.now().strftime('%H')
  135. # if int(hour)+1 > 8 :
  136. message = send_msg_pg(viewid, elmt['ga:pageviews'])
  137. # result.append(elmt)
  138. print('inserting.....')
  139. return message
  140. if __name__ == '__main__':
  141. creat_table()
  142. main('123')