how to access teams group chat messages using graph api

Nathan V 45 Reputation points
2025-06-09T10:51:18.8666667+00:00

Hello all ,

I am currently working with Microsoft Graph API to fetch Teams chat data. I am successfully able to:

Retrieve one-on-one (individual) chat conversations

Access channel messages

However, I am unable to retrieve both the list of group chats and their messages. I have explored the documentation, but could not find a clear example or endpoint that allows access to:

Listing all group chats

Retrieving messages within those group chats

Could you please help clarify the required permissions, API endpoints, or any sample documentation that supports this functionality?

Looking forward to your guidance.

Microsoft Teams | Development
Microsoft Teams | Development

Building, integrating, or customizing apps and workflows within Microsoft Teams using developer tools and APIs


2 answers

Sort by: Most helpful
  1. Nathan V 45 Reputation points
    2025-06-11T13:30:40.6433333+00:00

    Hi @Gabriel-N

    can you please share me the python version of powershell script you shared,I tried converting it using an AI tool, but it didn't work as expected. Having a Python version would be very helpful.

    Also, I attempted using the interactive token-based approach with the following function:

    def get_access_token_interactive(client_id, tenant_id, scopes):
        """
        Get an access token using delegated permissions (interactive user login) via MSAL.
        """
        authority = f"https://login.microsoftonline.com/{tenant_id}"
        app = msal.PublicClientApplication(client_id, authority=authority)
        accounts = app.get_accounts()
        if accounts:
            result = app.acquire_token_silent(scopes, account=accounts[0])
            if result and 'access_token' in result:
                return result['access_token']
        # Interactive login
        result = app.acquire_token_interactive(scopes)
        if 'access_token' in result:
            return result['access_token']
        else:
            print("Failed to obtain access token interactively.")
            print(result.get('error_description'))
            return None
    def find_group_chat_by_name(access_token, group_chat_name): 
        """
        Find a group chat by its name from the signed-in user's chats and return its chat ID.
        """
        url = "https://graph.microsoft.com/v1.0/me/chats?$filter=chatType eq 'group'"
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }
        response = requests.get(url, headers=headers)
        if response.status_code != 200:
            print(f"Error fetching group chats: {response.status_code}")
            print(response.text)
            return None
        chats = response.json().get('value', [])
        for chat in chats:
            if chat.get('topic', '').lower() == group_chat_name.lower():
                return chat['id']
    
      
    

    This approach works perfectly fine in a local environment. Initially, it opens a browser window and displays the message 'Authenticated successfully, you can close this window now,' after which it successfully retrieves the messages from the group chat. However, in GitHub Actions, GUI-based (interactive) authentication is not supported, so this method cannot be used in that environment.

    Was this answer helpful?


  2. Gabriel-N 20,675 Reputation points Microsoft External Staff Moderator
    2025-06-09T13:17:58.5833333+00:00

    Hi Nathan V

    Thanks so much for posting your question in the Microsoft Q&A forum! 

    I noticed that some other users have already shared helpful documentation and suggestions to guide you through accessing Teams group chat messages using the Graph API. That’s great to see! 

    Since I currently don’t have access to a full testing environment, I can’t verify everything firsthand but I’d still love to help. I’d recommend trying the following PowerShell script using the Microsoft Graph SDK. It’s designed to: 

    • Connect to Microsoft Graph 
    • Retrieve all group chats 
    • Filter messages by a specific date range 
    • Handle potential errors (like chats with no messages) 
    • Export the results to a CSV file 

    Just a quick note: the Microsoft Graph SDK is very similar to the Graph API, it essentially wraps the API calls in a more developer-friendly way, making it easier to work with in PowerShell or other supported languages. 

    Hopefully, this approach will help you move forward and resolve the issue. 

    # Set your date range
    $startDate = Get-Date "2024-01-01"
    $endDate = Get-Date "2025-01-01"
    $exportPath = "$env:USERPROFILE\\Desktop\\TeamsGroupChatMessages.csv"
    # Install and import Microsoft Graph module
    Install-Module Microsoft.Graph -Scope CurrentUser -Force
    Import-Module Microsoft.Graph
    # Connect to Microsoft Graph
    Connect-MgGraph -Scopes "Chat.Read.All"
    # Prepare output list
    $allMessages = @()
    # Get all group chats
    $groupChats = Get-MgChat -All | Where-Object { $_.ChatType -eq "group" }
    foreach ($chat in $groupChats) {
        Write-Host "Processing Chat: $($chat.Topic) [$($chat.Id)]"
        try {
            $messages = Get-MgChatMessage -ChatId $chat.Id -Top 50
            $hasMessages = $false
            while ($messages) {
                foreach ($msg in $messages.Value) {
                    $msgDate = Get-Date $msg.CreatedDateTime
                    if ($msgDate -ge $startDate -and $msgDate -le $endDate) {
                        $sender = $msg.From?.User?.DisplayName
                        $content = $msg.Body?.Content
                        $allMessages += [PSCustomObject]@{
                            "Chat ID"         = $chat.Id
                            "Chat Topic"      = $chat.Topic
                            "Sender"          = $sender
                            "Message Date"    = $msgDate
                            "Message Content" = $content
                        }
                        $hasMessages = $true
                    }
                }
                if ($messages.'@odata.nextLink') {
                    $messages = Invoke-MgGraphRequest -Method GET -Uri $messages.'@odata.nextLink'
                } else {
                    $messages = $null
                }
            }
            if (-not $hasMessages) {
                Write-Host "No messages found in this chat within the specified date range."
            }
        } catch {
            Write-Warning "Failed to retrieve messages for chat $($chat.Id): $_"
        }
        Write-Host "`n===================================`n"
    }
    # Export to CSV
    if ($allMessages.Count -gt 0) {
        $allMessages | Sort-Object "Chat ID", "Message Date" | Export-Csv -Path $exportPath -NoTypeInformation -Encoding UTF8
        Write-Host "Messages exported to: $exportPath"
    } else {
        Write-Host "No messages matched the filters."
    }
     
    
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".  

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.  

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.