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

如何在Python版MS Teams Bot中向指定用户发送无交互通知

使用Bot Framework SDK (Python) 实现MS Teams Bot主动向指定用户发送通知

前提条件

  • 已完成Bot基础开发并部署至Teams,持有Bot的Microsoft App ID和Microsoft App Password
  • 已获取并存储目标用户的Teams User ID(可通过用户首次交互时的turn_context.activity.from_property.id获取,或通过Graph API查询)

1. 初始化Bot连接器客户端

先配置Bot身份信息,创建用于发送消息的适配器和连接器客户端:

from botbuilder.core import BotFrameworkAdapter, BotFrameworkAdapterSettings
from botbuilder.schema import Activity, ChannelAccount, ConversationAccount

# 替换为你的Bot凭据
APP_ID = "你的Microsoft App ID"
APP_PASSWORD = "你的Microsoft App Password"

adapter_settings = BotFrameworkAdapterSettings(APP_ID, APP_PASSWORD)
adapter = BotFrameworkAdapter(adapter_settings)

2. 构建通知消息结构

构造符合Teams规范的消息Activity,指定接收用户和内容:

def create_notification_activity(user_id: str, message: str) -> Activity:
    return Activity(
        type="message",
        recipient=ChannelAccount(id=user_id),
        from_property=ChannelAccount(id=APP_ID),
        conversation=ConversationAccount(id=user_id),  # Teams中用户ID可直接作为会话ID用于主动消息
        text=message,
        channel_id="msteams"
    )

3. 发送主动通知

编写异步方法发送消息,处理可能的异常:

async def send_notification_to_user(user_id: str, message: str):
    try:
        activity = create_notification_activity(user_id, message)
        # 创建连接器客户端并发送消息
        connector_client = adapter.create_connector_client(activity.service_url)
        await connector_client.conversations.send_to_conversation(activity.conversation.id, activity)
        print(f"通知已成功发送至用户 {user_id}")
    except Exception as e:
        print(f"发送失败: {str(e)}")

# 调用示例
if __name__ == "__main__":
    import asyncio
    target_user_id = "目标用户的Teams User ID"
    notification_content = "您有一份待提交的调查问卷。"
    asyncio.run(send_notification_to_user(target_user_id, notification_content))

关键注意事项

  • Service URL获取:如果未存储用户的service_url,可通过Microsoft Graph API查询用户的会话信息,或在用户首次与Bot交互时记录turn_context.activity.service_url并与user_id关联存储
  • 权限配置:确保Bot的应用注册已添加ChannelMessage.Send权限,且Bot已被目标用户添加(或管理员批量安装至Teams租户)
  • 异步要求:Bot Framework SDK的核心方法均为异步,需通过asyncio框架运行发送逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:39:57