> 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/maiagent-tech-ja/others/google-sheet-integration.md).

# Google Sheet 連携

本ページでは、Google Apps Script を活用して MaiAgent の強力な AI 機能を Google Sheets に統合する方法をご案内します。この方法により、スプレッドシート内から直接 MaiAgent Chatbot を呼び出し、複数の入力をまとめて一括処理できるようになり、作業効率を大幅に向上させることができます。

## 設定を始める

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

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

<figure><img src="/files/Az9meYiymPrRqIgCBaNA" 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 Sheet で MaiAgent 関数を使う

上記の設定を完了し、認証が正常に行われると、Google Sheet 内で組み込み関数と同じように `maiagent` 関数を使用できるようになります。

#### 1. Agent を単独で呼び出す

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

`=maiagent("Agent に送信したいメッセージ内容")`

例：

* `=maiagent("こんにちは、自己紹介をしてください")`
* `=maiagent("今日はいい天気ですね")`

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

#### 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 // true に設定することで、API が返す可能性のあるエラーメッセージを処理できます
  };

  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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
