Google Chat API'yi kullanarak mesaj gönderme

Bu kılavuzda, Google Chat API'nin Message kaynağında create() yöntemini kullanarak aşağıdakilerden herhangi birini nasıl yapacağınız açıklanmaktadır:

  • Metin, kart ve etkileşimli widget içeren mesajlar gönderme
  • Belirli bir Chat kullanıcısına özel mesaj gönderme
  • Mesaj dizisi başlatma veya yanıtlama
  • Diğer Chat API isteklerinde belirtebilmek için bir mesajı adlandırın.

Maksimum ileti boyutu (metin veya kartlar dahil) 32.000 bayttır. Bu boyutu aşan bir mesaj göndermek için Chat uygulamanız bunun yerine birden fazla mesaj göndermelidir.

Chat uygulamaları, mesaj oluşturmak için Chat API'sini çağırmanın yanı sıra kullanıcı etkileşimlerini yanıtlamak için mesaj oluşturup gönderebilir. Örneğin, kullanıcı bir alana Chat uygulamasını ekledikten sonra karşılama mesajı yayınlayabilir. Sohbet uygulamaları, etkileşimlere yanıt verirken etkileşimli iletişim kutuları ve bağlantı önizleme arayüzleri gibi diğer mesajlaşma özelliklerini kullanabilir. Chat uygulaması, kullanıcıyı yanıtlamak için Chat API'yi çağırmadan mesajı senkron olarak döndürür. Etkileşimlere yanıt vermek için mesaj gönderme hakkında bilgi edinmek istiyorsanız Google Chat uygulamanızla etkileşimleri alma ve yanıtlama başlıklı makaleyi inceleyin.

Chat API ile oluşturulan mesajları Chat'in görüntüleme ve ilişkilendirme şekli

create() yöntemini uygulama kimlik doğrulaması ve kullanıcı kimlik doğrulaması ile çağırabilirsiniz. Chat, kullandığınız kimlik doğrulama türüne bağlı olarak mesaj gönderen kişiyi farklı şekilde ilişkilendirir.

Chat uygulaması olarak kimliğinizi doğruladığınızda Chat uygulaması mesajı gönderir.

create() yöntemini uygulama kimlik doğrulamasıyla çağırma.
Şekil 1: Uygulama kimlik doğrulamasıyla Chat uygulaması mesajı gönderir. Gönderenin bir kişi olmadığını belirtmek için Chat, adının yanında App simgesini gösterir.

Kullanıcı olarak kimlik doğruladığınızda Chat uygulaması, mesajı kullanıcı adına gönderir. Chat, adını göstererek Chat uygulamasını da mesajla ilişkilendirir.

Kullanıcı kimlik doğrulamasıyla create() yöntemini çağırma.
Şekil 2: Kullanıcı kimlik doğrulamasıyla kullanıcı mesajı gönderir ve Chat, kullanıcının adının yanında Chat uygulama adını gösterir.

Kimlik doğrulama türü, iletiye ekleyebileceğiniz mesajlaşma özelliklerini ve arayüzlerini de belirler. Uygulama kimlik doğrulaması ile Chat uygulamaları, zengin metin, kart tabanlı arayüzler ve etkileşimli widget'lar içeren mesajlar gönderebilir. Chat kullanıcıları iletilerinde yalnızca metin gönderebildiğinden, kullanıcı kimlik doğrulamasıyla ileti oluştururken yalnızca metin ekleyebilirsiniz. Chat API'de kullanılabilen mesajlaşma özellikleri hakkında daha fazla bilgi edinmek için Google Chat mesajlarına genel bakış başlıklı makaleyi inceleyin.

Bu kılavuzda, Chat API ile mesaj göndermek için her iki kimlik doğrulama türünün nasıl kullanılacağı açıklanmaktadır.

Ön koşullar

Node.js

Python

Java

Apps Komut Dosyası

Chat uygulaması olarak mesaj gönderme

Bu bölümde, Uygulama kimlik doğrulaması kullanılarak metin, kart ve etkileşimli aksesuar widget'ları içeren mesajların nasıl gönderileceği açıklanmaktadır.

Uygulama kimlik doğrulamasıyla gönderilen ileti
4.şekil Bir Chat uygulaması metin, kart ve aksesuar düğmesi içeren bir mesaj gönderir.

Uygulama kimlik doğrulaması kullanarak CreateMessage() yöntemini çağırmak için istekte aşağıdaki alanları belirtmeniz gerekir:

  • chat.bot Yetkilendirme kapsamı.
  • Mesajı yayınlamak istediğiniz Space kaynağı. Sohbet uygulaması, alanın üyesi olmalıdır.
  • Oluşturulacak Message kaynağı. İletinin içeriğini tanımlamak için zengin metin (text), bir veya daha fazla kart arayüzü (cardsV2) ya da her ikisini de ekleyebilirsiniz.

İsteğe bağlı olarak aşağıdakileri ekleyebilirsiniz:

Aşağıdaki kodda, bir Chat uygulamasının, Chat uygulaması olarak yayınlanan ve metin, kart ve mesajın alt kısmında tıklanabilir bir düğme içeren bir mesajı nasıl gönderebileceğine dair bir örnek gösterilmektedir:

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 Komut Dosyası

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);
}

Bu örneği çalıştırmak için SPACE_NAME yerine alanın name alanındaki kimliği girin. Kimliği ListSpaces() yöntemini çağırarak veya alanın URL'sinden alabilirsiniz.

İletinin alt kısmına etkileşimli widget'lar ekleme

Bu kılavuzdaki ilk kod örneğinde, sohbet uygulaması mesajında mesajın alt kısmında tıklanabilir bir düğme gösterilir. Bu düğmeye aksesuar widget'ı adı verilir. Aksesuar widget'ları, iletideki metin veya kartlardan sonra görünür. Bu widget'ları kullanarak kullanıcıları iletinizle etkileşime geçmeye teşvik edebilirsiniz. Örneğin:

  • Bir mesajın doğruluğunu veya memnuniyet düzeyini değerlendirme
  • Mesaj veya Chat uygulamasıyla ilgili bir sorun bildirin.
  • Dokümanlar gibi ilgili içeriklerin bağlantılarını açma
  • Sohbet uygulamasından gelen benzer mesajları belirli bir süre boyunca kapatabilir veya erteleyebilirsiniz.

Yardımcı widget'lar eklemek için isteğinizin gövdesine accessoryWidgets[] alanını ekleyin ve dahil etmek istediğiniz bir veya daha fazla widget'ı belirtin.

Aşağıdaki resimde, kullanıcıların Chat uygulamasıyla ilgili deneyimlerini değerlendirebilmeleri için metin mesajına aksesuar widget'ları ekleyen bir Chat uygulaması gösterilmektedir.

Aksesuar widget&#39;ı.
Şekil 5: Metin ve aksesuar widget'ları içeren bir Chat uygulaması mesajı.

Aşağıda, iki aksesuar düğmesi içeren bir kısa mesaj oluşturan isteğin gövdesi gösterilmektedir. Kullanıcı bir düğmeyi tıkladığında ilgili işlev (ör. doUpvote) etkileşimi işler:

{
  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"
    }}
  }]}}]
}

Özel mesaj gönderme

Sohbet uygulamaları, mesajı yalnızca alandaki belirli bir kullanıcının görebileceği şekilde özel olarak gönderebilir. Bir sohbet uygulaması özel mesaj gönderdiğinde, mesajda kullanıcının mesajı yalnızca kendisinin görebileceğini belirten bir etiket gösterilir.

Chat API'yi kullanarak iletiyi özel olarak göndermek için isteğinizin gövdesinde privateMessageViewer alanını belirtin. Kullanıcıyı belirtmek için değeri, Chat kullanıcısını temsil eden User kaynağına ayarlarsınız. Ayrıca, aşağıdaki örnekte gösterildiği gibi, User kaynağının name alanını da kullanabilirsiniz:

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

Bu örneği kullanmak için USER_ID yerine kullanıcı için benzersiz bir kimlik (ör. 12345678987654321 veya hao@cymbalgroup.com) girin. Kullanıcıları belirtme hakkında daha fazla bilgi için Google Chat kullanıcılarını tanımlama ve belirtme başlıklı makaleyi inceleyin.

Özel mesaj göndermek için isteğinizde aşağıdakileri belirtmemeniz gerekir:

Kullanıcı adına kısa mesaj gönderme

Bu bölümde, kullanıcı kimlik doğrulaması kullanarak kullanıcı adına nasıl ileti gönderileceği açıklanmaktadır. Kullanıcı kimlik doğrulamasıyla, mesajın içeriği yalnızca metin içerebilir ve kart arayüzleri ile etkileşimli widget'lar da dahil olmak üzere yalnızca Chat uygulamalarında kullanılabilen mesajlaşma özellikleri çıkarılmalıdır.

Kullanıcı kimlik doğrulamasıyla gönderilen ileti
3.şekil Bir Chat uygulaması, kullanıcı adına kısa mesaj gönderir.

Kullanıcı kimlik doğrulamasıyla CreateMessage() yöntemini çağırmak için istekte aşağıdaki alanları belirtmeniz gerekir:

  • Bu yöntem için kullanıcı kimlik doğrulamasını destekleyen bir yetkilendirme kapsamı. Aşağıdaki örnekte chat.messages.create kapsamı kullanılmaktadır.
  • Mesajı yayınlamak istediğiniz Space kaynağı. Kimliği doğrulanmış kullanıcı, alanın üyesi olmalıdır.
  • Oluşturulacak Message kaynağı. İletinin içeriğini tanımlamak için text alanını eklemeniz gerekir.

İsteğe bağlı olarak aşağıdakileri ekleyebilirsiniz:

Aşağıdaki kodda, bir Chat uygulamasının kimliği doğrulanmış bir kullanıcı adına belirli bir alanda nasıl kısa mesaj gönderebileceğine dair bir örnek gösterilmektedir:

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 Komut Dosyası

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);
}

Bu örneği çalıştırmak için SPACE_NAME yerine alanın name alanındaki kimliği girin. Kimliği ListSpaces() yöntemini çağırarak veya alanın URL'sinden alabilirsiniz.

İleti dizisi başlatma veya ileti dizisinde yanıt verme

İleti dizilerinin kullanıldığı alanlarda, yeni bir mesajın ileti dizisi başlatıp başlatmayacağını veya mevcut bir ileti dizisini yanıtlayıp yanıtlamayacağını belirleyebilirsiniz.

Varsayılan olarak, Chat API kullanılarak oluşturulan mesajlar yeni bir ileti dizisi başlatır. İş parçacığını belirlemenize ve daha sonra yanıtlamanıza yardımcı olması için isteğinizde bir iş parçacığı anahtarı belirtebilirsiniz:

  • İsteğinizin gövde bölümünde thread.threadKey alanını belirtin.
  • Anahtar zaten varsa ne olacağını belirlemek için sorgu parametresini messageReplyOption belirtin.

Mevcut bir ileti dizisini yanıtlayan bir mesaj oluşturmak için:

  • İsteğinizin gövdesine thread alanını ekleyin. Ayarlanmışsa oluşturduğunuz threadKey'ı belirtebilirsiniz. Aksi takdirde, ileti dizisinin name kullanmanız gerekir.
  • messageReplyOption sorgu parametresini belirtin.

Aşağıdaki kod, bir Chat uygulamasının kimliği doğrulanmış bir kullanıcı adına belirli bir alandaki anahtarla tanımlanan belirli bir ileti dizisini başlatan veya bu ileti dizisine yanıt veren bir kısa mesaj gönderme örneğini gösterir:

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 Komut Dosyası

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);
}

Bu örneği çalıştırmak için aşağıdakileri değiştirin:

  • THREAD_KEY: Alanın mevcut bir ileti dizisi anahtarı veya yeni bir ileti dizisi oluşturmak için ileti dizisinin benzersiz adı.
  • SPACE_NAME: Alanın name alanındaki kimlik. Kimliği ListSpaces() yöntemini çağırarak veya alanın URL'sinden alabilirsiniz.

İletileri adlandırma

Gelecekteki API çağrılarında bir mesajı almak veya belirtmek için isteğinizdeki messageId alanını ayarlayarak bir mesaja ad verebilirsiniz. İletinize ad verdiğinizde, iletinin kaynak adından sisteme atanan kimliği (name alanında gösterilir) depolamanıza gerek kalmadan iletiyi belirtebilirsiniz.

Örneğin, get() yöntemini kullanarak bir iletiyi almak için hangi iletinin alınacağını belirtmek üzere kaynak adını kullanırsınız. Kaynak adı, spaces/{space}/messages/{message} biçimindedir. Burada {message}, sisteme atanan kimliği veya mesajı oluştururken ayarladığınız özel adı temsil eder.

Bir iletiye ad vermek için iletiyi oluştururken messageId alanında özel bir kimlik belirtin. messageId alanı, Message kaynağının clientAssignedMessageId alanının değerini ayarlar.

Yalnızca oluşturduğunuz mesajlara ad verebilirsiniz. Mevcut iletiler için özel kimlikleri adlandıramaz veya değiştiremezsiniz. Özel kimlik aşağıdaki koşulları karşılamalıdır:

  • client- ile başlar. Örneğin, client-custom-name geçerli bir özel kimliktir ancak custom-name geçerli değildir.
  • En fazla 63 karakter içerir ve yalnızca küçük harf, rakam ve kısa çizgi içerebilir.
  • Bir alan içinde benzersiz olmalıdır. Bir Chat uygulaması, farklı mesajlar için aynı özel kimliği kullanamaz.

Aşağıdaki kod, bir Chat uygulamasının kimlik içeren bir kısa mesajı kimliği doğrulanmış bir kullanıcı adına belirli bir alana nasıl gönderebileceğine dair bir örnek gösterir:

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 Komut Dosyası

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);
}

Bu örneği çalıştırmak için aşağıdakileri değiştirin:

  • SPACE_NAME: Alanın name alanındaki kimlik. Kimliği ListSpaces() yöntemini çağırarak veya alanın URL'sinden alabilirsiniz.
  • MESSAGE-ID: custom- ile başlayan mesajın adı. Belirtilen alanda Chat uygulaması tarafından oluşturulan diğer mesaj adlarından farklı olmalıdır.

Sorun giderme

Bir Google Chat uygulaması veya kartı hata döndürdüğünde Chat arayüzünde "Bir hata oluştu" mesajı gösterilir. veya "İsteğiniz işlenemiyor." Bazen Chat kullanıcı arayüzünde hata mesajı gösterilmez ancak Chat uygulaması veya kartı beklenmedik bir sonuç üretir. Örneğin, kart mesajı görünmeyebilir.

Chat kullanıcı arayüzünde hata mesajı gösterilmese de Chat uygulamaları için hata günlüğü kaydı etkinleştirildiğinde hataları düzeltmenize yardımcı olacak açıklayıcı hata mesajları ve günlük verileri kullanılabilir. Hataları görüntüleme, hataları ayıklama ve düzeltme konusunda yardım için Google Chat hatalarını giderme ve düzeltme başlıklı makaleyi inceleyin.