zooeytsai %!s(int64=2) %!d(string=hai) anos
pai
achega
93b551d05f
Modificáronse 2 ficheiros con 216 adicións e 0 borrados
  1. 164 0
      monitor/GA_all.py
  2. 52 0
      monitor/notifyall.py

+ 164 - 0
monitor/GA_all.py

@@ -0,0 +1,164 @@
+#!/usr/bin/python3
+import sys
+import codecs
+import traceback
+import requests
+import re
+import pandas as pd
+import random
+import urllib
+import json
+import gspread
+import datetime
+from gspread_pandas import Spread, Client
+from oauth2client.service_account import ServiceAccountCredentials
+import os
+import threading
+from googleapiclient.discovery import build
+from oauth2client.service_account import ServiceAccountCredentials
+import dataset
+import pymysql
+pymysql.install_as_MySQLdb()
+from datetime import datetime
+import platform
+
+db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
+db.query('delete from ga_pagepath')
+db.begin()
+
+table=db['ga_pagepath']
+SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
+platform_now = platform.system().lower()
+
+# KEY_FILE_LOCATION = 'c:\gitlab\kw_tools\monitor\corded-velocity-301807-a3e3d5420aba.json'
+KEY_FILE_LOCATION = '/Users/zooeytsai/Downloads/corded-velocity-301807-a3e3d5420aba.json'
+
+
+# line notify header
+headers = {
+        "Authorization": "Bearer " + "QCAM5upFjeBVp54PGqT4eMZSXPU0y4vYk1e1CoASa2P",
+        "Content-Type": "application/x-www-form-urlencoded"
+}
+
+com_table = []
+def creat_table():
+  for i in range(0,24):
+    com_table.append([i,6000])
+  # com_table.append([24,70000])
+
+
+def send_msg_pg(pv):
+  # line notify send message
+    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #現在時間
+    hour = datetime.now().strftime('%H') 
+    # 判斷是否達標
+    complet="否"
+    # for i in range(0,25):
+    #   if int(hour)+1==com_table[i][0]:
+    #     print(i)
+    #     if int(kw) > com_table[i][1] :
+    #       complet="是"
+    #   elif int(hour) == 24:
+    #     if int(kw) > 70000 :
+    #       complet="是"
+    print('網頁瀏覽量',pv)
+    if int(pv) > 6000:
+      complet = "是"
+    params = {"message": "\n現在時間: " + current_time + "\n當前pageViews: "+pv + "\n是否達標: " + complet}
+    print(params)
+    return params
+    r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
+    print(r)
+
+
+def initialize_analyticsreporting(key_file):
+  """Initializes an Analytics Reporting API V4 service object.
+
+  Returns:
+    An authorized Analytics Reporting API V4 service object.
+  """
+  credentials = ServiceAccountCredentials.from_json_keyfile_name(
+      key_file, SCOPES)
+
+  # Build the service object.
+  analytics = build('analyticsreporting', 'v4', credentials=credentials)
+
+  return analytics
+
+
+def get_report(analytics,body):
+  """Queries the Analytics Reporting API V4.
+
+  Args:
+    analytics: An authorized Analytics Reporting API V4 service object.
+  Returns:
+    The Analytics Reporting API V4 response.
+  """
+  return analytics.reports().batchGet(
+      body={
+        'reportRequests':body
+      }
+  ).execute()
+
+
+def print_response(response):
+  """Parses and prints the Analytics Reporting API V4 response.
+
+  Args:
+    response: An Analytics Reporting API V4 response.
+  """
+  result=[]
+  for report in response.get('reports', []):
+    columnHeader = report.get('columnHeader', {})
+    dimensionHeaders = columnHeader.get('dimensions', [])
+    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
+
+    for row in report.get('data', {}).get('rows', []):
+      dimensions = row.get('dimensions', [])
+      dateRangeValues = row.get('metrics', [])
+      ga_dict={}
+
+      for header, dimension in zip(dimensionHeaders, dimensions):
+#        print(header + ': ', dimension)
+        ga_dict[header]=dimension
+      
+      for i, values in enumerate(dateRangeValues):
+#        print('Date range:', str(i))
+        for metricHeader, value in zip(metricHeaders, values.get('values')):
+          ga_dict[metricHeader.get('name')]=value
+#          print(metricHeader.get('name') + ':', value)
+        result.append(ga_dict)
+    return result
+#        print(ga_dict)
+
+
+def main(viewid,key_file):
+  creat_table()
+  analytics = initialize_analyticsreporting(key_file)
+  current_time = datetime.now().strftime('%Y-%m-%d') #現在時間
+  body=[{ 'viewId': viewid,
+  'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
+
+  'metrics': [{'expression': 'ga:users'},{'expression': 'ga:newusers'},{'expression': 'ga:sessions'},{'expression': 'ga:pageviews'},{'expression': 'ga:bounceRate'},{'expression': 'ga:pageviewsPerSession'}],
+#  'dimensions': [{'name': 'ga:pagePath'}],
+#  'orderBys':[{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],
+  'pageSize': '100'
+  }]
+
+  response = get_report(analytics,body)
+  ga_dict=print_response(response)
+
+  result=[]
+  for elmt in ga_dict:
+    print(elmt)
+    hour = datetime.now().strftime('%H')
+    # if int(hour)+1 > 8 :
+    message = send_msg_pg(elmt['ga:pageviews'])
+#      result.append(elmt)
+  print('inserting.....')
+  return message
+
+
+if __name__ == '__main__':
+  creat_table()
+  main('123')

+ 52 - 0
monitor/notifyall.py

@@ -0,0 +1,52 @@
+import redis
+import time
+import json
+from selenium import webdriver
+from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
+import time
+import os
+import urllib.parse
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+import codecs
+import random
+from bs4 import BeautifulSoup
+import requests
+import dataset
+import time
+import rpyc
+import sys
+import docker
+import pymysql
+pymysql.install_as_MySQLdb()
+from monitor import GA_all
+
+
+ga_info = {'班尼斯':['154114800',{
+        "Authorization": "Bearer " + "QCAM5upFjeBVp54PGqT4eMZSXPU0y4vYk1e1CoASa2P",
+        "Content-Type": "application/x-www-form-urlencoded"
+},'/Users/zooeytsai/Downloads/corded-velocity-301807-a3e3d5420aba.json'
+],'有夠讚':['208868237',{
+        "Authorization": "Bearer " + "Alur8iUgifYsh9CMiyUdlrTWK4Y9Xys8RZD52YkBMGl",
+        "Content-Type": "application/x-www-form-urlencoded"
+},'/Users/zooeytsai/Downloads/corded-velocity-301807-a0d690cd59d9.json'],
+          '神助物流':['265874206',{
+        "Authorization": "Bearer " + "50Qu8O3XUhOhIOkz5WHy6mhftRVBe8CtL3DXS05UXRC",
+        "Content-Type": "application/x-www-form-urlencoded"},'/Users/zooeytsai/Downloads/corded-velocity-301807-42d10dfc21a4.json']}
+
+def send_msg(viewid,header,key_file):
+    send_message = GA_all.main(viewid, key_file)
+    params = {"message": send_message['message']}
+    print('通知結果',params)
+    r = requests.post("https://notify-api.line.me/api/notify",headers=header, params=params)
+
+
+for k,v in ga_info.items():
+    send_msg(v[0],v[1],v[2])
+
+
+# schtasks /create /sc minute /mo 30 /sd 2022/05/050 /st 9:00 /et 23:00 /tn "linebat" /tr "C:\tmp\inn_line.bat"
+
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+sys.path.append(os.path.dirname(SCRIPT_DIR))