Espacio de nombres: microsoft.graph
Importante
Las API de la versión /beta de Microsoft Graph están sujetas a cambios. No se admite el uso de estas API en aplicaciones de producción. Para determinar si una API está disponible en la versión 1.0, use el selector de Versión.
Enviar un nuevo chatMessage en el chat especificado. Esta API no puede crear un nuevo chat; Debe usar el método List Chats para recuperar el identificador de un chat existente antes de crear un mensaje de chat.
Notas:
- No le recomendamos que utilice esta API para la migración de datos a través del flujo de mensajes de creación estándar. Para escenarios de migración de datos, utilice el flujo de importación de mensajes en su lugar.
- Usar Microsoft Teams como archivo de registro constituye una infracción de los términos de uso . Envía solo los mensajes que los usuarios leerán.
Esta API está disponible en las siguientes implementaciones en la nube nacional.
| Servicio global |
Administración pública de EE. UU. |
Gobierno de EE. UU. L5 (DOD) |
China operado por 21Vianet |
| ✅ |
✅ |
✅ |
✅ |
Permissions
Elija el permiso o los permisos marcados como con privilegios mínimos para esta API. Use uno o varios permisos con privilegios más altos solo si la aplicación lo requiere. Para obtener más información sobre los permisos delegados y de aplicación, consulte Tipos de permisos. Para obtener más información sobre estos permisos, consulte la referencia de permisos.
| Tipo de permiso |
Permisos con privilegios mínimos |
Permisos con privilegios más altos |
| Delegado (cuenta profesional o educativa) |
ChatMessage.Send |
Chat. ReadWrite, Group.ReadWrite.All |
| Delegado (cuenta personal de Microsoft) |
No admitida. |
No admitida. |
| Aplicación |
Teamwork.Migrate.All |
No disponible. |
Solicitud HTTP
POST /chats/{chat-id}/messages
| Nombre |
Descripción |
| Autorización |
{code} del portador. Necesario. |
Cuerpo de la solicitud
En el cuerpo de la solicitud, proporcione una representación JSON de un objeto chatMessage .
Respuesta
Si tiene éxito, este método devuelve un 201 Created código de respuesta y un nuevo objeto chatMessage en el cuerpo de la respuesta.
Ejemplos
Para obtener una lista más completa de ejemplos, consulte Crear chatMessage en un canal o un chat.
Ejemplo 1: Crear un chatMessage
Solicitud
En el ejemplo siguiente se muestra la solicitud.
POST https://graph.microsoft.com/beta/chats/19:2da4c29f6d7041eca70b638b43d45437@thread.v2/messages
Content-type: application/json
{
"body": {
"content": "Hello world"
}
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new ChatMessage
{
Body = new ChatMessageBody
{
Content = "Hello world",
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Chats["{chat-id}"].Messages.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewChatMessage()
body := graphmodels.NewChatMessageBody()
content := "Hello world"
body.SetContent(&content)
requestBody.SetBody(body)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Chats().ByChatId("chat-id").Messages().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ChatMessage chatMessage = new ChatMessage();
ChatMessageBody body = new ChatMessageBody();
body.setContent("Hello world");
chatMessage.setBody(body);
ChatMessage result = graphClient.chats().byChatId("{chat-id}").messages().post(chatMessage);
const options = {
authProvider,
};
const client = Client.init(options);
const chatMessage = {
body: {
content: 'Hello world'
}
};
await client.api('/chats/19:2da4c29f6d7041eca70b638b43d45437@thread.v2/messages')
.version('beta')
.post(chatMessage);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\ChatMessage;
use Microsoft\Graph\Beta\Generated\Models\ChatMessageBody;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ChatMessage();
$body = new ChatMessageBody();
$body->setContent('Hello world');
$requestBody->setBody($body);
$result = $graphServiceClient->chats()->byChatId('chat-id')->messages()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Teams
$params = @{
body = @{
content = "Hello world"
}
}
New-MgBetaChatMessage -ChatId $chatId -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.chat_message import ChatMessage
from msgraph_beta.generated.models.chat_message_body import ChatMessageBody
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ChatMessage(
body = ChatMessageBody(
content = "Hello world",
),
)
result = await graph_client.chats.by_chat_id('chat-id').messages.post(request_body)
Respuesta
En el ejemplo siguiente se muestra la respuesta.
HTTP/1.1 201 Created
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#chats('19%3A2da4c29f6d7041eca70b638b43d45437%40thread.v2')/messages/$entity",
"id": "1616991463150",
"replyToId": null,
"etag": "1616991463150",
"messageType": "message",
"createdDateTime": "2021-03-29T04:17:43.15Z",
"lastModifiedDateTime": "2021-03-29T04:17:43.15Z",
"lastEditedDateTime": null,
"deletedDateTime": null,
"subject": null,
"summary": null,
"chatId": "19:2da4c29f6d7041eca70b638b43d45437@thread.v2",
"importance": "normal",
"locale": "en-us",
"webUrl": null,
"channelIdentity": null,
"onBehalfOf": null,
"policyViolation": null,
"eventDetail": null,
"from": {
"application": null,
"device": null,
"conversation": null,
"user": {
"id": "8ea0e38b-efb3-4757-924a-5f94061cf8c2",
"displayName": "Robin Kline",
"userIdentityType": "aadUser"
}
},
"body": {
"contentType": "text",
"content": "Hello World"
},
"attachments": [],
"mentions": [],
"reactions": [],
"messageHistory": []
}
Ejemplo 2: Importar un mensaje
En el ejemplo siguiente se muestra cómo importar un mensaje. Para obtener más información, vea Importar mensajes a chats y canales de Microsoft Teams con Microsoft Graph.
Nota: El ámbito de permisos Teamwork.Migrate.All es necesario para este escenario. El chat de destino debe estar en modo de migración.
Solicitud
En el ejemplo siguiente se muestra cómo importar un mensaje en un chat en nombre de un usuario mediante las propiedades createdDateTime y from del cuerpo de la solicitud.
POST https://graph.microsoft.com/beta/chats/19:4b6bed8d24574f6a9e436813cb2617d8@thread.tacv2/messages
{
"createdDateTime": "2019-02-04T19:58:15.511Z",
"from": {
"user": {
"id": "8ea0e38b-efb3-4757-924a-5f94061cf8c2",
"displayName": "Robin Kline",
"userIdentityType": "aadUser"
}
},
"body": {
"contentType": "html",
"content": "Hello World"
}
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new ChatMessage
{
CreatedDateTime = DateTimeOffset.Parse("2019-02-04T19:58:15.511Z"),
From = new ChatMessageFromIdentitySet
{
User = new Identity
{
Id = "8ea0e38b-efb3-4757-924a-5f94061cf8c2",
DisplayName = "Robin Kline",
AdditionalData = new Dictionary<string, object>
{
{
"userIdentityType" , "aadUser"
},
},
},
},
Body = new ChatMessageBody
{
ContentType = BodyType.Html,
Content = "Hello World",
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Chats["{chat-id}"].Messages.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
"time"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewChatMessage()
createdDateTime , err := time.Parse(time.RFC3339, "2019-02-04T19:58:15.511Z")
requestBody.SetCreatedDateTime(&createdDateTime)
from := graphmodels.NewChatMessageFromIdentitySet()
user := graphmodels.NewIdentity()
id := "8ea0e38b-efb3-4757-924a-5f94061cf8c2"
user.SetId(&id)
displayName := "Robin Kline"
user.SetDisplayName(&displayName)
additionalData := map[string]interface{}{
"userIdentityType" : "aadUser",
}
user.SetAdditionalData(additionalData)
from.SetUser(user)
requestBody.SetFrom(from)
body := graphmodels.NewChatMessageBody()
contentType := graphmodels.HTML_BODYTYPE
body.SetContentType(&contentType)
content := "Hello World"
body.SetContent(&content)
requestBody.SetBody(body)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Chats().ByChatId("chat-id").Messages().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ChatMessage chatMessage = new ChatMessage();
OffsetDateTime createdDateTime = OffsetDateTime.parse("2019-02-04T19:58:15.511Z");
chatMessage.setCreatedDateTime(createdDateTime);
ChatMessageFromIdentitySet from = new ChatMessageFromIdentitySet();
Identity user = new Identity();
user.setId("8ea0e38b-efb3-4757-924a-5f94061cf8c2");
user.setDisplayName("Robin Kline");
HashMap<String, Object> additionalData = new HashMap<String, Object>();
additionalData.put("userIdentityType", "aadUser");
user.setAdditionalData(additionalData);
from.setUser(user);
chatMessage.setFrom(from);
ChatMessageBody body = new ChatMessageBody();
body.setContentType(BodyType.Html);
body.setContent("Hello World");
chatMessage.setBody(body);
ChatMessage result = graphClient.chats().byChatId("{chat-id}").messages().post(chatMessage);
const options = {
authProvider,
};
const client = Client.init(options);
const chatMessage = {
createdDateTime: '2019-02-04T19:58:15.511Z',
from: {
user: {
id: '8ea0e38b-efb3-4757-924a-5f94061cf8c2',
displayName: 'Robin Kline',
userIdentityType: 'aadUser'
}
},
body: {
contentType: 'html',
content: 'Hello World'
}
};
await client.api('/chats/19:4b6bed8d24574f6a9e436813cb2617d8@thread.tacv2/messages')
.version('beta')
.post(chatMessage);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\ChatMessage;
use Microsoft\Graph\Beta\Generated\Models\ChatMessageFromIdentitySet;
use Microsoft\Graph\Beta\Generated\Models\Identity;
use Microsoft\Graph\Beta\Generated\Models\ChatMessageBody;
use Microsoft\Graph\Beta\Generated\Models\BodyType;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ChatMessage();
$requestBody->setCreatedDateTime(new \DateTime('2019-02-04T19:58:15.511Z'));
$from = new ChatMessageFromIdentitySet();
$fromUser = new Identity();
$fromUser->setId('8ea0e38b-efb3-4757-924a-5f94061cf8c2');
$fromUser->setDisplayName('Robin Kline');
$additionalData = [
'userIdentityType' => 'aadUser',
];
$fromUser->setAdditionalData($additionalData);
$from->setUser($fromUser);
$requestBody->setFrom($from);
$body = new ChatMessageBody();
$body->setContentType(new BodyType('html'));
$body->setContent('Hello World');
$requestBody->setBody($body);
$result = $graphServiceClient->chats()->byChatId('chat-id')->messages()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Teams
$params = @{
createdDateTime = [System.DateTime]::Parse("2019-02-04T19:58:15.511Z")
from = @{
user = @{
id = "8ea0e38b-efb3-4757-924a-5f94061cf8c2"
displayName = "Robin Kline"
userIdentityType = "aadUser"
}
}
body = @{
contentType = "html"
content = "Hello World"
}
}
New-MgBetaChatMessage -ChatId $chatId -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.chat_message import ChatMessage
from msgraph_beta.generated.models.chat_message_from_identity_set import ChatMessageFromIdentitySet
from msgraph_beta.generated.models.identity import Identity
from msgraph_beta.generated.models.chat_message_body import ChatMessageBody
from msgraph_beta.generated.models.body_type import BodyType
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ChatMessage(
created_date_time = "2019-02-04T19:58:15.511Z",
from = ChatMessageFromIdentitySet(
user = Identity(
id = "8ea0e38b-efb3-4757-924a-5f94061cf8c2",
display_name = "Robin Kline",
additional_data = {
"user_identity_type" : "aadUser",
}
),
),
body = ChatMessageBody(
content_type = BodyType.Html,
content = "Hello World",
),
)
result = await graph_client.chats.by_chat_id('chat-id').messages.post(request_body)
Respuesta
En el ejemplo siguiente se muestra la respuesta.
HTTP/1.1 200 OK
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#chats('19%3A4b6bed8d24574f6a9e436813cb2617d8%40thread.tacv2')/messages/$entity",
"id": "1616991463150",
"replyToId": null,
"etag": "1616991463150",
"messageType": "message",
"createdDateTime": "2019-02-04T19:58:15.511Z",
"lastModifiedDateTime": null,
"deletedDateTime": null,
"subject": null,
"summary": null,
"chatId": "19:4b6bed8d24574f6a9e436813cb2617d8@thread.tacv2",
"importance": "normal",
"locale": "en-us",
"webUrl": null,
"channelIdentity": null,
"policyViolation": null,
"eventDetail": null,
"from": {
"application": null,
"device": null,
"conversation": null,
"user": {
"id": "8ea0e38b-efb3-4757-924a-5f94061cf8c2",
"displayName": "Robin Kline",
"userIdentityType": "aadUser"
}
},
"body": {
"contentType": "html",
"content": "Hello World"
},
"attachments": [],
"mentions": [],
"reactions": []
}