根据 MS Graphapi 文档,ChannelMessage.Send 权限仅适用于委派,不可作为应用程序权限使用。
由于我们必须使用委派权限将消息发送到 MS 团队,因此我们必须首先对用户进行身份验证,才能使用 GraphAPI 将消息发送到团队频道,我尝试以编程方式实现它,下面是代码片段
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())
如果我使用 ClientSecretCredential 作为凭据,则会抛出错误
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)
如果我使用 DeviceCodeCredential 作为凭据,则它会要求登录,使用 Web 浏览器打开页面 https://microsoft.com/devicelogin 并输入代码 XXXXXX 进行身份验证。身份验证后,向团队发送消息成功。
我需要您的帮助,了解如何在不登录浏览器的情况下以编程方式将消息发送到团队频道
根据在频道或聊天中发送聊天消息,引用
应用程序权限仅支持迁移。在 将来,Microsoft 可能会要求您或您的客户付费 根据导入的数据量收取额外费用。
您需要用户上下文才能发送消息。即使它是机器人,也需要用户身份验证,因为您只能使用委派的权限。
请注意,设备代码流程是用户交互流程