def _setup(self): self.apobj = apprise.Apprise() self.tags = {} # first load configfile if specified tags = self.settings.get("tags", "") configfile = self.settings.get("configfile", "") self.log.debug("%s - %s" % (tags, configfile)) if tags and configfile: if configfile[:1] != "/": configfile = "/opt/mycroft/skills/apprise-skill/" + configfile self.log.debug("configfile - %s" % configfile) if os.path.isfile(configfile): config = apprise.AppriseConfig() config.add(configfile) self.apobj.add(config) taglist = tags.split(",") self.log.debug("taglist: %s" % taglist) for t in taglist: self.tags[t.strip().lower()] = t.strip() else: self.log.warn("config file does not exist: %s" % configfile) # second load tags and service-urls from settings for i in range(1, 4): tag = self.settings.get("tag{}".format(i), "") service = self.settings.get("service{}".format(i), "") if tag and service: self.tags[tag.lower()] = tag self.apobj.add(service, tag=tag) self.log.debug("tags - %s" % self.tags)
def __init__(self, config: ConfigHelper) -> None: self.config = config name_parts = config.get_name().split(maxsplit=1) if len(name_parts) != 2: raise config.error(f"Invalid Section Name: {config.get_name()}") self.server = config.get_server() self.name = name_parts[1] self.apprise = apprise.Apprise() self.warned = False self.attach_requires_file_system_check = True self.attach = config.get("attach", None) if self.attach is None or \ (self.attach.startswith("http://") or self.attach.startswith("https://")): self.attach_requires_file_system_check = False url_template = config.gettemplate('url') self.url = url_template.render() if len(self.url) < 2: raise config.error(f"Invalid url for: {config.get_name()}") self.title = config.gettemplate('title', None) self.body = config.gettemplate("body", None) self.events: List[str] = config.getlist("events", separator=",") self.apprise.add(self.url)
def notification_runner(): while not app.config.exit.is_set(): try: # At the moment only one thread runs (single runner) n_object = notification_q.get(block=False) except queue.Empty: time.sleep(1) pass else: import apprise # Create an Apprise instance try: apobj = apprise.Apprise() for url in n_object['notification_urls']: apobj.add(url.strip()) apobj.notify( body=n_object['watch_url'], # @todo This should be configurable. title="ChangeDetection.io Notification - {}".format( n_object['watch_url'])) except Exception as e: print("Watch URL: {} Error {}".format(n_object['watch_url'], e))
def send_notification(title, body): """Send notification.""" hostname = socket.gethostname() recipient = RECIPIENTS.get(hostname, "*****@*****.**") # This allows to run the scripts even when no notification can be send. home = Path(os.environ.get("HOME") or os.environ.get("HOMEPATH")) credentials = home / ".credentials" if not credentials.exists(): warnings.warn("No configuration file for notifications available.") sys.exit(0) credentials = json.loads(credentials.read_text()) message_header = { "domain": "gmail.com", "to": recipient, "name": "respy", **credentials, } service = "mailto://{username}:{password}@{domain}?to={to}&name={name}" apobj = apprise.Apprise() apobj.add(service.format(**message_header)) apobj.notify(title=title, body=body)
def send_notifications(sonarr_series_id, sonarr_episode_id, message): providers = get_notifier_providers() series = get_series(sonarr_series_id) series_title = series['title'] series_year = series['year'] if series_year not in [None, '', '0']: series_year = ' ({})'.format(series_year) else: series_year = '' episode = get_episode_name(sonarr_episode_id) asset = apprise.AppriseAsset(async_mode=False) apobj = apprise.Apprise(asset=asset) for provider in providers: if provider['url'] is not None: apobj.add(provider['url']) apobj.notify( title='Bazarr notification', body="{}{} - S{:02d}E{:02d} - {} : {}".format(series_title, series_year, episode[1], episode[2], episode[0], message), )
def update_notifier(): # define apprise object a = apprise.Apprise() # Retrieve all of the details results = a.details() notifiers_new = [] notifiers_old = [] conn_db = sqlite3.connect(os.path.join(config_dir, 'db', 'bazarr.db'), timeout=30) c_db = conn_db.cursor() notifiers_current = c_db.execute('SELECT name FROM table_settings_notifier').fetchall() for x in results['schemas']: if x['service_name'] not in str(notifiers_current): notifiers_new.append(x['service_name']) logging.debug('Adding new notifier agent: ' + x['service_name']) else: notifiers_old.append(x['service_name']) notifier_current = [i[0] for i in notifiers_current] notifiers_to_delete = list(set(notifier_current) - set(notifiers_old)) for notifier_new in notifiers_new: c_db.execute('INSERT INTO `table_settings_notifier` (name, enabled) VALUES (?, ?);', (notifier_new, '0')) for notifier_to_delete in notifiers_to_delete: c_db.execute('DELETE FROM `table_settings_notifier` WHERE name=?', (notifier_to_delete,)) conn_db.commit() c_db.close()
def update_notifier(): # define apprise object a = apprise.Apprise() # Retrieve all of the details results = a.details() notifiers_new = [] notifiers_old = [] notifiers_current_db = database.execute( "SELECT name FROM table_settings_notifier") notifiers_current = [] for notifier in notifiers_current_db: notifiers_current.append(notifier['name']) for x in results['schemas']: if x['service_name'] not in notifiers_current: notifiers_new.append(x['service_name']) logging.debug('Adding new notifier agent: ' + x['service_name']) else: notifiers_old.append(x['service_name']) notifier_current = [i for i in notifiers_current] notifiers_to_delete = list(set(notifier_current) - set(notifiers_old)) for notifier_new in notifiers_new: database.execute( "INSERT INTO table_settings_notifier (name, enabled) VALUES (?, ?)", (notifier_new, 0)) for notifier_to_delete in notifiers_to_delete: database.execute("DELETE FROM table_settings_notifier WHERE name=?", (notifier_to_delete, ))
def get_service(hass, config, discovery_info=None): """Get the Apprise notification service.""" # Create our Apprise Asset Object asset = apprise.AppriseAsset(async_mode=False) # Create our Apprise Instance (reference our asset) a_obj = apprise.Apprise(asset=asset) if config.get(CONF_FILE): # Sourced from a Configuration File a_config = apprise.AppriseConfig() if not a_config.add(config[CONF_FILE]): _LOGGER.error("Invalid Apprise config url provided") return None if not a_obj.add(a_config): _LOGGER.error("Invalid Apprise config url provided") return None if config.get(CONF_URL): # Ordered list of URLs if not a_obj.add(config[CONF_URL]): _LOGGER.error("Invalid Apprise URL(s) supplied") return None return AppriseNotificationService(a_obj)
def update_notifier(): # define apprise object a = apprise.Apprise() # Retrieve all of the details results = a.details() notifiers_new = [] notifiers_old = [] notifiers_current_db = database.execute("SELECT name FROM table_settings_notifier") notifiers_current = [] for notifier in notifiers_current_db: notifiers_current.append([notifier['name']]) for x in results['schemas']: if [x['service_name']] not in notifiers_current: notifiers_new.append([x['service_name'], 0]) logging.debug('Adding new notifier agent: ' + x['service_name']) else: notifiers_old.append([x['service_name']]) notifiers_to_delete = [item for item in notifiers_current if item not in notifiers_old] database.execute("INSERT INTO table_settings_notifier (name, enabled) VALUES (?, ?)", notifiers_new, execute_many=True) database.execute("DELETE FROM table_settings_notifier WHERE name=?", notifiers_to_delete, execute_many=True)
def telegram_text(message): # create an Apprise instance apobj = apprise.Apprise() # Adding telegram id apobj.add( 'tgram://1436452271:AAH06lhnvlTMVg_TZKpw7fhZ7VjtRhZ2LLg/110473419/') # Sending notification apobj.notify(body=message)
def get_apprise_client(config): """Return Apprise instance.""" apprise_client = apprise.Apprise() for conf in config: apprise_client.add(conf) return apprise_client
def messaging(title, body): apobj = apprise.Apprise() if config['Notification']['Pushover']: apobj.add(config['Notification']['Pushover']) apobj.notify( title=title, body=body, )
def test_notification(protocol, provider): provider = unquote(provider) apobj = apprise.Apprise() apobj.add(protocol + "://" + provider) apobj.notify(title='Bazarr test notification', body='Test notification') return '', 200
def notify(self, urls: List[str], title: str, body: str = None): """Notify""" apobj = apprise.Apprise() for url in urls: apobj.add(url) apobj.notify(title=title, body=body)
def plugin(srv, item): """Send a message to a single Apprise plugin.""" srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target) sender = item.config.get('sender') sender_name = item.config.get('sender_name') baseuri = item.config['baseuri'] addresses = item.addrs title = item.title body = item.message try: srv.logging.debug( "Sending notification to Apprise. target=%s, addresses=%s" % (item.target, addresses)) to = ','.join(addresses) # Create an Apprise instance. apobj = apprise.Apprise(asset=apprise.AppriseAsset(async_mode=False)) # Collect URL parameters. params = OrderedDict() if sender: params["from"] = sender if to: params["to"] = to if sender_name: params["name"] = sender_name # Add notification services by server url. uri = baseuri if params: uri += '?' + urlencode(params) apobj.add(uri) # Submit notification. outcome = apobj.notify( body=body, title=title, ) if outcome: srv.logging.info("Successfully sent message using Apprise") return True else: srv.logging.error("Sending message using Apprise failed") return False except Exception as e: srv.logging.error( "Sending message using Apprise failed. target=%s, error=%s" % (item.target, e)) return False
def __init__(self): if not os.path.exists(APPRISE_CONFIG_PATH): raise RuntimeError("No Apprise config found.") config = apprise.AppriseConfig() config.add(APPRISE_CONFIG_PATH) self.apobj = apprise.Apprise() self.apobj.add(config) self.queue = queue.Queue()
def __init__(self, enabled=True): if enabled and path.exists(APPRISE_CONFIG_PATH): self.apobj = apprise.Apprise() config = apprise.AppriseConfig() config.add(APPRISE_CONFIG_PATH) self.apobj.add(config) self.queue = queue.Queue() self.start_worker() self.enabled = True else: self.enabled = False
def send_notifications(target_gpu, notification_type, notifications): for name, service in notifications['services'].items(): logging.info(f'Sending notifications to {name}') apobj = apprise.Apprise() apobj.add(service['url']) title = f"Alert - {target_gpu['name']} {notification_type}" msg = notifications[notification_type]['message'] if service['screenshot']: apobj.notify(title=title, body=msg, attach='screenshot.png') else: apobj.notify(title=title, body=msg)
def __init__(self, config: dict = None): if config is None: config = ambianic.config self.apobj = apprise.Apprise(debug=True) self.config = config.get("notifications", {}) for name, cfg in self.config.items(): providers = cfg.get("providers", []) for provider in providers: if not self.apobj.add(provider, tag=name): log.warning("Failed to add notification provider: %s=%s" % (name, provider))
def iphone(title="python notification", body=os.path.basename(__file__)): """ usage: import notify sentence = "lets eat trail snacks" notify.iphone(sentence,sp.sentence(sentence)[2]) """ apobj = apprise.Apprise() # A pushbullet notification apobj.add(pbul) apobj.notify(body, title)
def send_notifications(self, notification_type): for name, service in self.config['services'].items(): logging.info(f'Sending notifications to {name}') apobj = apprise.Apprise() apobj.add(service['url']) title = f"{notification_type.replace('-',' ').title()} - {self.gpu['name']}" msg = self.config[notification_type]['message'] if service['screenshot']: apobj.notify(title=title, body=msg, attach='screenshot.png') else: apobj.notify(title=title, body=msg)
def test_notification(protocol, provider): provider = unquote(provider) asset = apprise.AppriseAsset(async_mode=False) apobj = apprise.Apprise(asset=asset) apobj.add(protocol + "://" + provider) apobj.notify(title='Bazarr test notification', body='Test notification') return '', 200
def plugin(srv, item): """Send a message to Apprise plugin(s).""" srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target) addresses = item.addrs if not addresses: srv.logging.warning("Skipped sending notification to Apprise %s, " "no addresses configured" % (item.target)) return False sender = item.config.get('sender') sender_name = item.config.get('sender_name') baseuri = item.config['baseuri'] title = item.title body = item.message try: srv.logging.debug("Sending notification to Apprise %s, addresses: %s" % (item.target, addresses)) to = ','.join(addresses) # Create an Apprise instance. apobj = apprise.Apprise(asset=apprise.AppriseAsset(async_mode=False)) # Add notification services by server url. uri = '{baseuri}?from={sender}&to={to}'.format(baseuri=baseuri, sender=sender, to=to) if sender_name: uri += '&name={sender_name}'.format(sender_name=sender_name) apobj.add(uri) # Submit notification. outcome = apobj.notify( body=body, title=title, ) if outcome: srv.logging.info("Successfully sent message using Apprise") return True else: srv.logging.error("Sending message using Apprise failed") return False except Exception as e: srv.logging.error("Error sending message to %s: %s" % (item.target, e)) return False
def send_message(message): if not message: return print(message) apobj = apprise.Apprise() apobj.add('gotify://' + gotify_address + '/' + gotify_token) apobj.notify( body=message, title='Homelab', )
def post_to_discord(title, body, attach): asyncio.set_event_loop(asyncio.new_event_loop()) app = apprise.Apprise() app.add("discord://{}/{}/?avatar={}".format( os.environ["DISCORD_WEBHOOK_ID"], os.environ["DISCORD_WEBHOOK_TOKEN"], CUSTOM_AVATAR )) app.notify( title=title, body=body, attach=attach )
def apprise_url_validator(url: str) -> bool: """Validate a apprise URL""" if url is not None: apobj = apprise.Apprise() status = apobj.add(url) del apobj if status: return status raise ValidationError("Invalid Apprise URL") return True
def apprise_notify(sid, data): """ Send Notification on Apprise """ url = os.getenv("DBNET_APPRISE_URL") apobj = apprise.Apprise() apobj.add(url) apobj.notify( title=data['title'], body=data['body'], ) log(f'''Sent notification: "{data['title']}"''') return 'OK'
def send_notifications_movie(radarrId, message): providers = get_notifier_providers() movie = get_movies_name(radarrId) apobj = apprise.Apprise() for provider in providers: if provider[1] is not None: apobj.add(provider[1]) apobj.notify( title='Bazarr notification', body=movie + ' : ' + message, )
def send_notifications_movie(radarr_id, message): providers = get_notifier_providers() movie = get_movies_name(radarr_id) apobj = apprise.Apprise() for provider in providers: if provider['url'] is not None: apobj.add(provider['url']) apobj.notify( title='Bazarr notification', body="{} : {}".format(movie, message), )
def send_message(message: str) -> bool: # apprise notifications - https://github.com/caronc/apprise nefarious_settings = NefariousSettings.get() if nefarious_settings.apprise_notification_url: apprise_instance = apprise.Apprise() apprise_instance.add(nefarious_settings.apprise_notification_url) try: return apprise_instance.notify(body=message, ) except Exception as e: logger_background.warning( 'apprise notification error for url {}'.format( nefarious_settings.apprise_notification_url)) logger_background.exception(e) return False return False