本文整理汇总了Python中pushover.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PushoverNotificationService
class PushoverNotificationService(BaseNotificationService):
"""Implement the notification service for Pushover."""
def __init__(self, user_key, api_token):
"""Initialize the service."""
from pushover import Client
self._user_key = user_key
self._api_token = api_token
self.pushover = Client(
self._user_key, api_token=self._api_token)
def send_message(self, message='', **kwargs):
"""Send a message to a user."""
from pushover import RequestError
# Make a copy and use empty dict if necessary
data = dict(kwargs.get(ATTR_DATA) or {})
data['title'] = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
targets = kwargs.get(ATTR_TARGET)
if not isinstance(targets, list):
targets = [targets]
for target in targets:
if target is not None:
data['device'] = target
try:
self.pushover.send_message(message, **data)
except ValueError as val_err:
_LOGGER.error(str(val_err))
except RequestError:
_LOGGER.exception("Could not send pushover notification")
示例2: check
def check(push, show):
header = {'Authorization': 'Token ' + API_TOKEN}
session = requests.Session()
url = "https://api.dusti.xyz/v1/node/"
r = session.get(url, headers=header)
if push:
client = Client(PUSHOVER_CLIENT_TOKEN, api_token=PUSHOVER_API_TOKEN)
for node in r.json():
if node.get("last_data_push"):
last_data_push = datetime.datetime.strptime(node.get("last_data_push")[:19],
"%Y-%m-%dT%H:%M:%S")
sensor_id = node.get('sensors', [{}])[0].get('id')
last_check_timestamp = check_file(sensor_id)
uid = node.get('uid')
description = node.get('sensors', [{}])[0].get('description')
if (last_data_push < datetime.datetime.utcnow() - datetime.timedelta(minutes=LAST_N_MINUTES) and
last_data_push > datetime.datetime.utcnow() - datetime.timedelta(hours=LAST_N_HOURS)):
if show:
click.echo("{} | {:>35} | {}".format(last_data_push, uid, description))
if not last_check_timestamp:
if push:
client.send_message("sensor: {}\ndescription: {}".format(uid, description),
title="Sensor hasn't pushed in the last {} minutes!".format(LAST_N_MINUTES))
# FIXME: calculate moment of last push and add into message
update_file(sensor_id, last_data_push)
elif last_check_timestamp:
delete_file(sensor_id)
if push:
client.send_message("RESTORED sensor: {}\ndescription: {}".format(uid, description),
title="Sensor is back again!")
示例3: PONotif
def PONotif(chapter, series):
global xml_list
PO_token = re.search('<PO_token>(.*?)</PO_token>', xml_list, re.DOTALL|re.MULTILINE).group(1).strip()
PO_user = re.search('<PO_user>(.*?)</PO_user>', xml_list, re.DOTALL|re.MULTILINE).group(1).strip()
client = Client(PO_user, api_token=PO_token)
client.send_message('Series: \"{}\"\nChapter: {}\n\n'.format(series, '{:3.1f}'.format(chapter['num']).zfill(5)), title="New manga chapter downloaded")
示例4: SonosUpdateHandler
class SonosUpdateHandler(FileSystemEventHandler):
def __init__(self, system=SonosSystem(), interval=5.0,
api_key=None, user_key=None):
super(SonosUpdateHandler, self).__init__()
assert isinstance(system, SonosSystem)
self.system = system
self.interval = interval
self.timer = None
self.client = Client(user_key, api_token=api_key) \
if api_key and user_key else None
self.albuminfo = None
syslog.syslog('Created SonosUpdateHandler: Interval {}'.format(
self.interval))
def on_moved(self, event):
syslog.syslog('File moved event -> {}'.format(event.dest_path))
file_path, filename = path.split(event.dest_path)
file_path, album = path.split(file_path)
file_path, artist = path.split(file_path)
self.albuminfo = artist, album
self._handle_valid_event(event)
def on_deleted(self, event):
syslog.syslog('File deleted event -> {}'.format(event.src_path))
self._handle_valid_event(event)
def _handle_valid_event(self, event):
if self.timer:
self.timer.cancel()
self.timer = Timer(self.interval,
self._update_sonos)
self.timer.start()
def _update_sonos(self):
self.timer = None
syslog.syslog('Updating Sonos Library ...')
self.system.update()
if self.albuminfo and self.client:
syslog.syslog('Sending pushover notification ...')
artist, album = self.albuminfo
self.albuminfo = None
self.client.send_message(
'{} - {}'.format(artist, album),
title='Album Downloaded')
示例5: WriteAudit
def WriteAudit(AuditMessage):
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')
Logger.info(st+'\t'+AuditMessage)
with open(config.get('Files','auditlog'), "a") as auditfile:
auditfile.write(st+'\t'+AuditMessage+'\n')
auditfile.close()
if config.getboolean('Pushover','enabled'):
Pushover_client = Client(config.get('Pushover','user_key'),api_token=config.get('Pushover','api_token'))
Pushover_client.send_message(st+' '+AuditMessage, title=LANGUAGES_DICT[config.get('Defaults','language')]['doorbell_title'])
示例6: __init__
def __init__(self, user_key, api_token):
# pylint: disable=no-name-in-module, unused-variable
from pushover import Client
self._user_key = user_key
self._api_token = api_token
self.pushover = Client(
self._user_key, api_token=self._api_token)
示例7: __init__
def __init__(self, user_key, api_token):
"""Initialize the service."""
from pushover import Client
self._user_key = user_key
self._api_token = api_token
self.pushover = Client(
self._user_key, api_token=self._api_token)
示例8: __init__
def __init__(self, config):
init(config.get("settings", "pushover_api_token"))
self.client = Client(config.get("settings", "pushover_user_key"))
self.btrfs_mount_points = [path for key, path in config.items("btrfs_mount_points")]
self.data_dir = config.get("settings", "data_directory")
self.suppression_window = config.getint("settings", "suppression_window")
self.btrfs_enabled = config.getboolean("settings", "btrfs_enabled")
self.zfs_enabled = config.getboolean("settings", "zfs_enabled")
示例9: Pushover
class Pushover(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__config = config
self.__packpub_info = packpub_info
self.__client = Client(self.__config.get('pushover', 'pushover.user_key'), api_token=self.__config.get('pushover', 'pushover.api_key'))
def send(self):
self.__client.send_message(self.__packpub_info['description'].encode('utf-8'), title="New book downloaded from Packt: " + self.__packpub_info['title'].encode('utf-8'), url="https://www.packtpub.com/packt/offers/free-learning", url_title="See more")
log_success('[+] notification sent to pushover')
def sendError(self, exception, source):
self.__client.send_message(repr(exception), title='packtpub-crawler {source}: Could not download ebook'.format(source=source))
log_success('[+] error notification sent to pushover')
示例10: __init__
def __init__(self, apitoken, cache_path, pushover_apikey, pushover_userkey):
""" init method, run at class creation """
logger.debug("Connecting to GitHub")
self._gh = login(token=apitoken)
logger.info("Connected to GitHub API")
self._cache_path = os.path.abspath(os.path.expanduser(cache_path))
self._cache = self._get_cache()
self._pushover = Client(pushover_userkey, api_token=pushover_apikey)
logger.info('Connected to Pushover for user %s', pushover_userkey)
示例11: PushoverNotificationService
class PushoverNotificationService(BaseNotificationService):
""" Implements notification service for Pushover. """
def __init__(self, user_key, api_token):
from pushover import Client
self._user_key = user_key
self._api_token = api_token
self.pushover = Client(
self._user_key, api_token=self._api_token)
def send_message(self, message="", **kwargs):
""" Send a message to a user. """
from pushover import RequestError
try:
self.pushover.send_message(message, title=kwargs.get(ATTR_TITLE))
except RequestError:
_LOGGER.exception("Could not send pushover notification")
示例12: __init__
def __init__(self, pokemon, bot):
self.pokemon = pokemon
self.api = bot.api
self.bot = bot
self.position = bot.position
self.config = bot.config
self.pokemon_list = bot.pokemon_list
self.item_list = bot.item_list
self.inventory = bot.inventory
self.client = Client(self.config.pushover_user_key, api_token=self.config.pushover_api_token)
示例13: main
def main():
init(PUSHOVER_TOKEN)
pushover = Client(PUSHOVER_KEY)
tz = pytz.timezone(TIMEZONE)
now = tz.normalize(datetime.utcnow().replace(tzinfo=pytz.utc))
card_number = os.getenv('CARD_NUMBER')
db = Database(DATABASE_URL)
current_value = db.get_balance()
edenred_value = balance(int(card_number))
print '{0}\t{1}\t{2}'.format(now, current_value, edenred_value)
if current_value != edenred_value:
delta = edenred_value - current_value
db.add_balance(edenred_value)
message = 'Edenred {3}. Previous {0}. Current {1}. Delta {2}.'.format(
current_value,
edenred_value,
delta,
now.strftime('%Y-%m-%d %H:%M:%S'))
pushover.send_message(message, title='Edenred')
示例14: main
def main():
client = Client("<user-key>", api_token="<api-token>")
while 1:
# transition from ACKNOWLEDGED to READY
write_stdout('READY\n')
# read header line and print it to stderr
line = sys.stdin.readline()
# read event payload and print it to stderr
headers = dict([ x.split(':') for x in line.split() ])
data = sys.stdin.read(int(headers['len']))
data_dic = dict([ x.split(':') for x in data.split()])
group_name = data_dic.get('groupname')
process_name = data_dic.get('processname')
pid = data_dic.get('pid')
from_state = data_dic.get('from_state')
message = "{} with the pid {} just stopped.".format(process_name, pid)
client.send_message(message, title=group_name)
# transition from READY to ACKNOWLEDGED
write_stdout('RESULT 2\nOK')
示例15: PushoverClient
class PushoverClient(PushNotificationClient):
_client = None
_api_token = "aYBH7B28vQCKopoJXGCnwQ5NhPTG9w"
def get_name(self):
return "Pushover"
def set_api_key(self, api):
try:
self._client = Client(user_key=api, api_token=self._api_token)
except Exception as e:
self._logger.exception(str(e))
def send_message(self, title, msg):
try:
self._client.send_message(title=title, message=msg)
except Exception as e:
self._logger.exception(str(e))
def set_logger(self, logger):
pass