You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Azure Bot Framework无需预安装向所有Teams群组发通知

解答

Microsoft Teams 出于安全和权限管控的底层设计,没有任何方法可以让未安装到目标群组的Bot直接发送主动消息,所有主动消息推送的前提都是Bot已被添加到对应会话(单聊/群组/团队)中,这是不可突破的平台规则。

如果你不想手动逐个为群组分配安装Bot,目前唯一的官方合规方案就是通过Graph API实现租户级的批量静默安装,具体落地逻辑可以结合你现有代码调整:

前置准备

  • 为Bot对应的Azure AD应用申请应用级Graph权限:TeamsAppInstallation.ReadWriteForTeam.All、Team.ReadBasic.All,申请后需要租户全局管理员完成权限同意
  • 确保你的Teams应用包已经上传到租户应用目录,设置为允许全局安装

逻辑调整步骤

  1. 先通过Graph API拉取租户内所有团队的ID列表,遍历列表为每个团队静默安装你的Bot应用,过程中同步存储每个团队对应的conversation_id、service_url这两个主动发消息的核心参数到你的数据库
  2. 你的_send_proactive_message方法需要从数据库读取存储的会话参数,结合Bot Framework的TurnContext构造逻辑来推送消息,这些参数不需要从notify接口的HTTP请求里获取,是提前预存的

调整后参考代码

from botbuilder.core import TurnContext, BotFrameworkAdapter, BotFrameworkAdapterSettings
from botbuilder.schema import Activity, ConversationParameters, ChannelAccount, ConversationReference

# 初始化Bot适配器,替换为你自己的Bot ID和密码
SETTINGS = BotFrameworkAdapterSettings("YOUR_BOT_ID", "YOUR_BOT_PASSWORD")
ADAPTER = BotFrameworkAdapter(SETTINGS)

def get_stored_group_conversations():
    # 从你的数据库读取提前存储的所有群组会话参数
    # 返回结构示例:[{"conversation_id": "xxx", "service_url": "xxx"}, ...]
    return []

async def _send_proactive_message(data):
    group_conversations = get_stored_group_conversations()
    for conv in group_conversations:
        async def callback(turn_context: TurnContext):
            await turn_context.send_activity(data.get("message_content", "默认通知内容"))
        
        # 调用适配器构造主动会话上下文推送消息
        await ADAPTER.continue_conversation(
            conversation_reference=ConversationReference(
                conversation=ChannelAccount(id=conv["conversation_id"]),
                service_url=conv["service_url"]
            ),
            callback=callback,
            bot_id="YOUR_BOT_ID"
        )

async def notify(req: Request) -> Response: 
   body = await req.json()
   await _send_proactive_message(body)
   return Response(status=HTTPStatus.OK, text="Proactive messages have been sent")

APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/notify", notify)

内容的提问来源于stack exchange,提问作者EtherealNP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 23:36:03