見出し画像

PythonでGoogleアナリティクスAPIに接続して人気記事ランキングをツイートする

ブログ用Twitterアカウントを運用するにあたって、自分のブログの人気記事をランキング形式でツイートする機能を実装したかったので、そのメモを残します。

前提として、Googleアナリティクス用アカウントをすでに持っている、Pythonのインストールはすでに完了しているものとします。

実行環境
OS : MacOS Mojave
Python 3.6.3


目次

・アナリティクスAPIに登録
・Googleクライアント ライブラリをインストール
・キーjsonファイルをダウンロード
・サンプルコードのダウンロード
・サンプルコードをカスタマイズしてアクセスランキングを取得
・アクセスランキングをツイート


アナリティクスAPIに登録

はじめにアクセスデータを引っ張ってくるためにアナリティクスAPIに登録する必要があります。アナリティクスAPIを利用するために、Google APIでプロジェクトの作成、APIの有効化...と言った作業が必要です。公式ドキュメントにわかりやすく記載されているので、こちらを参照していただければと思います。


Google クライアント ライブラリをインストール

PythonからアナリティクスAPIを利用するために、いくつかライブラリのインストールが必要です。ターミナルからpipでパッケージをインストールしましょう。

pip install google-api-python-client
pip install pyopenssl


キーjsonファイルのダウンロード

アナリティクスAPIを登録した後、公開鍵/秘密鍵等が記載されたファイルをダウンロードします。鍵のタイプを尋ねるメッセージが表示されたら [JSON] を選択してください。生成されたjsonファイルを『client_secrets.json』というファイル名で保存します。こちらは自分のアナリティクスデータにアクセスできるキーファイルですので、厳重に保管しましょう。


サンプルコードのダウンロード

もちろん使い方がわかる人はサンプルコードなんて必要ないのですが、おそらくそうも行かないのでサンプルコードをダウンロードしましょう。こちらにサンプルコードを載せておきます。ファイル名は、公式ドキュメントにある通り『HelloAnalytics.py』とします。

"""A simple example of how to access the Google Analytics API."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

    # Build the service object.
    service = build(api_name, api_version, credentials=credentials)

    return service

def get_first_profile_id(service):
    # Use the Analytics service object to get the first profile id.

    # Get a list of all Google Analytics accounts for this user
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        # Get the first Google Analytics account.
        account = accounts.get('items')[0].get('id')

        # Get a list of all the properties for the first account.
        properties = service.management().webproperties().list(
                accountId=account).execute()

        if properties.get('items'):
            # Get the first property id.
            property = properties.get('items')[0].get('id')

            # Get a list of all views (profiles) for the first property.
            profiles = service.management().profiles().list(
                    accountId=account,
                    webPropertyId=property).execute()

            if profiles.get('items'):
                # return the first view (profile) id.
                return profiles.get('items')[0].get('id')

    return None

def get_results(service, profile_id):
    # Use the Analytics Service Object to query the Core Reporting API
    # for the number of sessions within the past seven days.
    return service.data().ga().get(
            ids='ga:' + profile_id,
            start_date='7daysAgo',
            end_date='today',
            metrics='ga:sessions').execute()

def print_results(results):
    # Print data nicely for the user.
    if results:
        print 'View (Profile):', results.get('profileInfo').get('profileName')
        print 'Total Sessions:', results.get('rows')[0][0]

    else:
        print 'No results found'

def main():
    # Define the auth scopes to request.
    scope = 'https://www.googleapis.com/auth/analytics.readonly'
    key_file_location = '<REPLACE_WITH_JSON_FILE>'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    print_results(get_results(service, profile_id))

if __name__ == '__main__':
    main()

上のサンプルコード内の'<REPLACE_WITH_JSON_FILE>'の部分に、先ほどダウンロードしたキーファイルへのパスを入力します。例えば、以下のようなファイル構造の場合...

root/
    ├ HelloAnalytics.py
    └ client_secrets.json

'<REPLACE_WITH_JSON_FILE>'の部分は'./client_secrets.json'になります。これで面倒な初期設定は完了です。次はこちらのサンプルコードをカスタマイズして、週間アクセスランキングをツイートするスクリプトにしてきましょう。


サンプルコードをカスタマイズしてアクセスランキングを取得

さて、ここからが本題です。

まずはツイートのことを考えずに、アナリティクスAPIからアクセスデータを引っ張ってくることから始めましょう。こちらはアナリティクスAPIを通して、7日間のアクセスランキングを、記事タイトルとともに引っ張ってくるものです。

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

    # Build the service object.
    service = build(api_name, api_version, credentials=credentials)

    return service

def get_first_profile_id(service):
    # Use the Analytics service object to get the first profile id.

    # Get a list of all Google Analytics accounts for this user
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        # Get the first Google Analytics account.
        account = accounts.get('items')[0].get('id')

        # Get a list of all the properties for the first account.
        properties = service.management().webproperties().list(
                accountId=account).execute()

        if properties.get('items'):
            # Get the first property id.
            property = properties.get('items')[0].get('id')

            # Get a list of all views (profiles) for the first property.
            profiles = service.management().profiles().list(
                    accountId=account,
                    webPropertyId=property).execute()

            if profiles.get('items'):
                # return the first view (profile) id.
                return profiles.get('items')[0].get('id')

    return None

def get_weekly_access_ranking(service, profile_id): #7日間のアクセス数と記事タイトルを取得する関数
    results = service.data().ga().get(
                ids='ga:' + profile_id,
                start_date='7daysAgo', #7日前から
                end_date='today', #今日までのアクセスを取得
                dimensions='ga:pageTitle', #記事のタイトルを取得
                metrics='ga:pageviews' #記事のアクセス数を取得
                ).execute()

    ranking = []
    for i in results.get('rows'):
        ranking.append([i[0][:-15], int(i[1])])

    ranking.sort(key=lambda x:x[1], reverse=True) #アクセス数でリストをソート
    return ranking


def main():
    # Define the auth scopes to request.
    scope = 'https://www.googleapis.com/auth/analytics.readonly'
    key_file_location = './client_secrets.json'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    print(get_weekly_access_ranking(service, profile_id)) #アクセスランキングリストを表示


if __name__ == '__main__':
    main()

新しく追加したのはget_weekly_access_ranking()の関数です。こちらは7日間のブログアクセスとアクセス先の記事タイトルをリスト化し、ソートして返す関数です。実行していただくと、アクセスが多い順にリストの要素が表示されます。

こちらをTwitter APIを通してツイートしましょう。


アクセスランキングをツイート

最後に先ほどの取得してきたアクセスデータをツイートして終わりです。

PythonなどのスクリプトからTwitterを利用するには、Twitter APIに登録する必要があります。Twitter APIを登録すると、『Consumer Key』『Consumer Secret』『Access Token』『Access Token Secret』の4つの情報を取得することができます。Twitter APIの登録方法については、以下の記事を参考にしてください。

スクリプトからTwitterを利用できると、簡単にツイートBotアプリなんかも作れますし、Twitter APIは登録して損はないと思います。

取得をしたら、先ほどのスクリプトを以下のように変更します。

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import json, random, twitter_config
from requests_oauthlib import OAuth1Session


def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

    # Build the service object.
    service = build(api_name, api_version, credentials=credentials)

    return service

def get_first_profile_id(service):
    # Use the Analytics service object to get the first profile id.

    # Get a list of all Google Analytics accounts for this user
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        # Get the first Google Analytics account.
        account = accounts.get('items')[0].get('id')

        # Get a list of all the properties for the first account.
        properties = service.management().webproperties().list(
                accountId=account).execute()

        if properties.get('items'):
            # Get the first property id.
            property = properties.get('items')[0].get('id')

            # Get a list of all views (profiles) for the first property.
            profiles = service.management().profiles().list(
                    accountId=account,
                    webPropertyId=property).execute()

            if profiles.get('items'):
                # return the first view (profile) id.
                return profiles.get('items')[0].get('id')

    return None

def get_weekly_access_ranking(service, profile_id): #7日間のアクセス数と記事タイトルを取得する関数
    results = service.data().ga().get(
                ids='ga:' + profile_id,
                start_date='7daysAgo', #7日前から
                end_date='today', #今日までのアクセスを取得
                dimensions='ga:pageTitle', #記事のタイトルを取得
                metrics='ga:pageviews' #記事のアクセス数を取得
                ).execute()

    ranking = []
    for i in results.get('rows'):
        ranking.append([i[0][:-15], int(i[1])])

    ranking.sort(key=lambda x:x[1], reverse=True) #アクセス数でリストをソート
    return ranking

def tweet_weekly_ranking(ranking): #アクセスランキングをツイートする関数
    CK = '<CONSUMER_KEY>'  #Twitter APIのコンシューマーキー
    CS = '<CONSUMER_SECRET>'  #Twitter APIのコンシューマーシークレット
    AT = '<ACCESS_TOKEN>'  #Twitter APIのアクセストークン
    ATS = '<ACCESS_TOKEN_SECRET>'  #Twitter APIのアクセストークンシークレット
    twitter = OAuth1Session(CK, CS, AT, ATS)
    url = "https://api.twitter.com/1.1/statuses/update.json"
    params = {"status" : '''【週別人気記事ランキング】\n1位 : %s\n2位 : %s\n3位 : %s''' % (ranking[0][0], ranking[1][0], ranking[2][0], )}
    res = twitter.post(url, params=params)
    print(res)  #Twitter APIのレスポンスを表示

def main():
    # Define the auth scopes to request.
    scope = 'https://www.googleapis.com/auth/analytics.readonly'
    key_file_location = './client_secrets.json'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    tweet_weekly_ranking(get_weekly_access_ranking(service, profile_id))

if __name__ == '__main__':
    main()

これで完成です。もちろん、やり方によってはアクセスランキング以外のこともアナリティクスAPIを通してツイートすることは可能です。cronなどの設定をすれば、毎週土曜日の9:00にアクセスランキングをツイートするといったことも実現可能です。

cronの使い方に関しては、以前書いた記事がありますので、そちらを参照していただければと思います。

以上でアナリティクスAPIから引っ張ってきたアクセスランキングをツイートするまでの手順は終わりです。お好きにカスタマイズして、面白い機能をどんどん実装してください!

この記事が気に入ったらサポートをしてみませんか?