Cloud FunctionsからGASを実行したい

実現したいこと

Cloud Functions(Node.js)からGASに書いた関数を呼び出し、実行したい。
そのために必要なCloud Functions側のコードと、GAS側のコードが知りたい。

発生している問題・分からないこと

事前準備

  • GCPでプロジェクト作成
  • IAMでサービスアカウント作成→jsonファイルダウンロード
  • GASで実行したい関数を作成

発生している問題

Cloud Functionsでコードを作成しデプロイすると、デプロイ中に「アーカイブの取得中に不明なエラーが発生しました」のメッセージが出る。
デプロイは無事に完了するが、コードは保存されておらず、初期状態のコードに戻ってしまう。

Cloud Functions側のコード

index.js

1const { google } = require('googleapis'); 2 3exports.callGoogleAppsScript = async (req, res) => { 4 try { 5 // Google Apps ScriptのプロジェクトIDを設定 6 const scriptId = 'YOUR_GOOGLE_APPS_SCRIPT_PROJECT_ID'; 7 8 // パラメータとして渡すデータ 9 const requestData = { 10 arg1: 'value1', 11 arg2: 'value2', 12 }; 13 14 // OAuth2クライアントの作成 15 const auth = new google.auth.GoogleAuth({ 16 keyFile: 'path/to/your/credentials.json', // サービスアカウントのJSONファイルのパス 17 scopes: ['https://www.googleapis.com/auth/script.external_request'], // 必要なスコープ 18 }); 19 const authClient = await auth.getClient(); 20 21 // Google Apps ScriptのAPIを呼び出す 22 const script = google.script({ version: 'v1', auth: authClient }); 23 const response = await script.scripts.run({ 24 scriptId, 25 resource: { 26 function: 'yourFunctionName', // Google Apps Scriptの関数名 27 parameters: [JSON.stringify(requestData)], // パラメータをJSON文字列に変換して渡す 28 }, 29 }); 30 31 // ログに出力(ここではCloud Functionsのログに出力します) 32 console.log('Google Apps Script Response:', response.data); 33 34 // 成功時のレスポンス 35 res.status(200).send('Google Apps Script executed successfully'); 36 } catch (error) { 37 console.error('Error calling Google Apps Script:', error); 38 // エラー時のレスポンス 39 res.status(500).send('Error calling Google Apps Script'); 40 } 41}; 42

GAS側のコード

index.gs

1function yourFunctionName(data) { 2 console.log('Received data:', data); 3 return 'Function executed successfully'; 4} 5

試したこと・調べたこと

上記の詳細・結果

コードはchatGPTで検索してみて出てきたものです。
書いていて自信がなかったのは、googleapisをインストールする際、Cloud Shellで

bash

1npm install googleapis@40

と打ったんですが、これが動いてるのかどうかよく分からなかったところです。

補足

特になし

コメントを投稿

0 コメント