2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GASから短縮URL付きで自動ツイートする

Posted at

はじめに

個人アプリで、新着記事があったらpushを送る、という機能を実装したのですが、これをtwitterでも自動ツイートできると、アプリの拡散・宣伝にも繋がるかもしれないな、と思い立ち、やってみることにしました。

ツイート処理

こちらの記事が丁寧でわかりやすかったです。
Google Apps Script (GAS) でTwitterへ投稿するだけの機能を実装してみる

こちらを参考に、PUSHのタイミングでツイートもしてあげるとよいかと思います。
また、アプリの宣伝のためには、マーケットのURLもツイートに含めてあげる必要がありますが、URLが長すぎるといろいろ不都合が多いので、短縮URLを使ってあげます。

URLの短縮

利用するサービスはこちら。
Google URL Shortener

GASから利用するには、スクリプトのメニュー「リソース」>「Googleの拡張サービス」から、「URL Shortener API」をON(有効)にします。

次に、下記URLからコンソール上でもURL Shortener APIを有効にします。
https://console.cloud.google.com/apis/library/urlshortener.googleapis.com/?q=url

実際のコードはこちらの記事を参考にさせていただきました。
[GAS]SpreadSheetで短縮URLを出力する関数(goo.gl編)

API_KEY = 'xxxxxxxxxxxx';
function urlShortener(url) {
  var apiUrl  = 'https://www.googleapis.com/urlshortener/v1/url?key='+API_KEY;
  var payload = { longUrl: url };
  var options = {
        method: 'POST',
        contentType: 'application/json',
        payload: JSON.stringify(payload),
        muteHttpExceptions: true
      }
  var response = UrlFetchApp.fetch(apiUrl, options);
  if (response.getResponseCode() !== 200) {
    throw new Error('cannot shorten url.');
  } else {
    return JSON.parse(response).id;
  }
}

API_KEYは以下の手順で作成できます。
https://console.cloud.google.com/apis/credentials
「認証情報」タブ>「認証情報を作成」ボタン>「APIキー」から作成
作成済みの場合は認証情報タブにAPIキーとして記載されていると思います。

解析

Googleの短縮URLではクリック数などのも計測可能です。
https://developers.google.com/url-shortener/v1/getting_started

function shortUrlClickCount(shortUrl) {
  try {    
    // projection=FULL にするともっと細かい情報も取得可能です。
    var apiUrl = 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=' + shortUrl + '&projection=ANALYTICS_CLICKS&key=' + API_KEY
    var response = UrlFetchApp.fetch(apiUrl);
    if (response.getResponseCode() !== 200) {
      throw new Error('cannot analyze shorten url.');
    } else {
      return JSON.parse(response).analytics['allTime']['shortUrlClicks'].toString();
    }
  } catch(e) {
    return e.toString();
  }
}

解析結果は下記のような配列で返却されます。

({allTime:{shortUrlClicks:"1", longUrlClicks:"1"}, 
  month:{shortUrlClicks:"1", longUrlClicks:"1"}, 
  week:{shortUrlClicks:"1", longUrlClicks:"1"}, 
  day:{shortUrlClicks:"1", longUrlClicks:"1"}, 
  twoHours:{shortUrlClicks:"1", longUrlClicks:"1"}) 

期間がallTime/month/week/day/twoHours が用意されており、それぞれshortUrlClicksとlongUrlClicksが取得できるようですが、サンプルでは全期間の短縮URLクリック数のみ出力しています。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?