Диалоговый поток: работа с объектами google.protobuf в Python - PullRequest
1 голос
/ 18 октября 2019

Я создал класс Dialogflow Python, который будет возвращаться в качестве ответа в виде строки, которая будет использоваться для отправки SMS-сообщений. Возвращенная строка представляет собой сложный список словарей с вложенными списками.

class DialogFlow():
    """
    A class to authenticate and point to a specific Dialogflow Agent. This will
    allow for multiple agents to be selected based on user response without
    having to create multiple separate functions
    """
    def __init__(self, project_id, language_code, session_id):
        self.project_id = project_id
        self.language_code = language_code
        self.session_id = session_id

    def detect_intent_response(self, text):
        """Returns the result of detect intent with texts as inputs.
        Using the same `session_id` between requests allows continuation
        of the conversation."""

        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(self.project_id, self.session_id)

        text_input = dialogflow.types.TextInput(
            text=text, language_code=self.language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(
            session=session, query_input=query_input)

        return_text = response.query_result.fulfillment_messages

        return str(return_text)

При построении объекта и вызове метода detect_intent_response возвращается объект google.protobuf.pyext._message.RepeatedCompositeContainer:

[text { text: "Foo" } , text { text: "Bar" } , text { text: "Char" } ]

После нескольких часов поиска я обнаружил, что в библиотеке google.protobuf есть модуль "json_format", который позволяет сериализовать в JSON или преобразовывать в словарь Python, поэтому я изменил класс вследующим образом:

response = session_client.detect_intent(
            session=session, query_input=query_input)

        responses = MessageToDict(response, preserving_proto_field_name=True)
        desired_response = responses['query_result']

        return str(desired_response.get('fulfillment_messages', {}))

, который возвращает сложный список с вложенными словарями.

[{'text': {'text': ['Foo']}}, {'text': {'text': ['Bar']}}, {'text': {'text': ['Char']}}]

Требуемый результат будет возвращать следующее в виде строки

Foo Bar Char

Как я могу это сделать?

...