当前位置: 首页>>代码示例>>Python>>正文


Python pushover.Client类代码示例

本文整理汇总了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")
开发者ID:arsaboo,项目名称:home-assistant,代码行数:35,代码来源:pushover.py

示例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!")
开发者ID:opendata-stuttgart,项目名称:feinstaub-monitoring-client-python,代码行数:30,代码来源:monitor.py

示例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")
开发者ID:vlefevre86,项目名称:Manga,代码行数:9,代码来源:manga.py

示例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')
开发者ID:MrTam,项目名称:sonosmon,代码行数:54,代码来源:sonosmon.py

示例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'])
开发者ID:lmarton,项目名称:RaspiBell,代码行数:11,代码来源:DoorBell.py

示例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)
开发者ID:Baltibu,项目名称:home-assistant,代码行数:7,代码来源:pushover.py

示例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)
开发者ID:arsaboo,项目名称:home-assistant,代码行数:7,代码来源:pushover.py

示例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")
开发者ID:tlusk,项目名称:raid-status-notifier,代码行数:8,代码来源:main.py

示例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')
开发者ID:niqdev,项目名称:packtpub-crawler,代码行数:17,代码来源:mypushover.py

示例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)
开发者ID:jantman,项目名称:misc-scripts,代码行数:9,代码来源:github_issue_watch_pushover.py

示例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")
开发者ID:FanaHOVA,项目名称:home-assistant,代码行数:18,代码来源:pushover.py

示例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)
开发者ID:maxroustan,项目名称:PokemonGo-Bot,代码行数:10,代码来源:pokemon_catch_worker.py

示例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')
开发者ID:mpapierski,项目名称:eden,代码行数:19,代码来源:edenred.py

示例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')
开发者ID:Scriptkiddi,项目名称:supervisor_pushover_eventlistener,代码行数:21,代码来源:__main__.py

示例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
开发者ID:smartycoder,项目名称:DSVideoMonitor,代码行数:22,代码来源:PushoverClient.py


注:本文中的pushover.Client类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。