def notify_pushover(is_success, status, stack_name): """ send notification via pushover """ msg = 'Operation on stack {n} finished with status {s}'.format(n=stack_name, s=status) title = '{n}: {s}'.format(n=stack_name, s=status) if is_success: req = Client().send_message(msg, title=title, priority=0) else: req = Client().send_message(msg, title=title, priority=0, sound='falling')
def SendMessage(apiKey, clientkey, tit, mess, pri): init(apiKey) if pri == 2 or pri == "2": Client(clientKey).send_message(mess, title=tit, priority=pri, expire=120, retry=60) else: Client(clientKey).send_message(mess, title=tit, priority=pri)
def notify_pushover(result, job_name, build_no, duration, build_url): """ send notification via pushover """ msg = '{r}: {j} #{b} finished in {d} <{u}>'.format(r=result, j=job_name, b=build_no, d=duration, u=build_url) title = '{r}: {j} #{b}'.format(r=result, j=job_name, b=build_no) if result != "SUCCESS": req = Client().send_message(msg, title=title, priority=0, sound='falling') else: req = Client().send_message(msg, title=title, priority=0)
def notify_pushover(self, status, org, project, build_num, build_url, duration): """ send notification via pushover """ msg = '{s}: {o}/{p} #{b} finished in {d} <{u}>'.format( s=status, o=org, p=project, b=build_num, d=duration, u=build_url ) title = '{s}: {o}/{p} #{b}'.format( s=status, o=org, p=project, b=build_num ) argv = { 'title': title, 'priority': 0 } if not self._build_status_is_good(status): argv['sound'] = 'falling' logger.debug('Sending pushover notification; msg="%s" argv=%s', msg, argv) Client(self._pushover_userkey).send_message(msg, **argv)
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 init(self): """ Initializes the notification. :return: None :rtype: None """ self._client = Client(self._userkey, api_token=self._apikey)
def sendPush(messageToSend, title): __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'pushoverConfig.json')) as f: data = json.load(f) for user in data["users"]: Client(user["key"], api_token=data["apiKey"]).send_message(messageToSend, title=title, sound="tugboat")
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)
def send_message(message): client = Client(po_key, api_token=po_token) client.send_message(message, title="Docker Event") ## global pb_key ## pb = Pushbullet(pb_key) ## pb.push_note("Docker Event", message) pass
def push(self, msg): try: Client(self.config['KEY']).send_message(msg, title = self.config['TITLE']) except Exception: Log.log_error(traceback.format_exc()) return False return True
def send_notification(shop, url): try: for user in users: print("Message to: "+user, flush=True) client = Client(users[user], api_token=Config.PUSHOVERTOKEN) client.send_message('PS5 beschikbaar bij {}. Click link:'.format(shop), title="PS5 in Stock!", url=url) except: print("Error trying to send push notification") try: email = "*****@*****.**" password = Config.EMAILPW subject = "PS5 op voorraad bij {}".format(shop) message = "Link {}".format(url) msg = MIMEMultipart() msg["From"] = email msg["To"] = ", ".join(send_to_email) msg["Subject"] = subject msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, send_to_email, text) server.quit() except: print("Failed to send email")
def generate_weekly_report(): today = localdate(now()) last_week_sun = today + relativedelta(weekday=SU(-1)) last_week_mon = last_week_sun + relativedelta(weekday=MO(-1)) for user in User.objects.filter(pushover_user_key__isnull=False, pushover_api_token__isnull=False): totals = (ReportEntry.objects.filter( station__owner=user, created__gte=last_week_mon, created__lte=last_week_sun).values("phone_number").annotate( total_refund=Sum("station__refund_value"))) message = "\n".join([ f"{total.get('phone_number', 'anonymous')}: ${total.get('total_refund')}" for total in totals ]) if message: Client( user_key=user.pushover_user_key, api_token=user.pushover_api_token ).send_message( message, title= f"Todovoodoo: Weekly Refund Report ({last_week_mon.isoformat()} -- {last_week_sun.isoformat()})", priority=1, )
def mainloop(): """This function is the clock generator of this program This function creates the loop which checks if any changes on a given website occur over time. """ while True: check_for_update() ''' print("Original: ", original_md5sum) print("New: ", new_md5sum) ''' if Md5.original_md5sum == Md5.new_md5sum: print("Website hasn't been updated yet... " + datetime.now().strftime('%Y-%m-%d %H:%M:%S')) else: print("Website hat been updated! " + datetime.now().strftime('%Y-%m-%d %H:%M:%S')) if Settings.push: init("<email_key>") Client("<website_key>\ ").send_message("Website has been updated!", title="Website update") if Settings.music: p = vlc.MediaPlayer("file:///home/felix/Music/\ The_next_episode.mp3") p.play() time.sleep(60) p.stop() break time.sleep(Settings.update_timer)
def notify(job, title, body): # Send notificaions # title = title for notification # body = body of the notification if job.config.PB_KEY != "": try: from pushbullet import Pushbullet pb = Pushbullet(job.config.PB_KEY) pb.push_note(title, body) except: # noqa: E722 logging.error( "Failed sending PushBullet notification. Continueing processing..." ) if job.config.IFTTT_KEY != "": try: import pyfttt as pyfttt event = job.config.IFTTT_EVENT pyfttt.send_event(job.config.IFTTT_KEY, event, title, body) except: # noqa: E722 logging.error( "Failed sending IFTTT notification. Continueing processing..." ) if job.config.PO_USER_KEY != "": try: from pushover import init, Client init(job.config.PO_APP_KEY) Client(job.config.PO_USER_KEY).send_message(body, title=title) except: # noqa: E722 logging.error( "Failed sending PushOver notification. Continueing processing..." )
def watch(self): s = Query() arps = self.api(cmd='/ip/arp/print') leases = self.api(cmd='/ip/dhcp-server/lease/print') for x in arps: try: if db.search(s['mac-address'] == x['mac-address']): print("ALREADY KNOWN {}".format(x['mac-address'])) else: print("FOUND NEW MAC ADDRESS {}".format(x['mac-address'])) db.insert(x) try: ip = x['address'] except: ip = "Not Available" try: for l in leases: if x['mac-address'] == l['mac-address']: deets = l except: deets = {} Client(user_key).send_message( "New Device On The Network {} - {}\n\n{}".format( ip, x['mac-address'], deets), title="New MAC Address Found") except: pass
def send_push_request_accepted_if_token(pickUpRequest, user): if user.profile.pushover: client = Client(user.profile.pushover, api_token="ad9ohz7ege8sr2ejv3t3asfcnszyr9") client.send_message("Your PickUp Request to "+str(pickUpRequest.destination.title)+" was accepted. " + "The drivers phone number is " + pickUpRequest.ride.user.profile.phone, title="PickUp Request accepted", url="https://hitchcar.pillo.ch/#/home", url_title="Open Hitchcar")
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_notification(notification): if not API_TOKEN: print 'No Pushover API token set' return client = Client(USER_KEY, api_token=API_TOKEN) client.send_message(notification.body, title=notification.title)
def __init__(self, notif_queue): Thread.__init__(self) self.notif_queue = notif_queue init(app_token) self.members = [Client(client_token)] # Mine self.last_pinged = time()
def alert(text, **kwargs): """ >>> alert("Doctest",title="Title", sound="magic",url="https://school4one.com/",attachment=genimage(),url_title="School 4 One Link") 'OK' """ client = Client(user, api_token=token) client.send_message(text, html=1, **kwargs) return 'OK'
def SendPushNotification(): nl = "\n" today = "Energy: " + str(push_energy) + energy_units current = "Power: " + str(push_power) + power_units message = TimeStamp() + nl + today + nl + current logger.info("Push Notification:") logger.info(message) Client(pushover_userkey).send_message(message, title="Solar Production")
def __init__(self, user_key, api_token, is_allowed_path, local_www_path): """Initialize the service.""" from pushover import Client self._user_key = user_key self._api_token = api_token self._is_allowed_path = is_allowed_path self._local_www_path = local_www_path self.pushover = Client(self._user_key, api_token=self._api_token)
def __init__(self, settings): """Construct the object based on settings.""" self.client = Client( settings["pushover_user_key"], api_token=settings["pushover_api_token"] ) if settings["pushover-enabled"]: self.enabled = True else: self.enabled = False
def __init__(self): # public: self.config = configparser.ConfigParser() self.config.read('/etc/shannon.conf') self.token = self.config["PUSH"]["Token"] self.user_id = self.config["PUSH"]["UserId"] # private: self.__client = Client(self.user_id, api_token=self.token)
def SendErrorPushNotification(): nl = "\n" error = "Production Error" current = "Power " + str(push_power) + power_units message = TimeStamp() + nl + error + nl + current logger.info("Push Notification - Error:") logger.info(message) Client(pushover_userkey).send_message(message, title="Solar Production Error")
async def pubmsg(user, channel, worldboss, zone): log.debug(f'Executing pubmsg routine for [{worldboss}] in [{zone}]') userdata['0'] = str(int(datetime.now().timestamp())) userdata['1'] = {'boss': worldboss, 'zone': zone} saveuserdata() msg = f"**{len(userdata)-4}** players are being notified\nType {prefix}alert addme to get World Boss alerts" embed = discord.Embed(title=f"{worldboss.title()} is UP in {zone.title()}, Log in Now!", description=msg, color=SUCCESS_COLOR) embed.set_footer(text=f'World Boss Broadcast System') channel = bot.get_channel(int(announce_chan)) channel2 = bot.get_channel(int(announce_chan2)) try: for guild in bot.guilds: everyone = get(guild.roles, id=int(everyone_id)) everyone2 = get(guild.roles, id=int(everyone_id2)) except: log.exception('Error while parsing guild roles') try: await channel.send(everyone.mention) await channel.send(embed=embed) except: log.exception('Error while sending channel1 notification') if channel2 is not None: try: await channel2.send(everyone2.mention) await channel2.send(embed=embed) except: log.exception('Error while sending channel2 notification') smsmsg = f'{worldboss.title()} is up in {zone.title()}!\n\nReply STOP to end these notifications permanently' log.debug(f'Sending AWS SNS notification to topic [{topic_arn}]') try: snsresponse = sns.publish(TopicArn=topic_arn, Message=smsmsg) except: log.exception('Error in AWS SNS topid send') # pprint(snsresponse) ################################################################### pomsg = f'{worldboss.title()} is up in {zone.title()}!' pmmsg = f'{worldboss.title()} is up in {zone.title()}!\nType !alert remove to stop these alerts' for uid, udata in userdata.items(): if uid != '0' and uid != '1' and uid != '2' and uid != '3': if udata['alert'] == '1': log.debug(f'Sending discord PM notification to [{uid}]') try: duser = bot.get_user(int(uid)) await duser.send(pmmsg) except: log.exception('Error in pm send') await sleep(.1) elif udata['alert'] == '2': log.debug(f'Sending pushover notification to [{uid}]') if BRANCH != 'develop': try: Client(udata['pushover_id']).send_message(pomsg, title="World Boss Alert") await sleep(1) except: log.exception('Error in pushover send') else: log.warning('Skipping actual pushover notifications due to DEV MODE') await logchan(user, channel, worldboss, zone)
def act(item): webbrowser.open(item.url) engine = pyttsx3.init() engine.say("It's there!") engine.runAndWait() client = Client("<PUSHOVER CLIENT API>", api_token="<API TOKEN>") client.send_message(item.url, title=item.name + ": " + item.price)
def send_pushover(title, message): if USER_KEY is None or API_TOKEN is None: print("missing pushover credentials") return -1 global PUSHOVER_CLIENT if PUSHOVER_CLIENT is None: PUSHOVER_CLIENT = Client(USER_KEY, api_token=API_TOKEN) PUSHOVER_CLIENT.send_message(f"{message}", title=f"{title}") print("sent pushover")
def pushover(message): """Sends a push notification via Pushover.""" from pushover import Client, InitError try: Client().send_message(message, title="Changes to the Counted", url="https://github.com/{}/{}/commits/{}".format( GITHUB_USER, GITHUB_REPO, GITHUB_BRANCH)) except InitError: pass
def pushover(app_key, ptitle, message): try: client = Client(config.get('pushover', 'user_key'), api_token=app_key) client.send_message(message, title=ptitle) except Exception as e: log.error('Pushover notification failed. Error: %s' % str(e)) return False else: log.debug('Pushover notification sent. Title: {}'.format(ptitle)) return True