Nota: Se trata de una infracción de los términos de uso para usar Microsoft Teams como archivo de registro. Envíe solo mensajes que los usuarios leerán.
Elija el permiso o los permisos marcados como con privilegios mínimos para esta API. Use un permiso o permisos con privilegios superiores 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)
ChannelMessage.Send
Group.ReadWrite.All
Delegado (cuenta personal de Microsoft)
No admitida.
No admitida.
Aplicación
Teamwork.Migrate.All
No disponible.
Nota:
El permiso Group.ReadWrite.All solo se admite para la compatibilidad con versiones anteriores. Se recomienda actualizar las soluciones para usar un permiso alternativo enumerado en la tabla anterior y así evitar el uso de estos permisos en el futuro.
Los permisos de aplicación solo se admiten para la migración. En el futuro, Microsoft puede solicitarle a usted o a sus clientes que paguen tarifas adicionales en función de la cantidad de datos que se importen.
Solicitud HTTP
POST /teams/{team-id}/channels/{channel-id}/messages
Encabezados de solicitud
Nombre
Descripción
Autorización
{code} del portador. Necesario.
Tipo de contenido
application/json. Obligatorio.
Cuerpo de la solicitud
En el cuerpo de la solicitud, proporcione una representación JSON de un objeto chatMessage . Solo la propiedad body es obligatoria. Todas las demás propiedades son opcionales.
Respuesta
Si se ejecuta correctamente, este método devuelve un 201 Created código de respuesta y un nuevo objeto chatMessage en el cuerpo de la respuesta.
Ejemplos
Ejemplo 1: Creación de un mensaje en un canal especificado
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ChatMessage
{
Body = new ItemBody
{
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.Teams["{team-id}"].Channels["{channel-id}"].Messages.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewChatMessage()
body := graphmodels.NewItemBody()
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.Teams().ByTeamId("team-id").Channels().ByChannelId("channel-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();
ItemBody body = new ItemBody();
body.setContent("Hello World");
chatMessage.setBody(body);
ChatMessage result = graphClient.teams().byTeamId("{team-id}").channels().byChannelId("{channel-id}").messages().post(chatMessage);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ChatMessage;
use Microsoft\Graph\Generated\Models\ItemBody;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ChatMessage();
$body = new ItemBody();
$body->setContent('Hello World');
$requestBody->setBody($body);
$result = $graphServiceClient->teams()->byTeamId('team-id')->channels()->byChannelId('channel-id')->messages()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.chat_message import ChatMessage
from msgraph.generated.models.item_body import ItemBody
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ChatMessage(
body = ItemBody(
content = "Hello World",
),
)
result = await graph_client.teams.by_team_id('team-id').channels.by_channel_id('channel-id').messages.post(request_body)
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ChatMessage
{
CreatedDateTime = DateTimeOffset.Parse("2019-02-04T19:58:15.511Z"),
From = new ChatMessageFromIdentitySet
{
User = new Identity
{
Id = "id-value",
DisplayName = "Joh Doe",
AdditionalData = new Dictionary<string, object>
{
{
"userIdentityType" , "aadUser"
},
},
},
},
Body = new ItemBody
{
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.Teams["{team-id}"].Channels["{channel-id}"].Messages.PostAsync(requestBody);
// 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("id-value");
user.setDisplayName("Joh Doe");
HashMap<String, Object> additionalData = new HashMap<String, Object>();
additionalData.put("userIdentityType", "aadUser");
user.setAdditionalData(additionalData);
from.setUser(user);
chatMessage.setFrom(from);
ItemBody body = new ItemBody();
body.setContentType(BodyType.Html);
body.setContent("Hello World");
chatMessage.setBody(body);
ChatMessage result = graphClient.teams().byTeamId("{team-id}").channels().byChannelId("{channel-id}").messages().post(chatMessage);
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.chat_message import ChatMessage
from msgraph.generated.models.chat_message_from_identity_set import ChatMessageFromIdentitySet
from msgraph.generated.models.identity import Identity
from msgraph.generated.models.item_body import ItemBody
from msgraph.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 = "id-value",
display_name = "Joh Doe",
additional_data = {
"user_identity_type" : "aadUser",
}
),
),
body = ItemBody(
content_type = BodyType.Html,
content = "Hello World",
),
)
result = await graph_client.teams.by_team_id('team-id').channels.by_channel_id('channel-id').messages.post(request_body)
Ejemplo 3: Importación de mensajes con imágenes insertadas
Nota:
Actualmente, las imágenes insertadas son el único tipo de medio compatible con el esquema de la API de mensaje de importación.
Nota: El ámbito Teamwork.Migrate.All de permisos es necesario para este escenario.
Solicitud
En el ejemplo siguiente se muestra cómo importar mensajes back-in-time que contienen imágenes insertadas mediante las createDateTime claves y from en el cuerpo de la solicitud.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ChatMessage
{
CreatedDateTime = DateTimeOffset.Parse("2019-02-04T19:58:15.511Z"),
From = new ChatMessageFromIdentitySet
{
User = new Identity
{
Id = "id-value",
DisplayName = "John Doe",
AdditionalData = new Dictionary<string, object>
{
{
"userIdentityType" , "aadUser"
},
},
},
},
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "<div><div>\n<div><span><img height=\"250\" src=\"../hostedContents/1/$value\" width=\"176.2295081967213\" style=\"vertical-align:bottom; width:176px; height:250px\"></span>\n\n</div>\n\n\n</div>\n</div>",
},
HostedContents = new List<ChatMessageHostedContent>
{
new ChatMessageHostedContent
{
ContentBytes = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAANcAAAExCAYAAADvFzeeAAAXjklEQVR4Ae2d/XNU1RnH+9e0FFrA0RCIyaS8hRA0HV5KbS1gHRgVpjMClY4GHJ3yYm1HCmXaWttaaZUZtIIFKYi8lFAkvOQ9u5vN225IARVBbX9/Os9NbrLZbMjmhCfJPX5+2Lmb3T25y3O+n/M599x7w9f+++UXwoMakIF7n4GvUdR7X1RqSk01A8CFuZm5GGUAuIwKi72wF3ABF+YyygBwGRUWc2Eu4AIuzGWUAeAyKizmwlzABVyYyygDwGVUWMyFuYALuDCXUQaAy6iwmAtzARdwfWXMdeuzT+TGxz3Sfb1LunrapL07IW3pePDQ5/qavqef0c+OdYAELuAac4jGGkLL9rdvfyo9N9ODQAqBGmmrwGlb/R0u3xG4gMspOC5hG882CoRaaCSA8n1ff9doIQMu4PIOrus3u+8ZVNnw6e/Od5AALuDKOyz5hmqiPnfnzi1J9bSbgRWCpvvQfY307wQu4BoxJCOFaDK8rwsQmQsUIQhWW93XSIsewAVckYdLQ24F0Ui/926AARdwRRounZ6Np7GyYdN9DzdFBC7gijRc43GMlQ1U9s/6HXJNjYELuHI<<-----Removed----->>>>"),
ContentType = "image/png",
AdditionalData = new Dictionary<string, object>
{
{
"@microsoft.graph.temporaryId" , "1"
},
},
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Teams["{team-id}"].Channels["{channel-id}"].Messages.PostAsync(requestBody);
// 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("id-value");
user.setDisplayName("John Doe");
HashMap<String, Object> additionalData = new HashMap<String, Object>();
additionalData.put("userIdentityType", "aadUser");
user.setAdditionalData(additionalData);
from.setUser(user);
chatMessage.setFrom(from);
ItemBody body = new ItemBody();
body.setContentType(BodyType.Html);
body.setContent("<div><div>\n<div><span><img height=\"250\" src=\"../hostedContents/1/$value\" width=\"176.2295081967213\" style=\"vertical-align:bottom; width:176px; height:250px\"></span>\n\n</div>\n\n\n</div>\n</div>");
chatMessage.setBody(body);
LinkedList<ChatMessageHostedContent> hostedContents = new LinkedList<ChatMessageHostedContent>();
ChatMessageHostedContent chatMessageHostedContent = new ChatMessageHostedContent();
byte[] contentBytes = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAANcAAAExCAYAAADvFzeeAAAXjklEQVR4Ae2d/XNU1RnH+9e0FFrA0RCIyaS8hRA0HV5KbS1gHRgVpjMClY4GHJ3yYm1HCmXaWttaaZUZtIIFKYi8lFAkvOQ9u5vN225IARVBbX9/Os9NbrLZbMjmhCfJPX5+2Lmb3T25y3O+n/M599x7w9f+++UXwoMakIF7n4GvUdR7X1RqSk01A8CFuZm5GGUAuIwKi72wF3ABF+YyygBwGRUWc2Eu4AIuzGWUAeAyKizmwlzABVyYyygDwGVUWMyFuYALuDCXUQaAy6iwmAtzARdwfWXMdeuzT+TGxz3Sfb1LunrapL07IW3pePDQ5/qavqef0c+OdYAELuAac4jGGkLL9rdvfyo9N9ODQAqBGmmrwGlb/R0u3xG4gMspOC5hG882CoRaaCSA8n1ff9doIQMu4PIOrus3u+8ZVNnw6e/Od5AALuDKOyz5hmqiPnfnzi1J9bSbgRWCpvvQfY307wQu4BoxJCOFaDK8rwsQmQsUIQhWW93XSIsewAVckYdLQ24F0Ui/926AARdwRRounZ6Np7GyYdN9DzdFBC7gijRc43GMlQ1U9s/6HXJNjYELuHI<<-----Removed----->>>>");
chatMessageHostedContent.setContentBytes(contentBytes);
chatMessageHostedContent.setContentType("image/png");
HashMap<String, Object> additionalData1 = new HashMap<String, Object>();
additionalData1.put("@microsoft.graph.temporaryId", "1");
chatMessageHostedContent.setAdditionalData(additionalData1);
hostedContents.add(chatMessageHostedContent);
chatMessage.setHostedContents(hostedContents);
ChatMessage result = graphClient.teams().byTeamId("{team-id}").channels().byChannelId("{channel-id}").messages().post(chatMessage);