I am trying to use Microsoft Graph API to post a message to teams channel using SDK, I have registered an APP in Microsoft Azure, for Delegated permission, added ChannelMessage.Send and for Application permission added Teamwork.Migrate.All as per the MS documentaion - https://learn.microsoft.com/en-us/graph/api/chatmessage-post?view=graph-rest-1.0&tabs=http
I am able to fetch the token of the App (From get_access_token()) and while sending a message to one of the teams channel (get_access_token) getting failed response with below message:
{'error': {'code': 'Unauthorized', 'message': 'Message POST is allowed in application-only context only for import purposes. Refer to Import External Platform Messages - Teams for more details.', 'innerError': {'date': '2024-09-10T14:04:38', 'request-id': '1e8cd9e8-abcd-4f92-a3e8-xxxxxxxxx', 'client-request-id': '1e8cd9e8-abcd-4f92-a3e8-xxxxxxxxx'}}}
Below is the code to fetch the token by passing the registered app client id & secrets
def get_access_token():
url =f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
payload = {
"grant_type": "client_credentials", #"client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": "https://graph.microsoft.com/.default"
}
response = requests.post(url, data=payload)
response_data = response.json()
print(response_data)
access_token = response_data['access_token']
#print(access_token)
return access_token
Below is the code to send the message with my teams & channel IDs
def send_message():
endpoint_url = f"https://graph.microsoft.com/v1.0/teams/{team_id}/channels/{channel_id}/messages"
access_token = get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
request_body= {
"body": {
"content": "Hello world"
}
}
response = requests.post(endpoint_url, headers=headers, data=json.dumps(request_body))
print(response.status_code)
print(response.json())
Response after executing this code
401
{'error': {'code': 'Unauthorized', 'message': 'Message POST is allowed in application-only context only for import purposes. Refer to https://docs.microsoft.com/microsoftteams/platform/graph-api/import-messages/import-external-messages-to-teams for more details.', 'innerError': {'date': '2024-09-12T13:57:54', 'request-id': '60bd5cfb-xxxx-4bea-ba58-xxxxxxxxx', 'client-request-id': '60bd5cfb-xxxx-4bea-ba58-xxxxxxxx'}}}
Seeking help to achieve this use case