Returns the result of detect intent with texts as inputs and includes
    the response in an audio format.

    Using the same `session_id` between requests allows continuation
    of the conversaion.
976981
def detect_intent_with_texttospeech_response(project_id, session_id, texts,
                                             language_code):
    """"""
    import dialogflow_v2beta1 as dialogflow
    session_client = dialogflow.SessionsClient()

    session_path = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session_path))

    for text in texts:
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)

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

        # Set the query parameters with sentiment analysis
        output_audio_config = dialogflow.types.OutputAudioConfig(
            audio_encoding=dialogflow.enums.OutputAudioEncoding
            .OUTPUT_AUDIO_ENCODING_LINEAR_16)

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

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
        # The response's audio_content is binary.
        with open('output.wav', 'wb') as out:
            out.write(response.output_audio)
            print('Audio content written to file "output.wav"')
330942
def intent(method):
    

    def wrapper(self, *args, **kwargs):
        try:
            return method(self, *args, **kwargs)
        except exceptions.MatrixError as e:
            if isinstance(e.original_exception,
                          matrix_client.errors.MatrixRequestError):
                self._handle_request_exception(e)
                # May still throw exception for other reasons; not handled
                return method(self, *args, **kwargs)
            else:
                raise e

    return wrapper
904203
def ReadRequestsAndResponses(self,
                               session_id,
                               timestamp=None,
                               request_limit=None,
                               response_limit=None):
    """"""
    subject = session_id.Add("state")
    requests = {}

    # Get some requests.
    for predicate, serialized, _ in self.ResolvePrefix(
        subject,
        self.FLOW_REQUEST_PREFIX,
        limit=request_limit,
        timestamp=timestamp):

      request_id = predicate.split(":", 1)[1]
      requests[str(subject.Add(request_id))] = serialized

    # And the responses for them.
    response_data = dict(
        self.MultiResolvePrefix(
            list(iterkeys(requests)),
            self.FLOW_RESPONSE_PREFIX,
            limit=response_limit,
            timestamp=timestamp))

    for urn, request_data in sorted(iteritems(requests)):
      request = rdf_flow_runner.RequestState.FromSerializedString(request_data)
      responses = []
      for _, serialized, timestamp in response_data.get(urn, []):
        msg = rdf_flows.GrrMessage.FromSerializedString(serialized)
        msg.timestamp = timestamp
        responses.append(msg)

      yield (request, sorted(responses, key=lambda msg: msg.response_id))
695672
def reply(self, text):
        
        data = {'text': text, 'vchannel_id': self['vchannel_id']}
        if self.is_p2p():
            data['type'] = RTMMessageType.P2PMessage
            data['to_uid'] = self['uid']
        else:
            data['type'] = RTMMessageType.ChannelMessage
            data['channel_id'] = self['channel_id']
        return RTMMessage(data)
607168
async def sendAudio(self, chat_id, audio,
                        caption=None,
                        parse_mode=None,
                        duration=None,
                        performer=None,
                        title=None,
                        disable_notification=None,
                        reply_to_message_id=None,
                        reply_markup=None):
        
        p = _strip(locals(), more=['audio'])
        return await self._api_request_with_file('sendAudio', _rectify(p), 'audio', audio)
403945
def get_response(self):
        '''
        
        '''
        self.process_commmon()
        self.process_data()
        urlencoded_data = urllib.urlencode(self.data)
        if self.METHOD == POST:
            req = urllib2.Request(self.URL, urlencoded_data)
        else:
            req = urllib2.Request('%s?%s' %(self.URL, urlencoded_data))

        if not self.data['content']:
            raise PasteException("No content to paste")

        self.response = urllib2.urlopen(req)
        return self.response
1201766
def send_audio_file(
        self, audio_file, device_state, authentication_headers,
        dialog_request_id, distance_profile, audio_format
    ):
        

        payload = {
            'context': device_state,
            'event': {
                'header': {
                    'namespace': 'SpeechRecognizer',
                    'name': 'Recognize',
                    'messageId': self.generate_message_id(),
                    'dialogRequestId': dialog_request_id,
                },
                'payload': {
                    'profile': distance_profile,
                    'format': audio_format
                }
            }
        }
        multipart_data = MultipartEncoder(
            fields=[
                (
                    'request', (
                        'request',
                        json.dumps(payload),
                        'application/json;',
                        {'Content-Disposition': "form-data; name='request'"}
                    ),
                ),
                (
                    'audio', (
                        'audio',
                        audio_file,
                        'application/octet-stream',
                        {'Content-Disposition': "form-data; name='audio'"}
                    )
                ),
            ],
            boundary='boundary',
        )
        headers = {
            **authentication_headers,
            'Content-Type': multipart_data.content_type
        }
        stream_id = self.connection.request(
            'POST',
            '/v20160207/events',
            headers=headers,
            body=multipart_data,
        )
        response = self.connection.get_response(stream_id)
        return self.parse_response(response)
815809
def _get_response(self, url, **params):
        
        data = urlencode(params)
        url = "%s?%s" % (url, data)
        headers = {'User-Agent': self.get_random_agent()}
        request = Request(url, headers=headers, method='GET')

        def open_request(request, attempts, err=None):
            if attempts > self.request_attempts:
                raise
            attempts += 1
            try:
                with urlopen(request, timeout=self.timeout) as response:
                    return response.read()
            except HTTPError as err:
                if err.getcode() < 500:
                    raise
                print("HTTPError occurred while trying to request the url "
                      "%s. %s. Trying again in %s seconds..." % (url, err,
                                                self.seconds_between_attempts))
                time.sleep(self.seconds_between_attempts)
                return open_request(request, attempts, err)

        attempts = 0
        self.last_response = open_request(request, attempts)
        return self.last_response
1342191
def process_response(self, request, response):
        
        if hasattr(threadlocal, 'actionslog'):
            pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])

        return response
1233792
def answerReceived(self, value, originalValue,
                       originalSender, originalTarget):
        
        if value.type != AMP_ANSWER_TYPE:
            raise UnknownMessageType()
        commandName = self._boxFromData(originalValue.data)[COMMAND]
        rawArgs = self._boxFromData(value.data)
        placeholder = _ProtocolPlaceholder(originalSender, originalTarget)
        if ERROR in rawArgs:
            thunk = errorMethod.errbackForName(self, commandName, rawArgs[ERROR])
            thunk(Failure(thunk.exception()))
        else:
            thunk = answerMethod.responderForName(self, commandName)
            arguments = thunk.command.parseResponse(rawArgs, placeholder)
            thunk(**arguments)
622304
def generate_response(self, input_statement, additional_response_selection_parameters=None):
        
        Statement = self.storage.get_object('statement')

        results = []
        result = None
        max_confidence = -1

        for adapter in self.logic_adapters:
            if adapter.can_process(input_statement):

                output = adapter.process(input_statement, additional_response_selection_parameters)
                results.append(output)

                self.logger.info(
                    '{} selected "{}" as a response with a confidence of {}'.format(
                        adapter.class_name, output.text, output.confidence
                    )
                )

                if output.confidence > max_confidence:
                    result = output
                    max_confidence = output.confidence
            else:
                self.logger.info(
                    'Not processing the statement using {}'.format(adapter.class_name)
                )

        class ResultOption:
            def __init__(self, statement, count=1):
                self.statement = statement
                self.count = count

        # If multiple adapters agree on the same statement,
        # then that statement is more likely to be the correct response
        if len(results) >= 3:
            result_options = {}
            for result_option in results:
                result_string = result_option.text + ':' + (result_option.in_response_to or '')

                if result_string in result_options:
                    result_options[result_string].count += 1
                    if result_options[result_string].statement.confidence < result_option.confidence:
                        result_options[result_string].statement = result_option
                else:
                    result_options[result_string] = ResultOption(
                        result_option
                    )

            most_common = list(result_options.values())[0]

            for result_option in result_options.values():
                if result_option.count > most_common.count:
                    most_common = result_option

            if most_common.count > 1:
                result = most_common.statement

        response = Statement(
            text=result.text,
            in_response_to=input_statement.text,
            conversation=input_statement.conversation,
            persona='bot:' + self.name
        )

        response.confidence = result.confidence

        return response
678945
def _receive_poll(self, command_id, response_streams):
        
        logging.info('receive command: ' + command_id)
        resource = ResourceLocator(CommandShell.ShellResource)
        resource.add_selector('ShellId', self.__shell_id)

        stream_attributes = {'#text': " ".join(response_streams.keys()), '@CommandId': command_id}
        receive = {'rsp:Receive': {'rsp:DesiredStream': stream_attributes}}

        try:
            response = self.session.recieve(resource, receive)['rsp:ReceiveResponse']
        except Exception as e:
            return False, None

        # some responses will not include any output
        session_streams = response.get('rsp:Stream', ())
        if not isinstance(session_streams, list):
            session_streams = [session_streams]

        for stream in session_streams:
            if stream['@CommandId'] == command_id and '#text' in stream:
                response_streams[stream['@Name']] += base64.b64decode(stream['#text'])
                # XPRESS Compression Testing
                # print "\\x".join("{:02x}".format(ord(c)) for c in base64.b64decode(stream['#text']))
                # data = base64.b64decode(stream['#text'])
                # f = open('c:\\users\\developer\\temp\\data.bin', 'wb')
                # f.write(data)
                # f.close()
                # decode = api.compression.xpress_decode(data[4:])
        done = response['rsp:CommandState']['@State'] == CommandShell.StateDone
        if done:
            exit_code = int(response['rsp:CommandState']['rsp:ExitCode'])
        else: exit_code = None
        return done, exit_code
1112214
def handle_response(self, content, target=None, single_result=True, raw=False):
        
        response = content['response']

        self.check_errors(response)

        data = response.get('data')

        if is_empty(data):
            return data
        elif is_paginated(data):
            if 'count' in data and not data['count']:
                # Response is paginated, but is empty
                return data['data']
            data = data['data']

        if raw:
            return data
        return self.init_all_objects(data, target=target, single_result=single_result)
143312
def bot_intent(self) -> "IntentAPI":
        
        if not self._bot_intent:
            self._bot_intent = IntentAPI(self.bot_mxid, self, state_store=self.state_store,
                                         log=self.intent_log)
        return self._bot_intent
123349
def process_response(self, request, response):
        
        if hasattr(threadlocal, 'auditlog'):
            pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'])

        return response
939920
def get_page_and_url(session, url):
    
    reply = get_reply(session, url)
    return reply.text, reply.url
431639
def ReadResponsesForRequestId(self, session_id, request_id, timestamp=None):
    
    request = rdf_flow_runner.RequestState(id=request_id, session_id=session_id)
    for _, responses in self.ReadResponses([request], timestamp=timestamp):
      return responses