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

如何让Python版Azure Bot仅回复Teams主帖而非线程消息?

解决Teams Bot仅回复主帖而非线程消息的问题

问题背景

已基于Python开发Azure Bot,用于在Teams频道中针对特定关键词自动回复,但Bot会持续回复线程中含关键词的消息,希望仅对主帖回复一次,此前尝试区分主帖与线程的代码未生效。

解决方案

核心是通过判断消息的reply_to_id属性和Teams频道专属标识,过滤掉线程回复,只处理频道主帖。以下是修正后的完整代码:

import logging
from botbuilder.core import ActivityHandler, TurnContext

# 配置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

class MyBot(ActivityHandler):
    
    async def on_message_activity(self, turn_context: TurnContext):
        # 仅处理Microsoft Teams频道消息
        if turn_context.activity.channel_id != 'msteams':
            return
        
        # 仅处理频道类型的会话(排除私人聊天/群聊)
        if turn_context.activity.conversation.conversation_type != 'channel':
            return
        
        # 若消息存在reply_to_id,说明是线程回复,直接跳过
        if turn_context.activity.reply_to_id:
            logger.info("检测到线程消息,跳过处理")
            return
        
        # 处理主帖消息的关键词匹配逻辑
        user_message_lower = turn_context.activity.text.lower()
        
        lock_keywords = ['locked', 'unlock', 'blocked', 'locking', 'lock', 'login', 'connect', 'vpn']
        password_keywords = ['password', 'expired', 'credentials']
        duo_keywords = ['duo', '2fa']
        
        if any(word in user_message_lower for word in lock_keywords):
            response_message = (
                "Hi,\n\n"
                "If you are enrolled to SSPR you can now unlock yourself with this link:\n"
                "https://confluence.infobip.com/display/CWT/Self+service+password+reset+-+add+additional+sign-in+method\n\n"
                "If you are not enrolled, here is the link to enroll:\n"
                "https://confluence.infobip.com/display/CWT/Self+service+password+reset+-+add+additional+sign-in+method\n\n"
                "If it helped, write resolved,   if not, write help"
            )
            await turn_context.send_activity(response_message)
        
        if any(word in user_message_lower for word in password_keywords):
            await turn_context.send_activity("If your password is expired you can reset it using this link: https://account.activedirectory.windowsazure.com/ChangePassword.aspx")
        
        if any(word in user_message_lower for word in duo_keywords):
            await turn_context.send_activity("If you need to re-enroll in DUO 2FA, please raise a ticket here: https://jira.infobip.com/")

关键逻辑说明

  • 频道过滤:通过channel_id != 'msteams'和conversation_type != 'channel'确保只处理Teams频道内的消息,排除私人聊天、群聊场景。
  • 线程消息识别:Teams中线程回复的消息会携带reply_to_id属性(指向主帖的ID),通过判断该属性是否存在,直接跳过线程消息的处理。
  • 关键词匹配:保留原有大小写不敏感的关键词匹配逻辑,仅对主帖执行回复操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:37:42