How to use python to create a teams chat - How to fix the MainError(additional_data={}, code='Forbidden' error ?

Michael Wilcox 26 Reputation points
2024-12-21T18:13:34.3233333+00:00

I am trying to create a team's chat using python.

Here is the error I am receiving:

error: MainError(additional_data={}, code='Forbidden', details=None, inner_error=InnerError(additional_data={}, client_request_id='fe80e2cc-28d3-4593-9091-41aaf7f79c35', date=DateTime(2024, 12, 21, 17, 50, 49, tzinfo=Timezone('UTC')), odata_type=None, request_id='6db83fa7-e6f6-48bf-913b-6d89854a4c0e'), message="Missing scope permissions on the request. API requires one of 'Chat.Create, Chat.ReadWrite'. Scopes on the request 'User.Read, profile, openid, email'", target=None)

Here is my code:

import asyncio
from msgraph import GraphServiceClient
from msgraph.generated.models.chat import Chat
from msgraph.generated.models.chat_type import ChatType
from msgraph.generated.models.conversation_member import ConversationMember
from msgraph.generated.models.aad_user_conversation_member import AadUserConversationMember
from azure.identity import DeviceCodeCredential

# Multi-tenant apps can use "common",
# single-tenant apps must use the tenant ID from the Azure portal
# tenant_id = 'common'
tenant_id = "<ID>"

# Values from app registration
client_id = "lient_id = "ID "
client_secret = "secret "
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python

scopes = ['User.Read']

# azure.identity
credential = DeviceCodeCredential(
    tenant_id=tenant_id,
    client_id=client_id)

graph_client = GraphServiceClient(credential, scopes)


request_body = Chat(
	chat_type = ChatType.OneOnOne,
	members = [
		AadUserConversationMember(
			odata_type = "#microsoft.graph.aadUserConversationMember",
			roles = [
				"owner",
			],
			additional_data = {
					"user@odata_bind" : "https://graph.microsoft.com/v1.0/users('cefbd6a0-4b6d-4608-bec8-43fd0ea705a6')",
			}
		),
		AadUserConversationMember(
			odata_type = "#microsoft.graph.aadUserConversationMember",
			roles = [
				"owner",
			],
			additional_data = {
					"user@odata_bind" : "https://graph.microsoft.com/v1.0/users('cefbd6a0-4b6d-4608-bec8-43fd0ea705a6')",
			}
		),
	],
)
# result = await graph_client.chats.post(request_body)
# result = graph_client.chats.post(request_body)

loop = asyncio.get_event_loop()
result = loop.run_until_complete( graph_client.chats.post(request_body))
loop.close()

print (result)
Microsoft Teams
Microsoft Teams
A Microsoft customizable chat-based workspace.
10,895 questions
{count} votes

Your answer

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