LoginSignup
0
1

More than 3 years have passed since last update.

【Python】SlackbotでGoogle Analyticsのデータを取得する

Last updated at Posted at 2019-07-18

本記事は、SlackbotでGoogle AnalyticsのデータをPythonで取得する方法について説明する記事です。

SlackbotをGoogle Analyticsのデータを取得するにはGoogle APIに登録する必要があるのでやや面倒ですが、よく使う数字や期間をBotに登録しておけばいつでもワンタッチでアクセス数を確認できるようになります。

PythonでのSlackbotの基本的な実装方法は「SlackbotをPythonで作成しよう」をお読みください。

PythonでGoogle APIを取得する基本的な手順については「Google Analyticsの情報をPythonで取得する」をお読みください。

Google Analyticsのデータを取得方法

Google Analyticsからのデータはオブジェクトで取得できます。

データの内容や使い方は「公式ドキュメントのレポート作成ページ」にて説明されています。

データの取得はreports().batchGet()メソッドで行います。
取得するデータは以下のようなフォーマットで指定します。


analytics.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': self.VIEW_ID,
                # 期間を指定する
                'dateRanges': [{'startDate': '開始日', 'endDate': '終了日'}],
                'metrics': [
                    # ページビュー数を取得する
                    {'expression': 'ga:pageviews'},
                    # セッション数を取得する
                    {'expression': 'ga:sessions'}
                ],
            }]
    }
).execute()

「dateRanges」の「startDate」で「endDate」で開始日と終了日を指定できます。
「metrics」に取得したいデータを指定します。

実装方法
・Pythonの情報を取得する処理



from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from slackbot.bot import respond_to

# Analyticsデータの取得クラス
class HelloAnalytics:

    def __init__(self, scopes, key_file_location, view_id):
        self.SCOPES = scopes
        self.KEY_FILE_LOCATION = key_file_location
        self.VIEW_ID = view_id
        self.startDate = '7daysAgo'
        self.endDate = 'today'

    # レポートの初期化
    def initialize_analyticsreporting(self):
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            self.KEY_FILE_LOCATION, self.SCOPES)

        # Build the service object.
        analytics = build('analyticsreporting', 'v4', credentials=credentials)

        return analytics

    # レポートを取得する
    def get_report(self, analytics):
        return analytics.reports().batchGet(
            body={
                'reportRequests': [
                    {
                        'viewId': self.VIEW_ID,
                        'dateRanges': [{'startDate': self.startDate, 'endDate': self.endDate}],
                        'metrics': [
                            {'expression': 'ga:pageviews'},
                            {'expression': 'ga:sessions'}
                        ],
                        # 'dimensions': [{"name": "ga:pageTitle"}]
                    }]
            }
        ).execute()

    # アクセスの取得処理
    def report_access(self, response):
        reports = []
        # データを取得してレポートに格納する
        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', [])

                for header, dimension in zip(dimensionHeaders, dimensions):
                    reports.append(header + ': ' + dimension)

                for i, values in enumerate(dateRangeValues):
                    reports.append('Date range: ' + str(i))
                    for metricHeader, value in zip(metricHeaders, values.get('values')):
                        reports.append(metricHeader.get('name') + ': ' + value)
        return reports

# Botの応答
@respond_to('^アクセスチェック$')
def access_check(message):
    # パラメータを設定
    SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
    KEY_FILE_LOCATION = 'client_secrets.json'
    # view idを指定する
    VIEW_ID = 'xxxxxxx' 
    
    # インスタンスを生成
    hello_analytics = HelloAnalytics(SCOPES, KEY_FILE_LOCATION, VIEW_ID)
    hello_analytics.startDate = '2018-10-01'
    # 初期化
    analytics = hello_analytics.initialize_analyticsreporting()
    # データを取得
    response = hello_analytics.get_report(analytics)
    # レポートを作成
    reports = hello_analytics.report_access(response)
    message.send('\n'.join(reports))

◆実行例
analyticsデータの取得例

以上、SlackbotでGoogle Analyticsのデータを取得する方法でした。

◆ブログ:miyabino.py(みやびのどっとぴーわい)関連記事

SlackbotをPythonで作成しよう
SlackbotでTodoistの予定を確認する
Google Analyticsの情報をPythonで取得する

Slackbot+PythonまとめTOP>>Slackbotの構築マニュアル〜Python編〜

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1