> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/ja/api-integration/google-sheet-integration.md).

# Google Sheet 連携

Google Sheets 連携：Google Apps Script を使用してスプレッドシートから MaiAgent の Agent を呼び出し、カスタム関数で複数の入力を一括処理します。完全なスクリプトとデモ動画を掲載しています。

このページでは、Google Apps Script を使用して MaiAgent の強力な AI 機能を Google Sheets に組み込む方法を説明します。スプレッドシートから MaiAgent Chatbot を直接呼び出し、複数の入力を一括処理することで、作業効率を大幅に向上できます。

## 初期設定

### ステップ1：Google Apps Script エディタを開く

1. MaiAgent と連携する Google Sheets のスプレッドシートを開くか、新しいスプレッドシートを作成します。
2. 上部メニューの「拡張機能」 > 「Apps Script」をクリックします。

<figure><img src="https://605688223-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVYMUz6J7vDZ0QTvb1rbN%2Fuploads%2Fgit-blob-9edd9980a6679883115c3e18c19810ded49329e9%2F%E6%88%AA%E5%9C%96%202025-05-09%20%E4%B8%8B%E5%8D%883.35.40.png?alt=media" alt=""><figcaption></figcaption></figure>

### ステップ2：スクリプトを貼り付けて設定する

1. Apps Script エディタに表示される `Code.gs` ファイルの既定の内容を削除します。
2. 末尾の[添付資料](#fu-jian)にある MaiAgent 提供の Apps Script コードをすべてコピーし、`Code.gs` ファイルに貼り付けます。
3. **冒頭の API\_KEY と CHATBOT\_ID を置き換えます。**
4. 置き換えたら、エディタ上部の保存アイコン（💾）をクリックしてスクリプトを保存します。

## Google Sheets で MaiAgent 関数を使用する

上記の設定と承認が完了すると、Google Sheets で組み込み関数と同じように `maiagent` 関数を使用できます。

#### 1. Agent を1回呼び出す

任意のセルに、次の形式の数式を入力します：

`=maiagent("Agent に送信するメッセージ内容")`

例：

* `=maiagent("こんにちは、自己紹介をお願いします")`
* `=maiagent("今日はいい天気ですね")`

Enter キーを押すと、スクリプトが指定された Agent にメッセージを送信し、そのセルに Agent の応答内容を表示します。

#### 2. 他のセルからメッセージ内容を読み取る

`maiagent` 関数で他のセルの内容を読み取り、入力メッセージとして使用できます。

送信するメッセージがセル `A1` にある場合、別のセル（例：`B1`）に次の数式を入力します：

`=maiagent(A1)`

これにより、セル `B1` に `A1` の内容に対する MaiAgent の応答が表示されます。

## 連携のデモ動画

{% embed url="<https://drive.google.com/file/d/1NsRpwWGxWpakkRNyXh2WJeBN3Kzw6yDY/view?usp=sharing>" %}

## まとめ

Google Apps Script を通じて MaiAgent を Google Sheets に組み込むことで、自動化と生産性向上の新たな可能性が広がります。技術担当者は、具体的な要件に合わせてスプレッドシートをカスタマイズし、強力な AI 対話ツールとして活用できます。コンテンツ生成、データ分析、自動応答など、さまざまな作業を効率化できます。

## **添付資料**

{% code title="Apps Script コード" %}

```javascript
// --- ここで API キーと Chatbot ID を定義します ---
const API_KEY = '<実際の API キーに置き換えてください>';
const CHATBOT_ID = '<実際の Chatbot ID に置き換えてください>';
// --- --- --- --- --- --- --- --- --- --- --- ---

/**
 * MaiAgent API にメッセージを送信し、応答内容を直接返します。
 * API キーと Chatbot ID には、スクリプト冒頭で定義した定数を使用します。
 * is_streaming は常に false とし、conversation と attachments は送信しません。
 *
 * @param {string} messageContent 送信するメッセージ内容です。
 * @return {string} API 応答の "content" フィールドの内容、またはエラーメッセージです。
 */
function maiagent(messageContent) {
  // API_KEY と CHATBOT_ID が設定されているか確認します
  if (API_KEY === 'YOUR_API_KEY' || CHATBOT_ID === 'YOUR_CHATBOT_ID') {
    const warningMessage = '警告：スクリプトに API キーまたは Chatbot ID が設定されていません。スクリプトを編集し、YOUR_API_KEY と YOUR_CHATBOT_ID を置き換えてください。';
    Logger.log(warningMessage);
    // 無効な API 呼び出しを防ぐため、必要に応じてここでエラーをスローするか、警告を返します
    // throw new Error(warningMessage);
    return warningMessage;
  }

  const url = `https://api.maiagent.ai/api/v1/chatbots/${CHATBOT_ID}/completions/`;

  const payload = {
    message: {
      content: messageContent
    },
    is_streaming: false
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      'Authorization': `Api-Key ${API_KEY}`
    },
    payload: JSON.stringify(payload),
    muteHttpExceptions: true // API が返す可能性のあるエラーメッセージを処理できるように true に設定します
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const responseCode = response.getResponseCode();
    const responseBody = response.getContentText();

    if (responseCode === 200) {
      Logger.log('API 呼び出しに成功しました:');
      Logger.log(responseBody); // デバッグ用に生の応答全体も記録します
      try {
        const jsonResponse = JSON.parse(responseBody);
        if (jsonResponse && typeof jsonResponse.content !== 'undefined') {
          return jsonResponse.content; // content フィールドの値を直接返します
        } else {
          Logger.log('API 応答は成功しましたが、"content" フィールドがないか、形式が正しくありません。');
          Logger.log(responseBody);
          return 'エラー: API 応答は成功しましたが、"content" フィールドがありません。';
        }
      } catch (parseError) {
        Logger.log(`API 応答の JSON 解析中にエラーが発生しました: ${parseError.toString()}`);
        Logger.log(`生の応答内容: ${responseBody}`);
        return `エラー: API 応答の解析に失敗しました - ${parseError.toString()}`;
      }
    } else {
      Logger.log(`API 呼び出しに失敗しました。応答コード: ${responseCode}`);
      Logger.log(`エラー応答の内容: ${responseBody}`);
      return `エラー: ${responseCode} - ${responseBody}`;
    }
  } catch (e) {
    Logger.log(`API 呼び出し中に例外が発生しました: ${e.toString()}`);
    Logger.log(e.stack); // 詳細なデバッグ用にスタックトレースを記録します
    return `例外: ${e.toString()}`;
  }
}
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/ja/api-integration/google-sheet-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
