ソースを参照

seo_notify新增GA sessions

zooeytsai 2 年 前
コミット
e662c98994
2 ファイル変更123 行追加4 行削除
  1. 8 4
      SEO/seo_notify.py
  2. 115 0
      monitor/ga_click.py

+ 8 - 4
SEO/seo_notify.py

@@ -20,7 +20,7 @@ import sys
 import docker
 import pymysql
 pymysql.install_as_MySQLdb()
-from monitor import GA_innnews
+from monitor.ga_click import main
 
 headers = {
     "Authorization": "Bearer " + "OZDcq7sVKwr3F6YNLtBF3LuIgpa4Ql9eAnBWeD7sHTJ",
@@ -32,19 +32,21 @@ name = {'beastparadise.net':'毛怪','taroboba-yuan.com':'清原','match-planet.
 def send_msg(kw):
     params = {"message": kw}
     print('通知結果', params)
-    # r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
+    r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
 
 
 db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
 cursor = db.query(
     'SELECT * FROM seo.general_log where domain != "innews.com.tw" and datediff(now(),dt)=0 order by dt desc')
+cursor_rank = db.query(
+    'SELECT * FROM seo.google_rank where datediff(now(),dt)=0 order by dt desc')
 result = "\n"
 idx = 0
 d = {'beastparadise.net':0,'match-planet.com':0,'taroboba-yuan.com':0,'hhh.com.tw':0,'sctt.com.tw':0,'hhh.com.tw/designer':0}
 for c in cursor:
     custom_name = c['domain']
     if custom_name in d:
-        if custom_name == 'hhh.com.tw' and c['num']=='s':
+        if custom_name == 'hhh.com.tw' and c['num']==1:
             d['hhh.com.tw/designer']+=1
         d[custom_name]+=1
     idx += 1
@@ -58,7 +60,9 @@ per_total_click = f"毛怪:{d['beastparadise.net']}\n清原:{d['taroboba-yuan.co
 print(per_total_click)
 msg_per_total_click = '\n點擊次數總計:\n' + per_total_click
 msg = "\n機器人執行次數:" + str(idx)
-send_msg(msg_per_total_click + result)
+ga_sessions = '\n幸福空間的GA Sessions'+main()['ga:sessions']
+send_msg(msg_per_total_click + result + ga_sessions)
+
 
 
 # schtasks /create /sc minute /mo 30 /sd 2022/05/050 /st 9:00 /et 23:00 /tn "linebat" /tr "C:\tmp\inn_line.bat"

+ 115 - 0
monitor/ga_click.py

@@ -0,0 +1,115 @@
+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
+
+SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
+KEY_FILE_LOCATION_bennis = '/Users/zooeytsai/Downloads/corded-velocity-301807-a3e3d5420aba.json'
+KEY_FILE_LOCATION_inn = '/Users/zooeytsai/Downloads/corded-velocity-301807-9262189e4dd5.json'
+KEY_FILE_LOCATION_hhh = '/Users/zooeytsai/Downloads/choozmo-ga-58715a47b676.json'
+VIEW_ID_inn = '213054263'
+VIEW_ID_hhh = '188916214'
+
+def initialize_analyticsreporting():
+    """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_LOCATION_hhh, 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
+
+
+def main():
+    analytics = initialize_analyticsreporting()
+    current_time = datetime.now().strftime('%Y-%m-%d')
+    body = [{ 'viewId': VIEW_ID_hhh,
+      'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
+    
+      'metrics': [{'expression': 'ga:sessions'},{'expression': 'ga:pageviews'}],
+      'dimensions': [{'name': 'ga:sourceMedium'}],
+    #  'orderBys':[{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],
+      'pageSize': '100'
+      }]
+
+    response = get_report(analytics, body)
+    ga_dict = print_response(response)
+    result = None
+    for elmt in ga_dict:
+        hour = datetime.now().strftime('%H')
+        if 'google' in elmt['ga:sourceMedium'] and 'organic' in elmt['ga:sourceMedium']:
+            print(elmt)
+            result = elmt
+    return result
+
+
+if __name__ == '__main__':
+  main()