Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

Google App ScriptでAPIから必要なデータのみを取り出してWebhookをで送信する方法とコード例を教えてください。

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-mini’s answer.
  1. User

    Google App ScriptでAPIから必要なデータのみを取り出してWebhookをで送信する方法とコード例を教えてください。

  2. Claude Assistant

    Google Apps ScriptでAPIからデータを取得し、必要な部分のみを抽出してWebhookで送信する基本的な流れとコード例をご紹介します。

    基本的な流れ

    1. APIからデータを取得
    2. 必要なデータのみを抽出・加工
    3. Webhookエンドポイントに送信

    コード例

    function fetchDataAndSendWebhook() {
      try {
        // 1. APIからデータを取得
        const apiUrl = 'https://api.example.com/data';
        const apiResponse = UrlFetchApp.fetch(apiUrl, {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer YOUR_API_TOKEN',
            'Content-Type': 'application/json'
          }
        });
        
        const rawData = JSON.parse(apiResponse.getContentText());
        
        // 2. 必要なデータのみを抽出
        const filteredData = extractNeededData(rawData);
        
        // 3. Webhookで送信
        sendWebhook(filteredData);
        
      } catch (error) {
        console.error('エラーが発生しました:', error);
      }
    }
    
    // データ抽出関数の例
    function extractNeededData(rawData) {
      // 例:配列から特定の条件に合うデータのみを抽出
      if (Array.isArray(rawData)) {
        return rawData
          .filter(item => item.status === 'active') // アクティブなもののみ
          .map(item => ({
            id: item.id,
            name: item.name,
            updatedAt: item.updated_at,
            value: item.metrics?.value || 0
          }));
      }
      
      // 例:オブジェクトから必要なフィールドのみを抽出
      return {
        summary: rawData.summary,
        totalCount: rawData.total_count,
        lastUpdated: rawData.last_updated,
        importantItems: rawData.items?.slice(0, 5) // 最初の5件のみ
      };
    }
    
    // Webhook送信関数
    function sendWebhook(data) {
      const webhookUrl = 'https://hooks.example.com/webhook';
      
      const payload = {
        timestamp: new Date().toISOString(),
        source: 'Google Apps Script',
        data: data
      };
      
      const options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        payload: JSON.stringify(payload)
      };
      
      const response = UrlFetchApp.fetch(webhookUrl, options);
      
      if (response.getResponseCode() === 200) {
        console.log('Webhook送信成功');
      } else {
        console.error('Webhook送信失敗:', response.getResponseCode());
      }
    }
    

    より実践的な例(Slack Webhook)

    function sendToSlack() {
      // APIからユーザーデータを取得
      const apiResponse = UrlFetchApp.fetch('https://api.example.com/users');
      const users = JSON.parse(apiResponse.getContentText());
      
      // 新規登録ユーザーのみを抽出
      const today = new Date();
      const newUsers = users.filter(user => {
        const registeredDate = new Date(user.registered_at);
        return registeredDate.toDateString() === today.toDateString();
      });
      
      // Slackメッセージを作成
      const message = {
        text: `本日の新規登録ユーザー: ${newUsers.length}名`,
        attachments: newUsers.slice(0, 10).map(user => ({
          color: 'good',
          fields: [
            {
              title: user.name,
              value: `Email: ${user.email}\n登録時刻: ${user.registered_at}`,
              short: true
            }
          ]
        }))
      };
      
      // Slack Webhookに送信
      UrlFetchApp.fetch('YOUR_SLACK_WEBHOOK_URL', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        payload: JSON.stringify(message)
      });
    }
    

    定期実行の設定

    function setupTrigger() {
      // 毎時実行するトリガーを設定
      ScriptApp.newTrigger('fetchDataAndSendWebhook')
        .timeBased()
        .everyHours(1)
        .create();
    }
    

    エラーハンドリングの強化

    function robustFetchAndSend() {
      const maxRetries = 3;
      let retryCount = 0;
      
      while (retryCount < maxRetries) {
        try {
          const response = UrlFetchApp.fetch(apiUrl, options);
          
          if (response.getResponseCode() !== 200) {
            throw new Error(`API Error: ${response.getResponseCode()}`);
          }
          
          const data = JSON.parse(response.getContentText());
          sendWebhook(extractNeededData(data));
          break; // 成功したらループを抜ける
          
        } catch (error) {
          retryCount++;
          console.error(`試行 ${retryCount} 失敗:`, error);
          
          if (retryCount >= maxRetries) {
            // 最終的に失敗した場合の通知
            sendErrorNotification(error);
          } else {
            Utilities.sleep(2000); // 2秒待機してリトライ
          }
        }
      }
    }
    

    このようにGoogle Apps Scriptを使用することで、APIからのデータ取得、フィルタリング、Webhook送信を自動化できます。用途に応じてデータ抽出ロジックやWebhookのペイロード形式を調整してください。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt

Google App ScriptでAPIから必要なデータのみを取り出し… · The Chat Archive