GA_innnews.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. import pymysql
  21. pymysql.install_as_MySQLdb()
  22. from datetime import datetime
  23. import platform
  24. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  25. db.query('delete from ga_pagepath')
  26. db.begin()
  27. table=db['ga_pagepath']
  28. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  29. platform_now = platform.system().lower()
  30. if platform_now == 'linux':
  31. KEY_FILE_LOCATION = '/root/src/kw_tools/monitor/choozmo-ga-beee24b7a4c1.json' #'c:\\keys\\choozmo-ga-beee24b7a4c1.json'
  32. elif platform_now == 'windows':
  33. KEY_FILE_LOCATION = 'c:\gitlab\kw_tools\monitor\corded-velocity-301807-9262189e4dd5.json'
  34. else:
  35. KEY_FILE_LOCATION = '/Users/zooeytsai/Downloads/corded-velocity-301807-9262189e4dd5.json'
  36. VIEW_ID = '213054263'
  37. # line notify header
  38. headers = {
  39. "Authorization": "Bearer " + "zsaS4I79fkbun9LLF8mQmeHL4PlEtBtN7OLzTp8m72Y",
  40. "Content-Type": "application/x-www-form-urlencoded"
  41. }
  42. com_table = []
  43. def creat_table():
  44. for i in range(0,24):
  45. com_table.append([i,6000])
  46. # com_table.append([24,70000])
  47. print(com_table)
  48. def send_msg_pg(pv):
  49. # line notify send message
  50. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #現在時間
  51. hour = datetime.now().strftime('%H')
  52. # 判斷是否達標
  53. complet="否"
  54. # for i in range(0,25):
  55. # if int(hour)+1==com_table[i][0]:
  56. # print(i)
  57. # if int(kw) > com_table[i][1] :
  58. # complet="是"
  59. # elif int(hour) == 24:
  60. # if int(kw) > 70000 :
  61. # complet="是"
  62. print('網頁瀏覽量',pv)
  63. if int(pv) > 6000:
  64. complet = "是"
  65. params = {"message": "\n現在時間: " + current_time + "\n當前pageViews: "+pv + "\n是否達標: " + complet}
  66. print(params)
  67. return params
  68. # r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  69. # print(r.text)
  70. def initialize_analyticsreporting():
  71. """Initializes an Analytics Reporting API V4 service object.
  72. Returns:
  73. An authorized Analytics Reporting API V4 service object.
  74. """
  75. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  76. KEY_FILE_LOCATION, SCOPES)
  77. # Build the service object.
  78. analytics = build('analyticsreporting', 'v4', credentials=credentials)
  79. return analytics
  80. def get_report(analytics,body):
  81. """Queries the Analytics Reporting API V4.
  82. Args:
  83. analytics: An authorized Analytics Reporting API V4 service object.
  84. Returns:
  85. The Analytics Reporting API V4 response.
  86. """
  87. return analytics.reports().batchGet(
  88. body={
  89. 'reportRequests':body
  90. }
  91. ).execute()
  92. def print_response(response):
  93. """Parses and prints the Analytics Reporting API V4 response.
  94. Args:
  95. response: An Analytics Reporting API V4 response.
  96. """
  97. result=[]
  98. for report in response.get('reports', []):
  99. columnHeader = report.get('columnHeader', {})
  100. dimensionHeaders = columnHeader.get('dimensions', [])
  101. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  102. for row in report.get('data', {}).get('rows', []):
  103. dimensions = row.get('dimensions', [])
  104. dateRangeValues = row.get('metrics', [])
  105. ga_dict={}
  106. for header, dimension in zip(dimensionHeaders, dimensions):
  107. # print(header + ': ', dimension)
  108. ga_dict[header]=dimension
  109. for i, values in enumerate(dateRangeValues):
  110. # print('Date range:', str(i))
  111. for metricHeader, value in zip(metricHeaders, values.get('values')):
  112. ga_dict[metricHeader.get('name')]=value
  113. # print(metricHeader.get('name') + ':', value)
  114. result.append(ga_dict)
  115. return result
  116. # print(ga_dict)
  117. def main():
  118. creat_table()
  119. analytics = initialize_analyticsreporting()
  120. #(FB_|facebook|IG_|LINE_|LINEMP_|qsear.ch)
  121. current_time = datetime.now().strftime('%Y-%m-%d') #現在時間
  122. body=[{ 'viewId': VIEW_ID,
  123. 'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
  124. 'metrics': [{'expression': 'ga:users'},{'expression': 'ga:newusers'},{'expression': 'ga:sessions'},{'expression': 'ga:pageviews'},{'expression': 'ga:bounceRate'},{'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(elmt['ga:pageviews'])
  137. # result.append(elmt)
  138. print('inserting.....')
  139. return message
  140. if __name__ == '__main__':
  141. creat_table()
  142. main()