I built a python Dialogflow class to return as response as a string to be used for sending SMS messages. The returned string is a complex list of dictionaries with nested lists.
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)
When building the object and calling the detect_intent_response method, the object returned is a google.protobuf.pyext._message.RepeatedCompositeContainer:
[text {
text: "Foo"
}
, text {
text: "Bar"
}
, text {
text: "Char"
}
]
After several hours of searching, I discovered the google.protobuf library has a Module "json_format" that allows serializing to JSON or converting to a python dictionary, so I modified the class in the following manner:
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', {}))
Which returns a complex list with nested dictionaries.
[{'text': {'text': ['Foo']}}, {'text': {'text': ['Bar']}}, {'text': {'text': ['Char']}}]
The desired result would return the following in a string format
Foo
Bar
Char
How can I accomplish this?