GA_organic.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. table=db['ga_pagepath']
  25. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  26. #KEY_FILE_LOCATION = '/root/src/kw_tools/monitor/choozmo-ga-beee24b7a4c1.json' #'c:\\keys\\choozmo-ga-beee24b7a4c1.json'
  27. KEY_FILE_LOCATION = 'c:\\keys\\choozmo-ga-beee24b7a4c1.json' #'c:\\keys\\choozmo-ga-beee24b7a4c1.json'
  28. VIEW_ID = '188916214'
  29. # line notify header
  30. headers = {
  31. "Authorization": "Bearer " + "WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD",
  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,2920*i])
  38. com_table.append([24,70000])
  39. print(com_table)
  40. def send_msg(kw):
  41. # line notify send message
  42. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #現在時間
  43. hour = datetime.now().strftime('%H')
  44. # 判斷是否達標
  45. complet="否"
  46. for i in range(0,25):
  47. if int(hour)+1==com_table[i][0]:
  48. print(i)
  49. if int(kw) > com_table[i][1] :
  50. complet="是"
  51. elif int(hour) == 24:
  52. if int(kw) > 70000 :
  53. complet="是"
  54. params = {"message": "\n現在時間: " + current_time + "\n當前pageViews: "+kw + "\n是否達標: " + complet}
  55. print(params)
  56. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  57. print(r.text)
  58. def initialize_analyticsreporting():
  59. """Initializes an Analytics Reporting API V4 service object.
  60. Returns:
  61. An authorized Analytics Reporting API V4 service object.
  62. """
  63. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  64. KEY_FILE_LOCATION, SCOPES)
  65. # Build the service object.
  66. analytics = build('analyticsreporting', 'v4', credentials=credentials)
  67. return analytics
  68. def get_report(analytics,body):
  69. """Queries the Analytics Reporting API V4.
  70. Args:
  71. analytics: An authorized Analytics Reporting API V4 service object.
  72. Returns:
  73. The Analytics Reporting API V4 response.
  74. """
  75. return analytics.reports().batchGet(
  76. body={
  77. 'reportRequests':body
  78. }
  79. ).execute()
  80. def print_response(response):
  81. """Parses and prints the Analytics Reporting API V4 response.
  82. Args:
  83. response: An Analytics Reporting API V4 response.
  84. """
  85. result=[]
  86. for report in response.get('reports', []):
  87. columnHeader = report.get('columnHeader', {})
  88. dimensionHeaders = columnHeader.get('dimensions', [])
  89. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  90. for row in report.get('data', {}).get('rows', []):
  91. dimensions = row.get('dimensions', [])
  92. dateRangeValues = row.get('metrics', [])
  93. ga_dict={}
  94. for header, dimension in zip(dimensionHeaders, dimensions):
  95. # print(header + ': ', dimension)
  96. ga_dict[header]=dimension
  97. for i, values in enumerate(dateRangeValues):
  98. # print('Date range:', str(i))
  99. for metricHeader, value in zip(metricHeaders, values.get('values')):
  100. ga_dict[metricHeader.get('name')]=value
  101. # print(metricHeader.get('name') + ':', value)
  102. result.append(ga_dict)
  103. return result
  104. # print(ga_dict)
  105. def main():
  106. analytics = initialize_analyticsreporting()
  107. #(FB_|facebook|IG_|LINE_|LINEMP_|qsear.ch)
  108. current_time = datetime.now().strftime('%Y-%m-%d') #現在時間
  109. body=[{ 'viewId': VIEW_ID,
  110. 'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
  111. 'metrics': [{'expression': 'ga:sessions'},{'expression': 'ga:pageviews'}],
  112. 'dimensions': [{'name': 'ga:sourceMedium'}],
  113. # 'orderBys':[{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],
  114. 'pageSize': '100'
  115. }]
  116. response = get_report(analytics,body)
  117. ga_dict=print_response(response)
  118. result=[]
  119. for elmt in ga_dict:
  120. hour = datetime.now().strftime('%H')
  121. if 'google' in elmt['ga:sourceMedium'] and 'organic' in elmt['ga:sourceMedium']:
  122. print(elmt)
  123. # if int(hour)+1 > 8 :
  124. # send_msg(elmt['ga:pageviews'])
  125. # print('inserting.....')
  126. if __name__ == '__main__':
  127. # creat_table()
  128. main()