Google Chat API を使用してメッセージを送信する

このガイドでは、Google Chat API の messages.create() メソッドを使用して、次のいずれかを行います。

  • テキスト、カード、インタラクティブなウィジェットを含むメッセージを送信します。
  • 特定の Chat ユーザーに非公開でメッセージを送信します。
  • メッセージ スレッドを開始するか、スレッドに返信します。
  • メッセージに名前を付けて、他の Chat API で指定できるようにする できます。

<ph type="x-smartling-placeholder">

メッセージの最大サイズ(テキストやカードを含む)は 32,000 バイトです。 このサイズを超えるメッセージを送信するには、Chat 用アプリで 複数のメッセージを送信する必要があります。

Chat アプリでは、messages.create() メソッドを呼び出すだけでなく、 ユーザーの操作に対するメッセージを作成、送信して、 ユーザーがスペースに Chat 用アプリを追加した後のウェルカム メッセージを 選択します。Chat アプリは、やり取りに応答する際に、他の参加者の メッセージ機能のタイプ(インタラクティブなダイアログ、リンク プレビューなど) インターフェースです。ユーザーに返信する場合、Chat アプリは新しい Chat API を呼び出すことなく、メッセージを同期的に送信できます。学習内容 やり取りへのメッセージの送信については、 Google Chat アプリとのやり取りを受信して応答する

Chat API で作成されたメッセージの表示とアトリビューションの仕組み

messages.create() メソッドは、次のコマンドを使用して呼び出すことができます。 アプリの認証 ユーザー認証があります。 Chat によってメッセージ送信者のアトリビューションが異なる 何を使用するかを選択できます

Chat アプリとして認証すると、 Chat アプリがメッセージを送信します。

<ph type="x-smartling-placeholder">
</ph> アプリ認証を使用して messages.create() メソッドを呼び出す。
図 1: アプリの認証が行われると、Chat アプリは 表示されます。送信者が人間ではないことを示すため、Chat で名前の横に App が表示されます。

ユーザーとして認証すると、Chat アプリは ユーザーの代わりに メッセージを送信できますChat ではさらに、 メッセージに名前が表示されます。

<ph type="x-smartling-placeholder">
</ph> ユーザー認証を使用して messages.create() メソッドを呼び出す。
図 2: ユーザー認証により、ユーザーがメッセージを送信すると、Chat に ユーザーの名前の横に Chat 用アプリの名前が表示されている。

また、認証タイプによって、どのメッセージ機能とインターフェースが メッセージに含めることができます。アプリ認証では Chat アプリは、リッチテキスト、 カードベースのインターフェース、 インタラクティブなウィジェットがあります Chat ユーザーはメッセージ内でのみテキストを送信できるため、 ユーザー認証を使用してメールを作成する場合、テキストのみを含めるようにします。 Google Chat 向けの 機能の詳細については、 Google Chat メッセージの概要

このガイドでは、いずれかの認証タイプを使用してメッセージを送信する方法について説明します。 やり取りできます

前提条件

Node.js

Python

Java

Apps Script

Chat アプリとしてメッセージを送信する

このセクションでは、テキスト、カード、メッセージが含まれる インタラクティブなアクセサリ ウィジェットを アプリの認証

アプリの認証で送信されたメッセージ
図 4. Chat アプリは、Google Chat で送信された テキスト、カード、アクセサリー ボタンです。

アプリの認証を使用して messages.create() を呼び出すには、 次のフィールドが返されます。

  • chat.bot 認可スコープ
  • Space リソース。このリソースには、 選択します。Chat 用アプリは、 メンバーの追加と削除ができます。
  • Message 作成します。メッセージの内容を定義するには、 リッチテキスト (text), 1 つ以上のカード インターフェース (cardsV2), または両方を選択できます

必要に応じて、次の情報を含めることができます。

次のコードは、Chat 用アプリが スペースを含む Chat アプリとして投稿されたメッセージを送信できます。 メッセージの下部にあるクリック可能なボタンも表示できます。

Node.js

chat/client-libraries/cloud/create-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to create message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world! I created this message by calling ' +
            'the Chat API\'s `messages.create()` method.',
      cardsV2 : [{ card: {
        header: {
          title: 'About this message',
          imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
        },
        sections: [{
          header: 'Contents',
          widgets: [{ textParagraph: {
              text: '🔡 <b>Text</b> which can include ' +
                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
            }}, { textParagraph: {
              text: '🖼️ A <b>card</b> to display visual elements' +
                    'and request information such as text 🔤, ' +
                    'dates and times 📅, and selections ☑️.'
            }}, { textParagraph: {
              text: '👉🔘 An <b>accessory widget</b> which adds ' +
                    'a button to the bottom of a message.'
            }}
          ]}, {
            header: "What's next",
            collapsible: true,
            widgets: [{ textParagraph: {
                text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
              }}, { textParagraph: {
                text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                      "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                      "the message."
              }
            }]
          }
        ]
      }}],
      accessoryWidgets: [{ buttonList: { buttons: [{
        text: 'View documentation',
        icon: { materialIcon: { name: 'link' }},
        onClick: { openLink: {
          url: 'https://developers.google.com/workspace/chat/create-messages'
        }}
      }]}}]
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_app_cred.py
from authentication_utils import create_client_with_app_credentials
from google.apps import chat_v1 as google_chat

# This sample shows how to create message with app credential
def create_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world! I created this message by calling ' +
                    'the Chat API\'s `messages.create()` method.',
            "cards_v2" : [{ "card": {
                "header": {
                    "title": 'About this message',
                    "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
                },
                "sections": [{
                    "header": "Contents",
                    "widgets": [{ "text_paragraph": {
                            "text": '🔡 <b>Text</b> which can include ' +
                                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
                        }}, { "text_paragraph": {
                            "text": '🖼️ A <b>card</b> to display visual elements' +
                                    'and request information such as text 🔤, ' +
                                    'dates and times 📅, and selections ☑️.'
                        }}, { "text_paragraph": {
                            "text": '👉🔘 An <b>accessory widget</b> which adds ' +
                                    'a button to the bottom of a message.'
                        }}
                    ]}, {
                        "header": "What's next",
                        "collapsible": True,
                        "widgets": [{ "text_paragraph": {
                                "text": "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
                            }}, { "text_paragraph": {
                                "text": "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                                        "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                                        "the message."
                            }
                        }]
                    }
                ]
            }}],
            "accessory_widgets": [{ "button_list": { "buttons": [{
                "text": 'View documentation',
                "icon": { "material_icon": { "name": 'link' }},
                "on_click": { "open_link": {
                    "url": 'https://developers.google.com/workspace/chat/create-messages'
                }}
            }]}}]
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java
import com.google.apps.card.v1.Button;
import com.google.apps.card.v1.ButtonList;
import com.google.apps.card.v1.Card;
import com.google.apps.card.v1.Icon;
import com.google.apps.card.v1.MaterialIcon;
import com.google.apps.card.v1.OnClick;
import com.google.apps.card.v1.OpenLink;
import com.google.apps.card.v1.TextParagraph;
import com.google.apps.card.v1.Widget;
import com.google.apps.card.v1.Card.CardHeader;
import com.google.apps.card.v1.Card.Section;
import com.google.chat.v1.AccessoryWidget;
import com.google.chat.v1.CardWithId;
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with app credential.
public class CreateMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world! I created this message by calling " +
                    "the Chat API\'s `messages.create()` method.")
          .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()
            .setHeader(CardHeader.newBuilder()
              .setTitle("About this message")
              .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg"))
            .addSections(Section.newBuilder()
              .setHeader("Contents")
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔡 <b>Text</b> which can include " +
                "hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🖼️ A <b>card</b> to display visual elements " +
                "and request information such as text 🔤, " +
                "dates and times 📅, and selections ☑️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "👉🔘 An <b>accessory widget</b> which adds " +
                "a button to the bottom of a message."))))
            .addSections(Section.newBuilder()
              .setHeader("What's next")
              .setCollapsible(true)
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                "the message."))))))
          .addAccessoryWidgets(AccessoryWidget.newBuilder()
            .setButtonList(ButtonList.newBuilder()
              .addButtons(Button.newBuilder()
                .setText("View documentation")
                .setIcon(Icon.newBuilder()
                  .setMaterialIcon(MaterialIcon.newBuilder().setName("link")))
                .setOnClick(OnClick.newBuilder()
                  .setOpenLink(OpenLink.newBuilder()
                    .setUrl("https://developers.google.com/workspace/chat/create-messages")))))));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function createMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world! I created this message by calling ' +
          'the Chat API\'s `messages.create()` method.',
    cardsV2 : [{ card: {
      header: {
        title: 'About this message',
        imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
      },
      sections: [{
        header: 'Contents',
        widgets: [{ textParagraph: {
            text: '🔡 <b>Text</b> which can include ' +
                  'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
          }}, { textParagraph: {
            text: '🖼️ A <b>card</b> to display visual elements' +
                  'and request information such as text 🔤, ' +
                  'dates and times 📅, and selections ☑️.'
          }}, { textParagraph: {
            text: '👉🔘 An <b>accessory widget</b> which adds ' +
                  'a button to the bottom of a message.'
          }}
        ]}, {
          header: "What's next",
          collapsible: true,
          widgets: [{ textParagraph: {
              text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
            }}, { textParagraph: {
              text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                    "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                    "the message."
            }
          }]
        }
      ]
    }}],
    accessoryWidgets: [{ buttonList: { buttons: [{
      text: 'View documentation',
      icon: { materialIcon: { name: 'link' }},
      onClick: { openLink: {
        url: 'https://developers.google.com/workspace/chat/create-messages'
      }}
    }]}}]
  };
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.create(
    message, parent, parameters, getHeaderWithAppCredentials()
  );

  // Handle the response
  console.log(response);
}

このサンプルを実行するには、SPACE_NAME を スペースの name フィールド。 ID を取得するには、 spaces.list() メソッド またはスペースの URL から取得できます。

メッセージの下部にインタラクティブなウィジェットを追加する

このガイドの最初のコードサンプルでは、 Chat 用アプリのメッセージでは、画面上部にクリック可能なボタンが表示され、 これはアクセサリ ウィジェットと呼ばれます。アクセサリ ウィジェット メッセージ内のテキストやカードの後に表示されます。これらのウィジェットを使用して ユーザーがさまざまな方法でメッセージに反応できます。たとえば、次のような方法です。

  • メッセージの正確性または満足度を評価してください。
  • メッセージまたは Chat アプリに関する問題を報告します。
  • ドキュメントなどの関連コンテンツへのリンクを開きます。
  • Chat アプリから類似のメッセージを閉じる、またはスヌーズする 表示されなくなります。

アクセサリ ウィジェットを追加するには、 accessoryWidgets[] フィールドをフィールドに追加して、リクエストするウィジェットを 1 つ以上 追加できます

次の図に、メッセージに ユーザーがエクスペリエンスを評価できるアクセサリ ウィジェットを含むテキスト メッセージ やり取りできます。

<ph type="x-smartling-placeholder">
</ph> アクセサリ ウィジェット。
図 5: テキスト ウィジェット、アクセサリ ウィジェットなどです。

以下は、テキスト メッセージを作成するリクエストの本文を示しています。 2 つのアクセサリ ボタン。ユーザーがボタンをクリックすると、対応する 関数(doUpvote など)がインタラクションを処理します。

{
  text: "Rate your experience with this Chat app.",
  accessoryWidgets: [{ buttonList: { buttons: [{
    icon: { material_icon: {
      name: "thumb_up"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doUpvote"
    }}
  }, {
    icon: { material_icon: {
      name: "thumb_down"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doDownvote"
    }}
  }]}}]
}

非公開でメッセージを送信する

Chat アプリは非公開でメッセージを送信できるため、 メッセージはスペース内の特定のユーザーのみに表示されます。特定の Chat アプリがプライベート メッセージを送信します。 は、メッセージが自分だけに表示されていることをユーザーに通知するラベルを表示します。

Chat API を使用してメッセージを非公開で送信するには、 privateMessageViewer 必ず指定してください。ユーザーを指定するには、値を User リソース。 Chat ユーザーを表します。また、 name フィールド User リソース。次の例をご覧ください。

{
  text: "Hello private world!",
  privateMessageViewer: {
    name: "users/USER_ID"
  }
}

このサンプルを使用するには、USER_ID を置き換えます。 (例: 12345678987654321)または一意の ID に置き換えます。 hao@cymbalgroup.com。ユーザーの指定について詳しくは、このモジュールの Google Chat ユーザーを特定して指定する

メッセージを非公開で送信するには、リクエストで次の項目を省略する必要があります。

ユーザーの代わりにテキスト メッセージを送信する

このセクションでは、 ユーザー認証。 ユーザー認証を使用すると、メッセージのコンテンツにテキストしか メッセージ機能は、Google Chat でのみ利用できる カード インターフェースやインタラクティブなウィジェットなどのチャットアプリ。

ユーザー認証で送信されたメッセージ
図 3. Chat アプリは、Google Chat で 使用できます。

ユーザー認証を使用して messages.create() を呼び出すには、 次のフィールドが返されます。

  • 認可スコープ サポートしています。次のサンプルでは、 chat.messages.create スコープ。
  • Space リソース。このリソースには、 選択します。認証されたユーザーは、 選択します。
  • Message 作成します。メッセージの内容を定義するには、 text 表示されます。

必要に応じて、次の情報を含めることができます。

次のコードは、Chat 用アプリが は、認証されたユーザーの代わりに、特定のスペースでテキスト メッセージを送信できます。

Node.js

chat/client-libraries/cloud/create-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world!' +
            'Text messages can contain things like:\n\n' +
            '* Hyperlinks 🔗\n' +
            '* Emojis 😄🎉\n' +
            '* Mentions of other Chat users `@` \n\n' +
            'For details, see the ' +
            '<https://developers.google.com/workspace/chat/format-messages' +
            '|Chat API developer documentation>.'
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

def create_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world!' +
                    'Text messages can contain things like:\n\n' +
                    '* Hyperlinks 🔗\n' +
                    '* Emojis 😄🎉\n' +
                    '* Mentions of other Chat users `@` \n\n' +
                    'For details, see the ' +
                    '<https://developers.google.com/workspace/chat/format-messages' +
                    '|Chat API developer documentation>.'
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with user credential.
public class CreateMessageUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world!" +
                    "Text messages can contain things like:\n\n" +
                    "* Hyperlinks 🔗\n" +
                    "* Emojis 😄🎉\n" +
                    "* Mentions of other Chat users `@` \n\n" +
                    "For details, see the " +
                    "<https://developers.google.com/workspace/chat/format-messages" +
                    "|Chat API developer documentation>."));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world!' +
          'Text messages can contain things like:\n\n' +
          '* Hyperlinks 🔗\n' +
          '* Emojis 😄🎉\n' +
          '* Mentions of other Chat users `@` \n\n' +
          'For details, see the ' +
          '<https://developers.google.com/workspace/chat/format-messages' +
          '|Chat API developer documentation>.'
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent);

  // Handle the response
  console.log(response);
}

このサンプルを実行するには、SPACE_NAME を スペースの name 表示されます。ID を取得するには、 spaces.list() メソッド またはスペースの URL から取得できます。

スレッドを開始または返信する

スレッドを使用するスペースの場合: 新しいメッセージがスレッドを開始するか、新しいメッセージが 削除することもできます。

デフォルトでは、Chat API を使用して作成したメッセージからは、 使用します。スレッドを特定して後で返信できるように、 あります。

  • リクエストの本文で、 thread.threadKey 表示されます。
  • クエリ パラメータを指定する messageReplyOption を使用して、鍵がすでに存在する場合にどうなるかを判断します。

既存のスレッドに返信するメッセージを作成するには:

  • リクエストの本文に thread フィールドを含めます。設定すると、 「 threadKey 作成します。それ以外の場合は、 name 表示されます。
  • クエリ パラメータ messageReplyOption を指定します。

次のコードは、Chat 用アプリが で識別された特定のスレッドに対して開始または返信するテキスト メッセージを送信できます 認証されたユーザーに代わって、特定のスペースのキーを渡します。

Node.js

chat/client-libraries/cloud/create-message-user-cred-thread-key.js
import {createClientWithUserCredentials} from './authentication-utils.js';
const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with thread key
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Creates the message as a reply to the thread specified by thread_key
    // If it fails, the message starts a new thread instead
    messageReplyOption: MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
    message: {
      text: 'Hello with user credential!',
      thread: {
        // Thread key specifies a thread and is unique to the chat app
        // that sets it
        threadKey: 'THREAD_KEY'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_thread_key.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

import google.apps.chat_v1.CreateMessageRequest.MessageReplyOption

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with thread key
def create_message_with_user_cred_thread_key():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Creates the message as a reply to the thread specified by thread_key.
        # If it fails, the message starts a new thread instead.
        message_reply_option = MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
        message = {
            "text": "Hello with user credential!",
            "thread": {
                # Thread key specifies a thread and is unique to the chat app
                # that sets it.
                "thread_key": "THREAD_KEY"
            }
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_thread_key()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.CreateMessageRequest.MessageReplyOption;
import com.google.chat.v1.Message;
import com.google.chat.v1.Thread;

// This sample shows how to create message with a thread key with user
// credential.
public class CreateMessageUserCredThreadKey {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Creates the message as a reply to the thread specified by thread_key.
        // If it fails, the message starts a new thread instead.
        .setMessageReplyOption(
          MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!")
          // Thread key specifies a thread and is unique to the chat app
          // that sets it.
          .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY")));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential with thread key
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredThreadKey() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Creates the message as a reply to the thread specified by thread_key
  // If it fails, the message starts a new thread instead
  const messageReplyOption = 'REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD';
  const message = {
    text: 'Hello with user credential!',
    thread: {
      // Thread key specifies a thread and is unique to the chat app
      // that sets it
      threadKey: 'THREAD_KEY'
    }
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageReplyOption: messageReplyOption
  });

  // Handle the response
  console.log(response);
}

このサンプルを実行するには、次のように置き換えます。

  • THREAD_KEY: スペース内の既存のスレッドキー、または 新しいスレッド(スレッドの一意の名前)を作成します。
  • SPACE_NAME: スペースの ID name 表示されます。ID を取得するには、 spaces.list() メソッド またはスペースの URL から取得できます。

メッセージに名前を付ける

今後の API 呼び出しでメッセージを取得または指定するには、メッセージに messages.create() リクエストに messageId フィールドを設定します。 メッセージに名前を付けることで、 メッセージのリソース名からシステムによって割り当てられた ID( name フィールド)。

たとえば、get() メソッドを使用してメッセージを取得するには、 して、取得するメッセージを指定します。リソース名は spaces/{space}/messages/{message} の形式。{message} は以下を表します。 システムによって割り当てられた ID、または 表示されます。

メッセージに名前を付けるには、カスタム ID を messageId 指定する必要があります。messageId フィールドは、次の値を設定します。 clientAssignedMessageId Message リソースのフィールド。

メッセージに名前を付けることができるのは、メッセージの作成時のみです。名前やメールアドレスを 既存のメッセージのカスタム ID を変更できます。カスタム ID は次の条件を満たす必要があります。 要件:

  • client- で始まります。たとえば、client-custom-name は有効なカスタム ID になりますが、custom-name は一致しません。
  • 63 文字以下で、英小文字、数字、 使用できます。
  • スペース内で一意である。Chat アプリでは、 同じカスタム ID を使用する必要があります。

次のコードは、Chat 用アプリが スペースに代理で ID を含むテキスト メッセージを送信できます。 認証されたユーザー:

Node.js

chat/client-libraries/cloud/create-message-user-cred-message-id.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with message id
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Message id lets chat apps get, update or delete a message without needing
    // to store the system assigned ID in the message's resource name
    messageId: 'client-MESSAGE-ID',
    message: { text: 'Hello with user credential!' }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_message_id.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with message id
def create_message_with_user_cred_message_id():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Message id let chat apps get, update or delete a message without needing
        # to store the system assigned ID in the message's resource name.
        message_id = "client-MESSAGE-ID",
        message = {
            "text": "Hello with user credential!"
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_message_id()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with message id specified with user
// credential.
public class CreateMessageUserCredMessageId {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!"))
        // Message ID lets chat apps get, update or delete a message without
        // needing to store the system assigned ID in the message's resource
        // name.
        .setMessageId("client-MESSAGE-ID");
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential with message id
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredMessageId() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Message id lets chat apps get, update or delete a message without needing
  // to store the system assigned ID in the message's resource name
  const messageId = 'client-MESSAGE-ID';
  const message = { text: 'Hello with user credential!' };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageId: messageId
  });

  // Handle the response
  console.log(response);
}

このサンプルを実行するには、次のように置き換えます。

  • SPACE_NAME: スペースの ID name 表示されます。ID を取得するには、 spaces.list() メソッド またはスペースの URL から取得できます。
  • MESSAGE-ID: 先頭のメッセージの名前 custom- に置き換えます。他のメッセージと重複しないようにする必要があります。 Chat アプリを開いたら、

トラブルシューティング

Google Chat アプリまたは card がエラーを返した場合、 Chat のインターフェースに「エラーが発生しました」というメッセージが表示されている。 または「リクエストを処理できません」が表示されます。場合によっては、Chat の UI が エラー メッセージは表示されませんが、Chat 用アプリまたは 予期しない結果が生じた場合たとえば、カード メッセージに 表示されます。

Chat UI にエラー メッセージが表示されない場合がありますが、 エラーの修正に役立つ、わかりやすいエラー メッセージとログデータ Chat 用アプリのエラーロギングが有効になっている場合。表示のヘルプについては、 エラーの修正について詳しくは、このモジュールの Google Chat のエラーのトラブルシューティングと修正