def __api_call(self, api, auth=True): url = 'https://api.twitch.tv/helix/' + api if auth: page = get_webpage(url, h=H_AUTH) else: page = get_webpage(url, h=H_BASIC) return convert_json(page)
def __api_call_old(self, api, auth=False): url = 'https://api.twitch.tv/kraken/' + api if auth: page = get_webpage(url, h=H_AUTH_OLD) else: page = get_webpage(url, h=H_BASIC) return convert_json(page)
def updateStreamData(self): if on_cooldown(self.lastUpdate, self.updateInterval): return stream_data = convert_json(get_webpage(self.url, h=H_BASIC)) if stream_data['stream'] == None: self.live = False self.stream_start = None self.game = None else: self.live = True self.stream_start = convert_timestamp(stream_data['stream']['created_at']) self.game = stream_data['stream']['game'] print self.live print self.stream_start print self.game print self.lastUpdate self.lastUpdate = set_cooldown()
def post(self): """Get an access_token - make an oAuth API request.""" #a direct call to post will always fetch a new access_token self.response, self.content = http.request(self.url, 'POST', headers=self.headers, body=urllib.urlencode(self.body)) #using httplib2, force_exception_to_status_code True we don't get exceptions' self.status_code = int(self.response['status']) try: _content_dict = convert_json(self.content) if self.status_code == 200: self.access_token = _content_dict['access_token'] #save the token pickle.dump(copy.deepcopy(self.access_token), open(self.persist_path, "wb")) else: logger.error('%s %s %s %s %s', self.name, 'status_code', self.status_code, 'content', self.content) self.access_token = None except ValueError, e: logger.error('%s %s %s %s %s %s %s', self.name, 'Error parsing JSON response', 'status_code', self.status_code, 'content', self.content, e) self.access_token = None
def post(self): """convert audio data to text""" #Watson Recognition object - JSON self.recognition = None #List of transcriptions self.transcription = [] self.number_of_transcriptions = 0 response = cStringIO.StringIO() response_headers = cStringIO.StringIO() #configure the API request using pycurl _curl = pycurl.Curl() _curl.setopt(_curl.POST, 1) _curl.setopt(_curl.URL, self.url) _curl.setopt(_curl.HEADERFUNCTION, response_headers.write) _curl.setopt(_curl.WRITEFUNCTION, response.write) #_curl.setopt(_curl.VERBOSE, 1) #_curl.setopt(_curl.TIMEOUT, 120) if type(self.body) is str: logger.debug('%s converting with a file', self.name) #non-streaming: instance was created with raw bytes if self.headers is None: self.headers = ['Authorization: Bearer ' + str(self.access_token), 'Content-Type: ' + self.content_type, 'Accept: application/json', 'Content-Language: en-US', 'X-SpeechContext: Generic', 'Content-Length: ' + str(len(self.body))] _curl.setopt(_curl.POSTFIELDS, self.body) _curl.setopt(_curl.POSTFIELDSIZE, len(self.body)) logger.debug('%s non-streaming _curl self.body len= %s', self.name, len(self.body)) elif type(self.body) is deque: logger.debug('%s converting with a stream', self.name) #streaming: instance was created with a deque (fifo) - chunk max size = 512 if self.headers is None: self.headers = ['Authorization: Bearer ' + str(self.access_token), 'Content-Type: ' + self.content_type, 'Accept: application/json', 'Content-Language: en-US', 'X-SpeechContext: Generic', 'Transfer-Encoding: chunked', 'Cache-Control: no-cache', 'Connection: Keep-Alive'] _curl.setopt(_curl.READFUNCTION, self.chunker) else: s = str(self.name) + ' unknown body type ' + str(type(self.body)) raise APIException(s) #best result or all results self.headers.append('X-Arg: HasMultipleNBest=false') logger.debug('%s Request headers= \n%s type of headers= %s', self.name, self.headers, type(self.headers)) _curl.setopt(_curl.HTTPHEADER, self.headers) _curl.perform() self.status_code = _curl.getinfo(_curl.HTTP_CODE) _curl.close() #this is raw curl response - format self.response_headers = response_headers self.response = response try: logger.debug('%s raw response value= \n%s', self.name, response.getvalue()) logger.debug('%s raw header value = \n%s', self.name, response_headers.getvalue()) self.content = convert_json(response.getvalue()) if self.status_code == 200: self.recognition_status = self.content['Recognition']['Status'] logger.debug('%s Recognition status = %s', self.name, self.recognition_status) #HTTP 200 OK is the only success response we expect self.recognition = self.content if self.recognition_status == 'OK': self.number_of_transcriptions = len( self.recognition['Recognition']['NBest']) #construct a list of transcriptions logger.info('%s Speech was recognized.', self.name) for index in range(self.number_of_transcriptions): self.transcription.append( self.recognition['Recognition']['NBest'][index][ 'ResultText']) else: #speech is not recognized logger.info('%s Speech was not recognized, please try again.', self.name) elif self.status_code == 400: #bad request logger.error('%s Bad Request: %s', self.status_code, self.content) elif self.status_code == 401: #Unauthorized logger.error('%s Unauthorized: %s', self.status_code, self.content) elif self.status_code == 403: #Forbidden logger.error('%s Forbidden: %s', self.status_code, self.content) elif self.status_code == 404: #Not found logger.error('%s Not found: %s', self.status_code, self.content) elif self.status_code == 405: #Method not supported logger.error('%s Method not supported: %s', self.status_code, self.content) elif self.status_code == 500: #Internal server error logger.error('%s Internal server error: %s', self.status_code, self.content) elif self.status_code == 503: #Service unavailable logger.error('%s Service unavailable: %s', self.status_code, self.content) else: logger.error('%s Error: %s', self.status_code, self.content) s = 'SpeechToText API: unknown HTTP status code' raise APIException(s) except ValueError, e: logger.error('%s %s %s %s %s %s', self.name, 'error parsing json', 'status_code', self.status_code, self.response, e)
def getCurrentUsers(self): self.current_users = list() api_dict = convert_json(get_webpage(self.url)) for user_type in api_dict['chatters']: self.current_users += api_dict['chatters'][user_type]