MS Teams – Chats – Get Chat Messages

Estimated reading: 6 minutes

MS Teams – Chats – Get Chat Messages

Get a list of messages in a chat.

Action details

PropertyValue
Action labelMS Teams – Chats – Get Chat Messages
CategoryCloudTools
Apex class and methodGetMSTeamsChatMessages.getChatMessages
Input typeGetMSTeamsChatMessages.GetMSTeamsChatMessagesInput
Output typeList<List<MSTeamsChatMessage>>
AuthorizationMicrosoft 365 connector; check endpoint support for delegated and application access.
Microsoft Graph requestGET /chats/{chatId}/messages

Prerequisites and permissions

Configure a CloudTools Connector with Connector Type set to Microsoft 365. Complete Microsoft sign-in for OAuth Delegated (Authorization Code). For endpoints supporting OAuth Application (Client Credentials), grant application permissions and administrator consent. The identity must have access to the selected resource. See Creating an Entra ID App and Integration Connectors for setup.

The action permission provider declares these alternatives; they are not cumulative requirements and not all are least privileged. Resource-specific permissions require consent for the relevant Teams resource.

Permission typeDeclared alternatives
DelegatedChat.Read, Chat.ReadWrite
ApplicationChatMessage.Read.Chat, Chat.Read.All, Chat.ReadWrite.All

Endpoints: /chats/{chat-id}/messages. ChatMessage.Read.Chat requires resource-specific consent.

See the Microsoft operation and permissions reference.

Inputs

InputApex fieldTypeRequiredDescription
User IduserIdStringNoOptional user identifier for delegated authorization code flow
Chat IdchatIdStringYesMS Teams chat identifier
ToptopQueryStringNoMax number of messages to return
Order ByorderByQueryStringNoOData order expression (for example: lastModifiedDateTime desc)
FilterfilterQueryStringNoOData filter expression (for example: lastModifiedDateTime gt 2019-11-04T19:23:53.304Z)

Supply a nonempty list with a non-null first request. This implementation processes only the first request and does not bulk-process Flow interviews. Global inputs do not expose connectorId; Flow and subscriber Apex use CloudTools connector selection. Use Microsoft Graph IDs, not Salesforce IDs or browser links. Resolve dynamic values before invoking this action.

Outputs

Returns an outer list containing one collection of MSTeamsChatMessage items. A missing or unmappable collection produces an empty inner list. The outer list does not correspond to every input request.

OutputApex fieldTypeDescription
IdidStringUnique identifier of the message
Chat IdchatIdStringIdentifier of the chat that contains the message
Created Date TimecreatedDateTimeStringCreated timestamp for the message
Deleted Date TimedeletedDateTimeStringDeleted timestamp for the message
ETageTagStringVersion number of the message
ImportanceimportanceStringImportance of the message
Last Modified Date TimelastModifiedDateTimeStringLast modified timestamp for the message
Last Edited Date TimelastEditedDateTimeStringLast edited timestamp for the message
LocalelocaleStringLocale for the message
Message TypemessageTypeStringType of the message
Reply To IdreplyToIdStringIdentifier of the parent/root message
SubjectsubjectStringSubject of the message
SummarysummaryStringSummary text for the message
Web URLwebUrlStringLink to the message in Teams
BodybodyMSTeamsMessageBodyContent body of the message
FromfromIdentityMSTeamsMessageFromIdentitySetSender identity set for the message
Channel IdentitychannelIdentityMSTeamsMessageChannelIdentityChannel identity for channel messages
AttachmentsattachmentsList<MSTeamsMessageAttachment>Attachments associated with the message
MentionsmentionsList<MSTeamsMessageMention>Mentions included in the message
Message HistorymessageHistoryList<MSTeamsMessageHistoryItem>History items for message activities
ReactionsreactionsList<MSTeamsMessageReaction>Reactions for the message
Hosted ContentshostedContentsList<MSTeamsMessageHostedContent>Hosted contents for the message
Policy ViolationpolicyViolationMSTeamsMessagePolicyViolationPolicy violation details for the message
Event DetaileventDetailMSTeamsMessageEventDetailEvent detail for event messages
RepliesrepliesList<MSTeamsChatMessage>Replies for this message
OData TypeodataTypeStringOData type for the message
OData ETagodataEtagStringOData ETag for the message
Additional PropertiesadditionalPropertiesList<DynamicObject>Additional properties from user-defined query

Behavior and limits

Only the returned value collection is mapped; this action does not follow or expose @odata.nextLink. A result may contain only the first page.

Nonblank query values are forwarded to Microsoft. Query support and syntax depend on the endpoint; the connector does not make unsupported OData options valid.

Use in Flow

Add MS Teams – Chats – Get Chat Messages where supported. Use a Microsoft 365 application connector configured as Set as default for Flow automations only if the endpoint supports the required application operation. Delegated connections are not supported for CloudTools Flow automation. Supply required values, retain outputs, and add fault handling.

Use in custom Apex

This subscriber-org example uses the Apptigent namespace. Replace example identifiers and values before use. Configure the connector, arrange authorization first, run in a context permitting callouts, and handle exceptions and empty results.

Apptigent.GetMSTeamsChatMessages.GetMSTeamsChatMessagesInput request =
    new Apptigent.GetMSTeamsChatMessages.GetMSTeamsChatMessagesInput();
request.userId = 'd7b45f12-8a16-4a1f-95f1-dfde7f2af91b';
request.chatId = '19:1c5b01696d2e4a179c292bc9cf04e63b@thread.v2';
request.topQuery = '10';
request.orderByQuery = 'lastModifiedDateTime desc';
request.filterQuery = 'lastModifiedDateTime gt 2019-11-04T19:23:53.304Z';

List<List<Apptigent.MSTeamsChatMessage>> results =
    Apptigent.GetMSTeamsChatMessages.getChatMessages(
        new List<Apptigent.GetMSTeamsChatMessages.GetMSTeamsChatMessagesInput>{ request }
    );
System.debug(results);

Use in a Lightning Web Component

Use getMSTeamsChatMessages from msTeamsConnectorLib through MSTeamsConnectorController. Set request.connectorId to select a configured connector. These c/ imports apply in the same namespace. The controller uses a shared request DTO; its field names differ from the global invocable input.

Global inputLWC request mapping
userIdrequest.userId
chatIdrequest.chatId
topQueryrequest.topQuery

The shared controller DTO does not expose these global inputs: orderByQuery, filterQuery. Adding them as arbitrary properties to request does not make them reach the action. Use global Apex/Flow for those inputs where authorization permits.

teamsActionExample.js

import { LightningElement } from 'lwc';
import { getMSTeamsChatMessages } from 'c/msTeamsConnectorLib';

export default class TeamsActionExample extends LightningElement {
    result = null;
    errorMessage = '';
    isRunning = false;
    completed = false;

    async handleRun() {
        if (this.isRunning || this.completed) return;
        this.isRunning = true;
        this.errorMessage = '';
        try {
            const request = { connectorId: 'REPLACE_WITH_CONNECTOR_RECORD_ID' };
            request.userId = 'd7b45f12-8a16-4a1f-95f1-dfde7f2af91b';
            request.chatId = '19:1c5b01696d2e4a179c292bc9cf04e63b@thread.v2';
            request.topQuery = '10';
            this.result = await getMSTeamsChatMessages(request);
            this.completed = true;
        } catch (error) {
            this.errorMessage = error.requiresInteractiveAuthorization
                ? 'Sign in to Microsoft for the connector, then try again.'
                : error.message || 'The Teams action failed.';
        } finally {
            this.isRunning = false;
        }
    }
}

teamsActionExample.html

<template>
    <lightning-button label="Run action" onclick={handleRun}
        disabled={isRunning}></lightning-button>
    <p role="alert">{errorMessage}</p>
</template>

The library resolves to an array of mapped objects. rawJson serializes the mapped Apex model rather than the untouched Microsoft response. Message body, membership roles, and nested properties can be flattened or serialized in JavaScript DTOs.

Use getMSTeamsAuthorizationState, beginMSTeamsAuthorization, and createMSTeamsOAuthMessageHandler to arrange delegated sign-in. The library normalizes errors but does not automatically sign in or retry. Reset completed for a new deliberate operation. Inspect resource state before retrying a mutation with an uncertain outcome.

Error handling and troubleshooting

SymptomWhat to check
Required fields errorSupply a nonempty request list, a non-null first request, and required or conditionally required values. For LWC, check controller mappings.
Authorization or access deniedCheck selected connector, delegated versus application support, consent, Teams app installation where required, and access to the resource.
Resource not foundCheck team, channel, chat, message, membership, and app installation IDs; these are distinct identifiers.
Missing dataCheck pagination, query support, empty-response behavior, and documented model mapping.
Operation rejectedInspect the Microsoft error, endpoint restrictions, supported properties, message authorization limits, and notification configuration.

See Teams connector introduction.

Share this Doc

MS Teams – Chats – Get Chat Messages

Or copy link

CONTENTS

Free eBook: The Ultimate Guide to Power Platform Custom Connectors

Antimanual

Ask our AI support assistant your questions about our platform, features, and services.

You are offline
Chatbot avatar
What can I help you with?

Subscribe

×
Cancel