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

基于16.proactive-messages扩展:实现无交互主动发送群聊消息

机器人启动时主动发送群聊消息的实现方案

机器人初始化阶段无法直接获取所在的所有群聊——因为Teams等平台不会主动把群聊信息推送给机器人,只有当用户在群内和机器人产生交互(比如@机器人、发送消息),或者机器人被添加到群聊时,才能捕获到对应的会话信息。以下是可行的解决思路:

核心思路:提前存储并复用会话引用

1. 捕获并持久化群聊会话引用

当机器人被添加到群聊、或用户首次在群内与机器人交互时,从TurnContext中提取ConversationReference(包含群聊ID、服务URL等关键信息),并将其存储到数据库、缓存或配置文件中。

例如在处理成员添加事件或消息事件时:

@Override
protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
    // 获取当前会话引用
    ConversationReference ref = turnContext.getConversationReference();
    // 存储到自定义仓库(示例)
    conversationReferenceRepository.save(ref);
    
    // 原有消息处理逻辑
    return turnContext.sendActivity("收到消息!")
        .thenApply(sendResult -> null);
}

@Override
protected CompletableFuture<Void> onMembersAddedActivity(List<ChannelAccount> membersAdded, TurnContext turnContext) {
    // 当机器人被添加到群聊时,捕获会话引用
    for (ChannelAccount member : membersAdded) {
        if (member.getId().equals(turnContext.getActivity().getRecipient().getId())) {
            ConversationReference ref = turnContext.getConversationReference();
            conversationReferenceRepository.save(ref);
            return turnContext.sendActivity("我已加入群聊!")
                .thenApply(sendResult -> null);
        }
    }
    return CompletableFuture.completedFuture(null);
}

2. 启动时读取会话引用主动发消息

在SpringBoot的启动逻辑中(比如实现ApplicationRunner接口或使用@PostConstruct注解),读取存储的所有群聊会话引用,通过BotFrameworkAdapter的continueConversation方法主动发送消息。

示例代码:

@Component
public class BotStartupTask implements ApplicationRunner {

    private final BotFrameworkAdapter adapter;
    private final ConversationReferenceRepository conversationRepo;

    public BotStartupTask(BotFrameworkAdapter adapter, ConversationReferenceRepository conversationRepo) {
        this.adapter = adapter;
        this.conversationRepo = conversationRepo;
    }

    @Override
    public void run(ApplicationArguments args) {
        // 读取所有存储的群聊会话引用
        List<ConversationReference> groupConversations = conversationRepo.findAll();
        
        for (ConversationReference ref : groupConversations) {
            // 主动发送启动通知
            adapter.continueConversation(ref, turnContext -> {
                return turnContext.sendActivity("机器人已启动,随时为您服务!");
            });
        }
    }
}

注意事项

  • 若机器人是刚部署到新群聊且无任何交互记录,无法主动发送消息,必须等首次交互后才能捕获并存储会话引用。
  • 确保serviceUrl的有效性:Teams的服务URL可能会变动,建议每次交互时重新存储会话引用,避免因URL失效导致消息发送失败。
  • 权限配置:添加机器人到群聊时,需确认机器人拥有群聊内发送消息的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:15:33