def _sendSlack(message=None, event=None, slack_token=None, method=None, force=False): if not lazylibrarian.CONFIG['USE_SLACK'] and not force: return False url = "https://hooks.slack.com/services/" if slack_token is None: slack_token = lazylibrarian.CONFIG['SLACK_TOKEN'] if method is None: method = 'POST' if event == "Test": logger.debug("Testing Slack notification") else: logger.debug("Slack message: %s: %s" % (event, message)) if slack_token.startswith(url): url = slack_token else: url = url + slack_token headers = {"Content-Type": "application/json"} postdata = '{"username": "******", ' postdata += '"attachments": [{"text": "%s", "thumb_url": ' % message postdata += '"https://github.com/DobyTang/LazyLibrarian/raw/master/data/images/ll.png"}], ' postdata += '"text":"%s"}' % event r = requests.request(method, url, data=postdata, headers=headers) if r.text.startswith('<!DOCTYPE html>'): logger.debug("Slack returned html errorpage") return "Invalid or missing Webhook" logger.debug("Slack returned [%s]" % r.text) return r.text
def _sendSlack(self, message=None, event=None, slack_token=None, method=None, force=False): if not lazylibrarian.USE_SLACK and not force: return False url = "https://hooks.slack.com/services/" if slack_token == None: slack_token = lazylibrarian.SLACK_TOKEN if method == None: method = 'POST' if event == "Test": logger.debug("Testing Slack notification") else: logger.debug("Slack message: " + str(event) + str(message)) url = url + slack_token headers = {"Content-Type": "application/json"} postdata = '{"username": "******", "text":"%s\n%s"}' % (event, message) r = requests.request(method, url, data=postdata, headers=headers ) if r.text.startswith('<!DOCTYPE html>'): logger.debug("Slack returned html errorpage") return "Invalid or missing Webhook" logger.debug("Slack returned [%s]" % r.text) return r.text
def _notify(telegram_token=None, telegram_userid=None, event=None, message=None, force=False): # suppress notifications if the notifier is disabled but the notify options are checked if not lazylibrarian.CONFIG['USE_TELEGRAM'] and not force: return False TELEGRAM_API = "https://api.telegram.org/bot%s/%s" if telegram_token is None: telegram_token = lazylibrarian.CONFIG['TELEGRAM_TOKEN'] if telegram_userid is None: telegram_userid = lazylibrarian.CONFIG['TELEGRAM_USERID'] logger.debug(u"Telegram: event: " + event) logger.debug(u"Telegram: message: " + message) # Construct message payload = {'chat_id': telegram_userid, 'text': event + ': ' + message} # Send message to user using Telegram's Bot API try: url = TELEGRAM_API % (telegram_token, "sendMessage") logger.debug(url) logger.debug(payload) response = requests.request('POST', url, data=payload) except Exception, e: logger.warn(u'Telegram notify failed: ' + str(e)) return False
def traktRequest(self, path, data=None, headers=None, url=None, method='GET',count=0): if None == url: url = self.api_url + path else: url = url + path count = count + 1 if None == headers: headers = self.headers if None == sickbeard.TRAKT_ACCESS_TOKEN: logger.log(u'You must get a Trakt TOKEN. Check your Trakt settings', logger.WARNING) raise traktAuthException(e) headers['Authorization'] = 'Bearer ' + sickbeard.TRAKT_ACCESS_TOKEN try: resp = requests.request(method, url, headers=headers, timeout=self.timeout, data=json.dumps(data) if data else [], verify=self.verify) # check for http errors and raise if any are present resp.raise_for_status() # convert response to json resp = resp.json() except requests.RequestException as e: code = getattr(e.response, 'status_code', None) if not code: # This is pretty much a fatal error if there is no status_code # It means there basically was no response at all raise traktException(e) elif code == 502: # Retry the request, cloudflare had a proxying issue logger.log(u'Retrying trakt api request: %s' % path, logger.WARNING) return self.traktRequest(path, data, headers, method) elif code == 401: logger.log(u'Unauthorized. Please check your Trakt settings', logger.WARNING) if self.traktToken(refresh=True,count=count): return self.traktRequest(path, data, url, method) raise traktAuthException(e) elif code in (500,501,503,504,520,521,522): #http://docs.trakt.apiary.io/#introduction/status-codes logger.log(u'Trakt may have some issues and it\'s unavailable. Try again later please', logger.WARNING) raise traktServerBusy(e) else: raise traktException(e) # check and confirm trakt call did not fail if isinstance(resp, dict) and resp.get('status', False) == 'failure': if 'message' in resp: raise traktException(resp['message']) if 'error' in resp: raise traktException(resp['error']) else: raise traktException('Unknown Error') return resp
def traktRequest(self, path, data=None, method='GET'): url = self.api_url + path headers = self.headers if not getattr(self, 'token', None): self.validateAccount() headers['trakt-user-login'] = self.username headers['trakt-user-token'] = self.token # request the URL from trakt and parse the result as json try: resp = requests.request(method, url, headers=headers, timeout=self.timeout, data=json.dumps(data) if data else [], verify=self.verify) # check for http errors and raise if any are present resp.raise_for_status() # convert response to json resp = resp.json() except requests.RequestException as e: code = getattr(e.response, 'status_code', None) if not code: # This is pretty much a fatal error if there is no status_code # It means there basically was no response at all raise traktException(e) elif code == 502: # Retry the request, cloudflare had a proxying issue logger.log(u"Retrying trakt api request: %s" % path, logger.WARNING) return self.traktRequest(path, data, method) elif code == 401: logger.log(u"Unauthorized. Please check your Trakt settings", logger.WARNING) raise traktAuthException(e) elif code in (500, 501, 503, 504, 520, 521, 522): #http://docs.trakt.apiary.io/#introduction/status-codes logger.log( u"Trakt may have some issues and it's unavailable. Try again later please", logger.WARNING) raise traktServerBusy(e) else: raise traktException(e) # check and confirm trakt call did not fail if isinstance(resp, dict) and resp.get('status', False) == 'failure': if 'message' in resp: raise traktException(resp['message']) if 'error' in resp: raise traktException(resp['error']) else: raise traktException('Unknown Error') return resp
def _request(self, method, url, postdata=None, params=None, files=None): headers = {"Accept": "application/json", "Content-Type": "application/json", "User-Agent": "pyPushBullet"} if postdata: postdata = json.dumps(postdata) r = requests.request( method, url, data=postdata, params=params, headers=headers, files=files, auth=HTTPBasicAuth(self.apiKey, "") ) r.raise_for_status() return r.json()
def __request(self, method, **kwargs): #Firebase API does not accept form-encoded PUT/POST data. It needs to #be JSON encoded. if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) params = {} if self.auth_token: if 'params' in kwargs: params = kwargs['params'] del kwargs['params'] params.update({'auth': self.auth_token}) r = requests.request(method, self.__url(), params=params, **kwargs) r.raise_for_status() #throw exception if error return r.json()
def _send_slack(self, message=None): slack_webhook = self.SLACK_WEBHOOK_URL + sickbeard.SLACK_WEBHOOK.replace(self.SLACK_WEBHOOK_URL,'') logger.log(u"Sending slack message: " + message, logger.INFO) logger.log(u"Sending slack message to url: " + slack_webhook, logger.INFO) method = 'POST' headers = {"Content-Type": "application/json"} postdata = '{"text":"%s"}' % message try: r = requests.request(method, slack_webhook, data=postdata, headers=headers ) except Exception as e: logger.log(u"Error Sending Slack message: " + ex(e), logger.ERROR) return False return True
def _request(self, method, url, postdata=None, params=None, files=None): headers = { "Accept": "application/json", "Content-Type": "application/json", "User-Agent": "pyPushBullet" } if postdata: postdata = json.dumps(postdata) r = requests.request(method, url, data=postdata, params=params, headers=headers, files=files, auth=HTTPBasicAuth(self.apiKey, "")) r.raise_for_status() return r.json()
def validateAccount(self): if hasattr(self, 'token'): del (self.token) data = {'login': self.username, 'password': self.password} try: resp = requests.request('POST', self.api_url + "auth/login", headers=self.headers, data=json.dumps(data), timeout=self.timeout, verify=self.verify) resp.raise_for_status() resp = resp.json() except requests.RequestException as e: code = getattr(e.response, 'status_code', None) if not code: # This is pretty much a fatal error if there is no status_code # It means there basically was no response at all raise traktException(e) elif code == 502: # Retry the request, cloudflare had a proxying issue logger.log(u"Retrying trakt api request: auth/login", logger.WARNING) return self.validateAccount() elif code == 401: logger.log(u"Unauthorized. Please check your Trakt settings", logger.WARNING) raise traktAuthException(e) elif code in (500, 501, 503, 504, 520, 521, 522): #http://docs.trakt.apiary.io/#introduction/status-codes logger.log( u"Trakt may have some issues and it's unavailable. Try again later please", logger.WARNING) raise traktServerBusy(e) else: raise traktException(e) if 'token' in resp: self.token = resp['token'] return True return False
def traktRequest(self, path, data=None, headers=None, url=None, method='GET', count=0): if None == url: url = self.api_url + path else: url = url + path count = count + 1 if None == headers: headers = self.headers if None == sickbeard.TRAKT_ACCESS_TOKEN: logger.log( u'You must get a Trakt TOKEN. Check your Trakt settings', logger.WARNING) raise traktAuthException(e) headers['Authorization'] = 'Bearer ' + sickbeard.TRAKT_ACCESS_TOKEN try: resp = requests.request(method, url, headers=headers, timeout=self.timeout, data=json.dumps(data) if data else [], verify=self.verify) # check for http errors and raise if any are present resp.raise_for_status() # convert response to json resp = resp.json() except requests.RequestException as e: code = getattr(e.response, 'status_code', None) if not code: # This is pretty much a fatal error if there is no status_code # It means there basically was no response at all raise traktException(e) elif code == 502: # Retry the request, cloudflare had a proxying issue logger.log(u'Retrying trakt api request: %s' % path, logger.WARNING) return self.traktRequest(path, data, headers, method) elif code == 401: logger.log(u'Unauthorized. Please check your Trakt settings', logger.WARNING) if self.traktToken(refresh=True, count=count): return self.traktRequest(path, data, url, method) raise traktAuthException(e) elif code in (500, 501, 503, 504, 520, 521, 522): #http://docs.trakt.apiary.io/#introduction/status-codes logger.log( u'Trakt may have some issues and it\'s unavailable. Try again later please', logger.WARNING) raise traktServerBusy(e) else: raise traktException(e) # check and confirm trakt call did not fail if isinstance(resp, dict) and resp.get('status', False) == 'failure': if 'message' in resp: raise traktException(resp['message']) if 'error' in resp: raise traktException(resp['error']) else: raise traktException('Unknown Error') return resp