Forum Discussion
MohamedJ1410
Oct 01, 2024Copper Contributor
Using Graph API send individual message on Teams
Dear Team,
I need to send Microsoft Teams message individual using python and below is code.
import requests
# Step 1: Obtain Access Token
tenant_id = 'code'
client_id = 'code'
client_secret = 'code'
# Token endpoint
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
token_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# Token request data
token_data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': 'https://graph.microsoft.com/.default'
}
# Request token
token_response = requests.post(token_url, headers=token_headers, data=token_data)
if token_response.status_code == 200:
access_token = token_response.json().get('access_token')
print("Access token obtained:", access_token)
# Step 2: Send Message
user_id = 'email address removed for privacy reasons' # Replace with recipient's ID or email
message_url = f'https://graph.microsoft.com/v1.0/users/{user_id}/chatMessages'
message_body = {
"body": {
"content": "Hello! This is an automated message."
}
}
message_headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
# Send message
message_response = requests.post(message_url, json=message_body, headers=message_headers)
if message_response.status_code == 201:
print("Message sent successfully!")
else:
print("Error sending message:", message_response.status_code, message_response.text)
else:
print("Error obtaining token:", token_response.status_code, token_response.text)
I am getting below error
Error sending message: 405 {"error":{"code":"Request_BadRequest","message":"Specified HTTP method is not allowed for the request target."
No RepliesBe the first to reply