团队Invoke_Response被团队拒绝吗?

发布于 2025-01-24 14:01:25 字数 554 浏览 4 评论 0原文

我有一个在独立服务器上运行的Teams应用程序,其中包含Azurebot设置,用于该应用程序上的消息扩展。我有一个类实施消息处理扩展团队施法者的班级,这一切似乎都在起作用。问题是当我来回应InvokerSponse时。我将其放入具有正确类型的活动中,我没有错误,但是团队似乎拒绝了该消息,因为它没有为我提供包含响应的帖子请求的ID。创建活动时我缺少一些东西吗?

async def handle(turn_context):

    invoke_response = await message_handler.on_invoke_activity(turn_context)

    # invoke_response is an instance of botbuilder.schema._models_py3.InvokeResponse

    result = await turn_context.send_activity(Activity(type=ActivityTypes.invoke_response, value=invoke_response))

    self.logger.info(result)

I have a teams app running on a standalone server with an AzureBot setup for message extensions on the app. I've got a class implementing message handling extending TeamsActivityHandler which all seems to be working. The issue is when I come to respond with an InvokeResponse. I place this into an activity with the right type, I get no errors but Teams seems to be rejecting the message as it doesn't give me an ID for the POST request containing the response. Is there something I'm missing when creating the Activity?

async def handle(turn_context):

    invoke_response = await message_handler.on_invoke_activity(turn_context)

    # invoke_response is an instance of botbuilder.schema._models_py3.InvokeResponse

    result = await turn_context.send_activity(Activity(type=ActivityTypes.invoke_response, value=invoke_response))

    self.logger.info(result)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贵在坚持 2025-01-31 14:01:25

我完全没有意识到,消息扩展遵循标准请求响应模型,而不是像机器人一样的请求模型。这是一个完整的工作示例,使用烧瓶-MS示例在这里

import asyncio
import json

from botbuilder.core.teams import TeamsActivityHandler
from botbuilder.schema import Activity, CardAction, HeroCard

from botbuilder.core import (
    BotFrameworkAdapter,
    BotFrameworkAdapterSettings, TurnContext, CardFactory, MessageFactory,
)

from botbuilder.schema.teams import (
    MessagingExtensionAttachment,
    MessagingExtensionQuery,
    MessagingExtensionResult,
    MessagingExtensionResponse,

)

from flask import request, Response
from flask_restful import Resource


class ActivityHandler(TeamsActivityHandler):

    async def on_teams_messaging_extension_query(self, turn_context: TurnContext, query: MessagingExtensionQuery):
        search_query = str(query.parameters[0].value).strip()
        if search_query == '':
            await turn_context.send_activity(
                MessageFactory.text('You cannot enter a blank string for the search')
            )
            return
       
        # TODO: Implement a search returning objects
        search_results = self._get_search_results(search_query)
   
        attachments = []
        for obj in search_results:
            hero_card = HeroCard(
                title=obj['name'], tap=CardAction(type='invoke', value=obj)
            )
   
            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=HeroCard(title=obj['name']),
                preview=CardFactory.hero_card(hero_card),
            )
            attachments.append(attachment)
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type='result', attachment_layout='list', attachments=attachments
            )
        )


class TeamsMessageExtensionsBot(Resource):

    def __init__(self):

        self.event_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.event_loop)

        app_config = BotFrameworkAdapterSettings(app_id='YOUR-BOT-ID',
                                                 app_password='YOUR-BOT-PASSWORD')
        self.bot_framework_adaptor = BotFrameworkAdapter(app_config)

    def post(self):

        message_handler = ActivityHandler()

        if 'application/json' in request.headers['Content-Type']:
            body = request.json
        else:
            return Response(status=415)

        activity = Activity().deserialize(body)
        auth_header = (
            request.headers['Authorization'] if 'Authorization' in request.headers else ''
        )

        try:
            task = self.event_loop.create_task(
                self.bot_framework_adaptor.process_activity(activity, auth_header, message_handler.on_turn)
            )

            invoke_response = self.event_loop.run_until_complete(asyncio.gather(task))[0]

            if invoke_response:
                self.logger.info(invoke_response.body)
                return Response(response=json.dumps(invoke_response.body),
                                status=invoke_response.status, mimetype='application/json')

            return Response(status=201)
        except Exception as exception:
            raise exception

I was totally unaware that message extensions followed a standard request response model rather than a request request model as the bot does. Here is a full working example using flask - ms example here :

import asyncio
import json

from botbuilder.core.teams import TeamsActivityHandler
from botbuilder.schema import Activity, CardAction, HeroCard

from botbuilder.core import (
    BotFrameworkAdapter,
    BotFrameworkAdapterSettings, TurnContext, CardFactory, MessageFactory,
)

from botbuilder.schema.teams import (
    MessagingExtensionAttachment,
    MessagingExtensionQuery,
    MessagingExtensionResult,
    MessagingExtensionResponse,

)

from flask import request, Response
from flask_restful import Resource


class ActivityHandler(TeamsActivityHandler):

    async def on_teams_messaging_extension_query(self, turn_context: TurnContext, query: MessagingExtensionQuery):
        search_query = str(query.parameters[0].value).strip()
        if search_query == '':
            await turn_context.send_activity(
                MessageFactory.text('You cannot enter a blank string for the search')
            )
            return
       
        # TODO: Implement a search returning objects
        search_results = self._get_search_results(search_query)
   
        attachments = []
        for obj in search_results:
            hero_card = HeroCard(
                title=obj['name'], tap=CardAction(type='invoke', value=obj)
            )
   
            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=HeroCard(title=obj['name']),
                preview=CardFactory.hero_card(hero_card),
            )
            attachments.append(attachment)
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type='result', attachment_layout='list', attachments=attachments
            )
        )


class TeamsMessageExtensionsBot(Resource):

    def __init__(self):

        self.event_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.event_loop)

        app_config = BotFrameworkAdapterSettings(app_id='YOUR-BOT-ID',
                                                 app_password='YOUR-BOT-PASSWORD')
        self.bot_framework_adaptor = BotFrameworkAdapter(app_config)

    def post(self):

        message_handler = ActivityHandler()

        if 'application/json' in request.headers['Content-Type']:
            body = request.json
        else:
            return Response(status=415)

        activity = Activity().deserialize(body)
        auth_header = (
            request.headers['Authorization'] if 'Authorization' in request.headers else ''
        )

        try:
            task = self.event_loop.create_task(
                self.bot_framework_adaptor.process_activity(activity, auth_header, message_handler.on_turn)
            )

            invoke_response = self.event_loop.run_until_complete(asyncio.gather(task))[0]

            if invoke_response:
                self.logger.info(invoke_response.body)
                return Response(response=json.dumps(invoke_response.body),
                                status=invoke_response.status, mimetype='application/json')

            return Response(status=201)
        except Exception as exception:
            raise exception
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文