As per MS Graphapi document, ChannelMessage.Send permission is available only for delegated and not available as application permission.
Since we have to use delegated permission to send the message to MS teams, so we have to authenticate with an user first to use the GraphAPI for sending the message to teams channel, I am trying to achieve it from programmatically, below is the code snippet
from azure.identity import ClientSecretCredential
from msgraph import GraphServiceClient
from msgraph.generated.models.chat_message import ChatMessage
from msgraph.generated.models.item_body import ItemBody
#from azure.identity import DeviceCodeCredential
import os
import asyncio
client_id = os.environ["clientid"]
client_secret = os.environ["clientsecret"]
tenant_id = os.environ["tenenatid"]
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret,
)
async def send_message():
scopes = ['https://graph.microsoft.com/.default']
client = GraphServiceClient(credentials=credential, scopes=scopes)
print(client)
request_body = ChatMessage(
body = ItemBody(
content = "Hello World",
),
)
channel_id = os.environ["channel_id"]
team_id = os.environ["team_id"]
result = await client.teams.by_team_id(team_id).channels.by_channel_id(channel_id).messages.post(request_body)
if result:
print(result)
if __name__ == "__main__":
asyncio.run(send_message())
If I use ClientSecretCredential for credentials then throwing an error
msgraph.generated.models.o_data_errors.o_data_error.ODataError:
APIError
Code: 401
message: None
error: MainError(additional_data={}, code='Unauthorized', details=None, inner_error=InnerError(additional_data={}, client_request_id='xxxxxx-412e-4493-xxxx-ccd3667dxxxx', date=DateTime(2024, 9, 20, 10, 58, 16, tzinfo=Timezone('UTC')), odata_type=None, request_id='xxxxxx-da73-4457-xxxx-ee9ea940xxxx'), 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.', target=None)
If I use DeviceCodeCredential for credentials then it asks to To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXX to authenticate. After Authentication, send message to teams was successful.
I would need your help on how can I send the message to teams channel programmatically without signing into browser