本文整理汇总了Python中pushover.Client.send_message方法的典型用法代码示例。如果您正苦于以下问题:Python Client.send_message方法的具体用法?Python Client.send_message怎么用?Python Client.send_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pushover.Client
的用法示例。
在下文中一共展示了Client.send_message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PushoverNotificationService
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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: Pushover
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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')
示例7: PushoverNotificationService
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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")
示例8: main
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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')
示例9: main
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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')
示例10: PushoverClient
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
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
示例11: open
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
import time
from pushover import Client
start_time = time.time() # 初始时间戳
now = time.strftime("%Y%m%d", time.localtime()) # 当前日期戳
file_name = 'PushOver' # 文件名
path_prefix = '/Users/alicewish/我的坚果云/' # 文件地址前缀
txt_file_path = path_prefix + file_name + '.txt' # TXT文件名
# ================按行读取文本:with open(更好)================
text_readline = [] # 初始化按行存储数据列表,不接受结尾换行符
with open(txt_file_path) as fin:
for line in fin:
text_readline.append((line).replace('\n', ''))
my_user_key = text_readline[0]
my_api_token = text_readline[1]
client = Client(my_user_key, api_token=my_api_token)
client.send_message("测试内容……" + now, title="标题", sound="cosmic")
# send_message可用关键字包括title, priority, sound, callback, timestamp, url, url_title, device, retry
# ================运行时间计时================
run_time = time.time() - start_time
if run_time < 60: # 两位小数的秒
print("耗时:{:.2f}秒".format(run_time))
elif run_time < 3600: # 分秒取整
print("耗时:{:.0f}分{:.0f}秒".format(run_time // 60, run_time % 60))
else: # 时分秒取整
print("耗时:{:.0f}时{:.0f}分{:.0f}秒".format(run_time // 3600, run_time % 3600 // 60, run_time % 60))
示例12: notify
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
def notify(message):
init(cfg['pushover_api'])
client = Client(cfg['pushover_user'])
client.send_message(message, title="Cat Alert")
示例13: send_pushover_notification
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
def send_pushover_notification(message, title):
client = Client(conf.PUSHOVER_USER, api_token=conf.PUSHOVER_API_TOKEN)
return client.send_message(message, title=title, html=1)
示例14: send_to_pushover
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
def send_to_pushover(astring):
client = Client(USER_KEY, api_token = API_TOKEN)
astring = "***Coastalwatch Report***\n" + astring
client.send_message(astring)
示例15: RaidStatusChecker
# 需要导入模块: from pushover import Client [as 别名]
# 或者: from pushover.Client import send_message [as 别名]
class RaidStatusChecker(object):
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")
@suppression_window
def check_btrfs_stats(self):
for mount_point in self.btrfs_mount_points:
stats_filename = "%s/btrfs-stats_%s.p" % (self.data_dir, mount_point[1:].replace("/", "-"))
device_stats = {}
if os.path.exists(stats_filename):
device_stats = pickle.load(open(stats_filename, "rb"))
status = check_output(["sudo", "btrfs", "device", "stats", mount_point]).decode("utf-8").strip()
new_errors = False
regex = re.compile('\[/dev/(.*)\]\.(\S*)\s*(\d*)')
for line in status.split('\n'):
match = regex.match(line)
if match is not None:
if match.group(1) not in device_stats:
device_stats[match.group(1)] = {}
previous_stats = device_stats[match.group(1)].get(match.group(2), 0)
if int(match.group(3)) > previous_stats:
device_stats[match.group(1)][match.group(2)] = int(match.group(3))
new_errors = True
if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir)
pickle.dump(device_stats, open(stats_filename, "wb"))
if new_errors is not False:
self.client.send_message(status, title="BTRFS Errors: %s" % mount_point)
@suppression_window
def check_btrfs_drives(self):
status = check_output(["sudo", "btrfs", "fi", "show", "-d"]).decode("utf-8").strip()
regex = re.compile('(missing|warning)')
if regex.match(status) is not None:
self.client.send_message(status, title="BTRFS Array Error")
@suppression_window
def check_zfs_drives(self):
status = check_output(["sudo", "zpool", "status", "-x"])
if status != "all pools are healthy":
self.client.send_message(status, title="ZFS Array Error")
def run(self):
if self.zfs_enabled:
self.check_zfs_drives()
if self.btrfs_enabled:
self.check_btrfs_stats()
self.check_btrfs_drives()