AdSense情報をGASを使ってLINE Botで受け取れるようにした
いちいちアカウントページに見に行くのも面倒なので、LINE Botで受け取れるようにしてみました。適当なテキストを送ると現時点の当日収益額と、昨日と当月トータルの収益額を返してくれるようにしました。↓こんな感じです。ソースコードを書き留めておきます。
ソースコードの前にAdSense収益額をLINE Botに乗せるまでの準備として以下の手順を踏みます。各リンクを参考にしてください。
- LINE Botを作るための準備(Messaging APIの登録)
- LINE Developersでチャネルアクセストークンを発行する方法
- LINE Bot開発:自動応答メッセージをOFFにする方法
- LINE BotをGoogle Apps Scriptで作ったら結構簡単だった
- Google Adsense情報をGoogle Apps Scriptで受け取る方法
上記のテクニックを使うことで今回のAdSense LINE Botを作ることができます。
それでは以下がソースコードとなります。
function getAdSenseData() { var dt = new Date(new Date().getFullYear(), new Date().getMonth(), 0); var startDate = Utilities.formatDate(dt, 'Asia/Tokyo', 'yyyy-MM-dd'); var id = 'ca-pub-XXXXX' //自分のアドセンスID var endDate = 'today'; var metrics = ['EARNINGS'] var args = { 'metric': metrics, 'dimension': ['DATE'], 'filter': ['AD_CLIENT_ID==' + id], 'useTimezoneReporting': true, //ローカルタイムゾーン設定 }; var report = AdSense.Reports.generate(startDate, endDate, args).getRows(); return report; } const TOKEN = '自分のチャンネルアクセストークン'; function doPost(e) { //AdSense情報GET report = getAdSenseData(); var today = -1; var yesterday = -1; var total = 0; report.forEach(function(key){ total+=Number(key[1]); }); if(report.length>=2) yesterday = report[report.length-2][1]; if(report.length>=1) today = report[report.length-1][1]; var mess = "Today:" +today+ "\nYesterday:" +yesterday+ "\ntotal:" +new Intl.NumberFormat('ja-JP').format(total); const responseLine = e.postData.getDataAsString(); const event = JSON.parse(responseLine).events[0]; const replyToken = event.replyToken; //ユーザーIDを取得 const userID = event.source.userId; //LINEのメッセージ形式にする const LineMessageObject = [{ 'type': 'text', 'text': mess, }]; const replyHeaders = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + TOKEN }; const replyBody = { 'replyToken': replyToken, 'messages': LineMessageObject }; const replyOptions = { 'method': 'POST', 'headers': replyHeaders, 'payload': JSON.stringify(replyBody) }; UrlFetchApp.fetch('https://api.line.me/v2/bot/message/reply', replyOptions); }
スポンサーリンク