GA_innnews.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. property_id= 'properties/375530887'
  29. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  30. platform_now = platform.system().lower()
  31. KEY_FILE_LOCATION = "C:\/Users\/s1301\/Downloads\/corded-velocity-301807-9262189e4dd5.json"
  32. VIEW_ID = '213054263'
  33. # line notify header
  34. headers = {
  35. "Authorization": "Bearer " + "zsaS4I79fkbun9LLF8mQmeHL4PlEtBtN7OLzTp8m72Y",
  36. "Content-Type": "application/x-www-form-urlencoded"
  37. }
  38. com_table = []
  39. def creat_table():
  40. for i in range(0,24):
  41. com_table.append([i,6000])
  42. # com_table.append([24,70000])
  43. print(com_table)
  44. def send_msg_pg(pv):
  45. # line notify send message
  46. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #現在時間
  47. hour = datetime.now().strftime('%H')
  48. # 判斷是否達標
  49. complet="否"
  50. # for i in range(0,25):
  51. # if int(hour)+1==com_table[i][0]:
  52. # print(i)
  53. # if int(kw) > com_table[i][1] :
  54. # complet="是"
  55. # elif int(hour) == 24:
  56. # if int(kw) > 70000 :
  57. # complet="是"
  58. print('網頁瀏覽量',pv)
  59. if int(pv) > 6000:
  60. complet = "是"
  61. params = {"message": "\n現在時間: " + current_time + "\n當前pageViews: "+pv + "\n是否達標: " + complet}
  62. print(params)
  63. return params
  64. # r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  65. # print(r.text)
  66. def initialize_analyticsreporting():
  67. """Initializes an Analytics Reporting API V4 service object.
  68. Returns:
  69. An authorized Analytics Reporting API V4 service object.
  70. """
  71. credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
  72. # Build the service object.
  73. analytics = build('analyticsdata', 'v1beta', credentials=credentials)
  74. return analytics
  75. def get_report(analytics,body):
  76. """Queries the Analytics Reporting API V4.
  77. Args:
  78. analytics: An authorized Analytics Reporting API V4 service object.
  79. Returns:
  80. The Analytics Reporting API V4 response.
  81. """
  82. response = analytics.properties().batchRunReports(property=property_id, body=body).execute()
  83. print(response)
  84. report_data = response.get('reports')
  85. pv = report_data[0].get('rows')[0].get('metricValues')[0].get('value')
  86. return pv
  87. def print_response(response):
  88. """Parses and prints the Analytics Reporting API V4 response.
  89. Args:
  90. response: An Analytics Reporting API V4 response.
  91. """
  92. result=[]
  93. for report in response.get('reports', []):
  94. columnHeader = report.get('columnHeader', {})
  95. dimensionHeaders = columnHeader.get('dimensions', [])
  96. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  97. for row in report.get('data', {}).get('rows', []):
  98. dimensions = row.get('dimensions', [])
  99. dateRangeValues = row.get('metrics', [])
  100. ga_dict={}
  101. for header, dimension in zip(dimensionHeaders, dimensions):
  102. # print(header + ': ', dimension)
  103. ga_dict[header]=dimension
  104. for i, values in enumerate(dateRangeValues):
  105. # print('Date range:', str(i))
  106. for metricHeader, value in zip(metricHeaders, values.get('values')):
  107. ga_dict[metricHeader.get('name')]=value
  108. # print(metricHeader.get('name') + ':', value)
  109. result.append(ga_dict)
  110. return result
  111. # print(ga_dict)
  112. def main():
  113. # creat_table()
  114. analytics = initialize_analyticsreporting()
  115. print(analytics)
  116. #(FB_|facebook|IG_|LINE_|LINEMP_|qsear.ch)
  117. current_time = datetime.now().strftime('%Y-%m-%d') #現在時間
  118. body={
  119. "requests": [
  120. {
  121. "dateRanges": [
  122. {
  123. "startDate": "2023-08-08",
  124. "endDate": "2023-08-08"
  125. }
  126. ],
  127. "metrics": [
  128. {
  129. "name": "screenPageViews"
  130. }
  131. ],
  132. "limit": "100"
  133. }
  134. ]
  135. }
  136. response = get_report(analytics,body)
  137. print(response)
  138. # ga_dict=print_response(response)
  139. # for elmt in ga_dict:
  140. # print(elmt)
  141. # hour = datetime.now().strftime('%H')
  142. # if int(hour)+1 > 8 :
  143. # message = send_msg_pg(elmt['ga:pageviews'])
  144. # return message
  145. if __name__ == '__main__':
  146. # creat_table()
  147. main()