def setup(bot): global PUSHOVER, SMTP table_name = bot.config.notify.table_name #ToDO: Check that we have a service to notify if PUSHOVER: app_api = bot.config.notify.pushover_app_api if app_api and app_api is not 'none': pushover.init(app_api) else: PUSHOVER = False if EMAIL: email_address = bot.config.notify.email_address email_server = bot.config.notify.email_server email_port = bot.config.notify.email_port email_username = bot.config.notify.email_username email_password = bot.config.notify.email_password SMTP = smtplib.SMTP(email_server, email_port) if email_username and email_password: SMTP.login(email_username, email_password) columns = ['pkey', 'nick', 'service', 'parameter'] pkey = columns[0] willie_db = willie.db.WillieDB(bot.config) connect = willie_db.connect() if not willie_db.check_table(table_name, columns, pkey): connect.execute( "CREATE TABLE notifydb (pkey integer NOT NULL, nick string, service string, parameter string, PRIMARY KEY (pkey));" ) connect.commit() connect.close()
def main(): # Leggo i parametri di configurazione if os.path.exists("config.txt") is True: global config config = ConfigParser() config.read("config.txt") comune = config.get("fibraclick", "comune") sede_clli = config.get("fibraclick", "sede_clli") onu_ids = config.get("fibraclick", "onu_ids").split(',') api_token = config.get("pushover", "api_token") user_key = config.get("pushover", "user_key") statusonus = config.get("stati", "statusonus").split('|') statuscomune = config.get("stati", "statuscomune") else: print "Impossibile leggere il file di configurazione." print "Editare i parametri del file config.sample.txt e rinominarlo in config.txt!" exit() # Inizializzo PushOver if api_token: init(api_token) else: print "Parametri Pushover assenti, impossibile inviare eventuale notifica push." if sede_clli and onu_ids: check_clli_and_onus(sede_clli, onu_ids, statusonus, api_token, user_key) # Se viene indicato il comune e non la sede Clli o ONU effettuo verifiche sullo stato di attivazione del coume if comune and not (sede_clli and onu_ids): check_comune(comune, statuscomune, api_token, user_key)
def check_url_status(url, delay, pushover_key, pushover_token): while True: request = urllib.request.Request(url) request.add_header( 'User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' ) url_status = urllib.request.urlopen(request).status if url_status not in IGNORED_STATUES: msg = "[{}]: {}".format( url_status, http.server.SimpleHTTPRequestHandler.responses[url_status]) try: LOG.warning("Status code is wrong: {}".format(msg)) pushover.init("<token>") pushover.Client("<user-key>").send_message( msg, title="Checker: {}".format(url)) except pushover.RequestError as e: LOG.error("Can't make a request to pushover: {}".format(e)) exit(-1) else: LOG.info("Status code is Ok") time.sleep(delay)
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 setup(bot): global PUSHOVER, SMTP table_name = bot.config.notify.table_name #ToDO: Check that we have a service to notify if PUSHOVER: app_api = bot.config.notify.pushover_app_api if app_api and app_api is not 'none': pushover.init(app_api) else: PUSHOVER = False if EMAIL: email_address = bot.config.notify.email_address email_server = bot.config.notify.email_server email_port = bot.config.notify.email_port email_username = bot.config.notify.email_username email_password = bot.config.notify.email_password SMTP = smtplib.SMTP(email_server, email_port) if email_username and email_password: SMTP.login(email_username, email_password) columns = ['pkey', 'nick', 'service', 'parameter'] pkey = columns[0] willie_db = willie.db.WillieDB(bot.config) connect = willie_db.connect() if not willie_db.check_table(table_name, columns, pkey): connect.execute("CREATE TABLE notifydb (pkey integer NOT NULL, nick string, service string, parameter string, PRIMARY KEY (pkey));") connect.commit() connect.close()
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 __init__(self): self.logger = logging.getLogger("PushoverDispatcher") self.logger.debug("Loading Pushover config info...") if os.path.isfile(os.path.join(os.getcwd(), "pushover_config.json")): with open(os.path.join(os.getcwd(), "pushover_config.json"), "r") as f: self.config = json.load(f) else: self.logger.error("pushover_config.json not found, creating...") self.config = {"TOKEN": "", "USER_KEY": ""} with open(os.path.join(os.getcwd(), "pushover_config.json"), "w") as f: json.dump(self.config, f, indent=4, sort_keys=True) try: self.logger.debug("Authenticating with Pushover...") pushover.init(self.config["TOKEN"]) self.client = pushover.Client(self.config["USER_KEY"]) if not self.client.verify(): self.logger.error( "Failed to authenticate with Pushover. Please correct the details in " "pushover_config.json and restart.") sys.exit(1) else: self.logger.debug("Authenticated with Pushover.") except (pushover.InitError, pushover.UserError, pushover.RequestError): self.logger.error( "Failed to authenticate with Pushover. Please correct the details in " "pushover_config.json and restart.") sys.exit(1)
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")
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 send_notification(self, message): try: token = self.config.get_token() user_key = self.config.get_user_key() pushover.init(token) pushover.Client(user_key).send_message(message, title="Incubator") except: logging.error("Failed to notify")
def __init__(self, configuration_file="luxmedSniper.yaml"): self.log = logging.getLogger("LuxMedSniper") self.log.info("LuxMedSniper logger initialized") self._loadConfiguration(configuration_file) self._createSession() self._logIn() pushover.init(self.config['pushover']['api_token']) self.pushoverClient = pushover.Client( self.config['pushover']['user_key'])
def _send_pushover(self, payload): init(config.get('Alerts', 'pushoverToken')) pushover = Client(config.get('Alerts', 'pushoverUserKey')) if payload.url: pushover.send_message(payload.generate_message(), title=self.title, url_title="See Product", url=payload.url) else: pushover.send_message(payload.generate_message(), title=self.title)
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 send_notification(): try: LOGGER.info('Initiating handshake with pushover') init('aBvnvKsL6YSDxDdkDkQehkoGH4m6oo') client = Client('uUJ7mE5whHv8273LFF9c38niv1w8gj').send_message( "Hello!, Someone is at the door at {}".format(time.ctime()), title="The is someone at the door.") except: LOGGER.error('Unable to connect to pushover server') raise RuntimeError('Unable to connect to pushover server')
def pushit(self, client_id, token, subject, msg): body = 'Subject: %s\n' % subject body += '\n' body += msg pushover.init(token); client = pushover.Client(client_id); client.send_message(msg, title=subject, priority=1) self.stderr.write('Mailed:\n\n%s' % body) self.mailed = body
def _notify(self, data, message): state = shelve.open(self.config['misc']['notifydb']) notifications = state.get(str(data['DoctorId']), []) if not data['AppointmentDate'] in notifications: notifications.append(data['AppointmentDate']) self.log.info(u'Sending notification: {}'.format(message)) pushover.init(self.config['pushover']['api_token']) pushover.Client(self.config['pushover']['user_key']).send_message( message, title=self.config['pushover']['title']) else: self.log.info('Notification was already sent.') state[str(data['DoctorId'])] = notifications state.close()
def send_alert(alert_kw): init(pushover_token) alert_body = "OSINT ALERT:\r\n" # walk through the searx results if alert_kw.has_key("searx"): for keyword in alert_kw['searx']: alert_body += "\r\nDetection: %s\r\n" % keyword for keyword_hit in alert_kw['searx'][keyword]: alert_body += "%s\r\n" % keyword_hit Client(pushover_key).send_message(title="OSINT Alert: Searx", message=alert_body) print "[!] Alert sent!" return
def send_statue_noti(loads): OPEN = 0 FULL = 0 WAIT = 0 for load in loads: if load._now_statue == 'OPEN': OPEN += 1 if load._now_statue == 'FULL': FULL += 1 if load._now_statue == 'Waitl': WAIT += 1 print(OPEN, FULL, WAIT) init('afiq2ntpokxubmzt61j9ii5kf2w4o9') Client('uuij88hm2xkrk17brz1enbiuyko6ph').send_message( 'Open:{} Full:{} Wait:{}'.format(OPEN, FULL, WAIT), title='RUNNING!')
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')
def ophalen(): naam = input("Voer uw naam in: ") achternaam = input("Voer uw achternaam in: ") fietsnummer = (input("Voer uw fietsnummer in: ")) wachtwoord = input("Voer uw PIN-code in: ") totallist = [fietsnummer, naam, achternaam, wachtwoord] with open('fietsen.csv', 'r+') as file: reader = csv.reader(file, delimiter=';') for row in reader: if totallist == row[0:4]: with open('register.csv', 'r+') as file2: reader = csv.reader(file2, delimiter=';') writer = csv.writer(file2, delimiter=";") for line in reader: if totallist == line[0:4]: test = 'Uw fiets is zojuist uit de stalling verwijderd. \nWas u dit niet? Stuur dan een e-mail naar [email protected]\nWij hopen dat u van onze dienst heeft genoten en hopelijk tot ziens!' from pushover import init, Client init("atwfgt129b3q3ai4hh3nnmu23b2ebm") Client( "uqjs6boje6bp7okwnre9ndb7s2gwgs").send_message( test, title="NS Stalling") sys.exit("Uw fiets is nu opgehaald") sys.exit('kon fiets niet ophalen')
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("Nothing there! " + datetime.now().strftime('%Y-%m-%d %H:%M:%S')) else: print("Result is out. Maybe :/" + datetime.now().strftime('%Y-%m-%d %H:%M:%S')) if Settings.push: init("anub5bu2j19hk7iovfrk7c4pjdxsrk") Client("ut7x3c9hizi7res7gisx5oh7oyyiub").send_message( "Result is out!! maybe :/", title="CHSL 17") time.sleep(Settings.update_timer)
def pushover(self, title): pushover.init(configuration.PUSHOVER_TOKEN) client = pushover.Client(configuration.PUSHOVER_CLIENT_ID) client.send_message(title, title=title, priority=1)
if os.path.exists(log_file) == False: log("date;apartments_found") log("{};{}".format(date, apartments_found)) # Read last line in log with open(log_file, 'r') as f: lines = f.read().splitlines() last_run = lines[-1][:10] last_run_apartments_found = int(lines[-1][11:]) # New day? New log entry. if date != last_run: log("{};{}".format(date, apartments_found)) # Exit if nothing to push if date == last_run and apartments_found <= last_run_apartments_found: print("{} | {} {} | Nothing to push".format(timestamp, apartments_found, type)) os._exit(0) except: print("{} | An error was thrown".format(timestamp)) # Send push if apartments_found > 0: # Pushover init(_TOKEN) Client(_KEY).send_message(u"Intresseanmäl på https://wahlinfastigheter.se/lediga-objekt/lagenheter/" .format(apartments_found), title="{} nya lägenheter".format(apartments_found)) print("{} | {} {} | Pushover message sent".format(timestamp, apartments_found, type)) log("{};{}".format(date, apartments_found))
from pushover import init, Client init("auf2xins5qc4rf66zqz19d17t3xn8f") Client("ur7vvtiuy43cytxszrw3fy87m919v4").send_message("Hello!", title="Hello")
from members.models import Member, Pushover import os import pushover import logging logger = logging.getLogger("members") pushover_available = False api_token = os.getenv('XEROPS_PUSHOVER_API_KEY', None) if api_token is None: logger.info("Pushover not configured. Alerts will not be sent.") else: try: pushover.init(api_token) pushover_available = True except Exception as e: logger.info("Pushover could not be initialized. Alerts will not be sent.") logger.info("Pushover init exception: "+str(e)) # REVIEW: This sometimes fails. Should it be an asynchronous task with retries? def notify(target_member: Member, title: str, message: str): if not pushover_available: return try: target_key = Pushover.objects.get(who=target_member).key except Pushover.DoesNotExist: logger.error("Couldn't send msg to %s since there's no pushover key for them.", str(target_member))
from pushover import init, Client init("azhGtg6JmozL2HHZiAwje9KJYEJFDJ") Client("u6BdkLpT3i2pJMQVVvHrSBxn4eNaMq").send_message("Hello!", title="Hello World")
import cv2 import numpy as np import sys import dropbox import os from pushover import init, Client import time init("aypdp8ionpppkenbx8w3irxhf6e855") #dropbox unique token token = 'Bj5eYdrWuUAAAAAAAAAAEtmDseR8WsNoxII72K_7z7n-w0f8aBprpJUrkrES3Rr9' dbx = dropbox.Dropbox(token) #check api, kust for testing purpose #print(dbx.users_get_current_account()) facePath = "haarcascade_frontalface_default.xml" faceClassifier = cv2.CascadeClassifier(facePath) img_cnt = 0 cap = cv2.VideoCapture(0) cap.set(3, 480) #set width cap.set(4, 480) #set height def uploadImg(file): path = file dbx.files_upload(file, path)
import RPi.GPIO as gpio import time import sys from pushover import init, Client # pushover init("<api key>") pump_pin = 21 soil = 20 sec_to_water = 30 gpio.setmode(gpio.BCM) gpio.setup(pump_pin, gpio.OUT) gpio.setup(soil, gpio.IN) def pump_off(): gpio.output(pump_pin, gpio.HIGH) def pump_on(): gpio.output(pump_pin, gpio.LOW) def soil_check(seconds): if gpio.input(20): print("Watering the plant for:" + str(seconds) + "s") # off pump_on() time.sleep(seconds)
import json import urllib2 from pushover import init, Client #from datetime import date, datetime import datetime from dateutil.relativedelta import relativedelta, FR init("aJcfJv8iqShDjjwXdg5A5eCRbwqvsH") targetprice = {"avh": 0.56} # grab latest alphavantage json extract avh = json.load( urllib2.urlopen( "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=%3CyourAPIKEY%3E&datatype=json&symbol=AVH.AX&outputsize=compact" )) # walk back through the avh dict day by day to find the most recent result i = 0 walkLimit = 7 # how many days to walk back, including 0 today = datetime.date.today() # for testing only # today = datetime.date.today() + relativedelta(weekday=FR(2)) while i < walkLimit: i += 1 pastDays = datetime.timedelta(days=i) currentDay = today - pastDays searchKey = str(currentDay.strftime('%Y-%m-%d'))
def send_note(msg): pushover.init("acfZ42h7KMGmAdbzyCBZxkDwTrzhPN") client = pushover.Client("uxFdSnAMc9D9kcBdgZWYkW3mwynUvc") client.send_message(msg, title=msg, priority=1)
def set_link_info(link, line): match_addr = REGEX_LINK_ADDR.search(line) if match_addr: link.addr = match_addr.group(1) match_ptp = REGEX_LINK_PTP.search(line) if match_ptp: link.ptp = match_ptp.group(1) match_mask = REGEX_LINK_MASK.search(line) if match_mask: link.mask = match_mask.group(1) interfaces = get_interfaces(ifconfig) vpns = [] for interface in interfaces: if interface.ptp: vpns.append(interface) if len(vpns) == 0: print('No VPN connections found.') try: init(PUSHOVER_APP_KEY) Client(PUSHOVER_USR_KEY).send_message('VPN on server is down.') except Exception as e: print(e)
dato = 1 def data_handler(client, userdata, msg): global FLAG_new_data global dato # Capturamos el dato recibido # dato = float(str(msg.payload.decode("utf-8"))) # Activamos el flag de recepcion de dato # FLAG_new_data = True if __name__ == "__main__": # Inicializamos la API mediante su token # init(API_TOKEN_PUSHOVER) printlog("Creando cliente MQTT ...", "INFO") clientMQTT = mqtt.Client(CLIENT_ID) printlog("Cliente MQTT creado!", "OK") printlog("Conectando a Broker MQTT", "INFO") clientMQTT.connect(BROKER_LOCALHOST_IP) # Comenzamos el loop de escucha del topic del acelerometro # clientMQTT.loop_start() printlog("Conectado a la red MQTT!", "OK") printlog("Escuchando el topic del acelerometro", "INFO") clientMQTT.subscribe(ACC_SENSOR_TOPIC) printlog("Listo!", "INFO")
from config import PUSHOVER_APP_TOKEN, PUSHOVER_USER_KEY import pushover # PUSHOVER pushover.init(PUSHOVER_APP_TOKEN) pushover_client = pushover.Client(PUSHOVER_USER_KEY)
import pushover from . import TOKEN_KEY pushover.init(TOKEN_KEY) from models import PushoverUserTokens # from https://pushover.net/api#priority PRIORITY = { 'LOWEST': -2, 'LOW': -1, 'NORMAL': 0, 'HIGH': 1, 'EMERGENCY': 2, } def send_push_notification(title, msg, priority=PRIORITY['NORMAL']): for t in PushoverUserTokens.objects.all(): client = pushover.Client(t.token) client.send_message(msg, title='Vilicus alert: ' + title, priority=priority)
from bs4 import BeautifulSoup # HTML scraping import urllib # load Ryanair web page import pushover # Pushover notifications import json # serialization import os # check if JSON exists # load stored fares if file exists cities = {} if os.path.exists("cities.json"): fileHandle = open("cities.json","r") cities = json.load(fileHandle) fileHandle.close() # initialize Pushover client pushover.init("APP-TOKEN") client = pushover.Client("USER-KEY") # scrape web page handle = urllib.urlopen("http://www.ryanair.com/de/fluge/nuremberg-nach-malaga") soup = BeautifulSoup(handle.read()) handle.close() # get fares from web page, get current fare from cities dictionary faresTable = soup.find("div", id="rfares").table for destination in faresTable.find_all("a"): city = destination.i.get_text() fare = float(destination.u.get_text()) if cities.has_key(city): currentFare = cities[city] else:
def retweet_from_last_minutes(user, mins): '''Retweets a random tweet from user in the past minutes''' api = get_connection() timeline = api.user_timeline(user, count=20) # Get only tweets that have been posted in the last hour recent_tweets = [] hour_ago = datetime.now(tz=tz.tzlocal()) - timedelta(seconds=mins*60) for tweet in timeline: # Convert utc time to local tweet_time = tweet.created_at.replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal()) if tweet_time > hour_ago: recent_tweets.append(tweet) if recent_tweets: tweet = random.choice(recent_tweets) api.retweet(tweet.id) if __name__ == '__main__': try: hourly_tweet() except Exception as ex: # Pushover alert if something goes wrong if use_pushover: timestr = time.strftime('%d/%m/%Y %H:%I %p') pushover.init(PUSHOVER_APP_TOKEN) pushover.Client(PUSHOVER_USER).send_message('Error:\n{}'.format(ex), title='{} error {}'.format(__file__, timestr)) # Re-raise the exception for any logs raise ex
def __init__(self, host, username, password): init(app_key) self.host = host self.username = username self.password = password self.api = connect(host=host, username=username, password=password)
from bs4 import BeautifulSoup import requests from datetime import datetime from pushover import init, Client import time url = "https://www.gymnasiumdorfen.de/" page = requests.get(url=url) print(page) init("a3jgvwuu37m48qb6x3cwhmo6qm9yt4") while (True): soup = BeautifulSoup(page.text, 'html.parser') container = soup.find_all(class_='ce-container') newdate = container[0].get_text().split("\n")[2].split(" ")[0] """ Datum aus Datei lesen und in var speichern Newsdate mit altem Datum vergleichen 1. newsdate == olddate -> Nichts neues 2. newsdate > olddate -> neuer post --> print --> newsdate speichern """ with open("datelog.txt", mode="r") as result: olddate = result.read() d_olddate = datetime.strptime(olddate, "%d.%m.%Y") d_newdate = datetime.strptime(newdate, "%d.%m.%Y")
pushover_token = "" pushover_userkey = "" solaredge_apikey = "" solaredge_siteid = "" city_name = "" with open('solarpi_config/config.json') as config_file: data = json.load(config_file) pushover_token = data['pushover_token'] pushover_userkey = data['pushover_userkey'] solaredge_apikey = data['solaredge_apikey'] solaredge_siteid = data['solaredge_siteid'] city_name = data['city_name'] init(pushover_token) def TimeStamp(): return datetime.today().strftime("%m/%d/%y %I:%M:%S %p") 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")
db.commit() except: db.rollback() # Database id function - returns list of ids def getExisting(): cursor.execute("SELECT id from Done") data = cursor.fetchall() dataList = [] for i in data: for a in i: dataList.append(a) return dataList # Setup pushover and the useragent for praw pushover.init(application) client = pushover.Client(user) r = praw.Reddit(user_agent=praw_useragent, client_id=praw_client_id, client_secret=praw_client_secret) # Main Function def main(): submissions = r.subreddit('pipetobaccomarket').new(limit=20) # iterate through them for x in submissions: # Discard all Wanting to Trade/Wanting to Buy posts, leaving only Wanting to Sell or untagged posts match = re.search('WT[TB]', str(x.title)) # Pull the list of ids from the database already_done = getExisting() if x.id not in already_done and not match:
#Alerts a user once a specific Script or MSSQL job has completed on a SQL Server. PUSHOVER_CLIENT_ID = "" PUSHOVER_API_KEY = "" MSSQL_DOMAIN = False #Use Domain Authentication? MSSQL_USER = "" MSSQL_PASS = "" from sqlalchemy.sql import text from pushover import init, Client init(PUSHOVER_API_KEY) class Job(object): name = None session_id = None job_id = None start_execution_date = None def __init__(self,name,session_id,job_id,start_execution_date): self.name = name self.sesion_id = session_id self.job_id = job_id self.start_execution_date = start_execution_date def __str__(self): return "%s started at %s" % (self.name, self.start_execution_date) def is_running(self,server): """ Check's to see if this job is still running." """ result = server.execute(text("""SELECT COUNT(*) FROM msdb.dbo.sysjobactivity AS sja INNER JOIN msdb.dbo.sysjobs AS sj ON sja.job_id = sj.job_id
def notify(message): init(cfg['pushover_api']) client = Client(cfg['pushover_user']) client.send_message(message, title="Cat Alert")
# Author: shubs import requests import sys import time import sqlite3 import os from pushover import init, Client from datetime import datetime sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import config init(config.PUSHNOTIFY_KEY) # Initiate manager BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' ) DATABASE = BASE_DIR+ '/assetnote.db' conn = sqlite3.connect(DATABASE) c = conn.cursor() c.execute("select * from domains") all_domains_to_scan = c.fetchall() def grab_subdomains_for_domain(domain): try: api_url = "http://www.threatcrowd.org/searchApi/v2/domain/report/?domain={0}".format(domain) api_call = requests.get(api_url, verify=False) print api_call.content api_results = api_call.json()
# in general, it's a HORRID idea to store creds in a script # especially when every scripting language has a dirt simple way to # use a config file # # ALSO: DON'T STORE THE CONFIG FILE IN THE DIRECTORY YOU'RE USING # AS A PRIVATE OR PUBLIC GIT REPO!!!! #pls # # make the location whatever you want, but it has to be readable by the script CONFIG_FILE = "/home/bob/.nizdos.conf" Config = ConfigParser.ConfigParser() Config.read(CONFIG_FILE) # initialize pushover pushover.init(Config.get("pushover","AppKey")) pushoverClient = pushover.Client(Config.get("pushover","UserKey")) # initialize twitter tweet = twitter.Api(consumer_key=Config.get("twitter","consumer_key"), consumer_secret=Config.get("twitter","consumer_secret"), access_token_key=Config.get("twitter","access_token"), access_token_secret=Config.get("twitter","access_token_secret")) # this is the user we'll be DMing rcpt = Config.get("twitter","user") # setup redis # # technically, sqlite, mongo or even a dbm or text file could have
import sqlite3, requests from pushover import init, Client from bs4 import BeautifulSoup as bs import re init("") #pushover api project key IphoneUser = "" #pushover phone/computer user key client = Client(IphoneUser) db = sqlite3.connect('toCheck.db') cursor = db.cursor() def getCurrent(): global cursor fetchQuery = """SELECT CheckMe.Name, CheckMe.Url, CheckMe.DesiredPrice, Websites.Name FROM CheckMe INNER JOIN Websites ON CheckMe.WebsiteID = Websites.ID""" results = cursor.execute(fetchQuery).fetchall() formattedResults = [] for result in results: formatDictionary = { "Name": result[0], "Url": result[1], "DesiredPrice": result[2], "Website": result[3] } formattedResults.append(formatDictionary) return formattedResults def CheckPrice(): CheckList = getCurrent()
import time import webbrowser from pyquery import PyQuery from time import strftime from pushover import init, Client CONSUMER_KEY = ' ' CONSUMER_SECRET = ' ' ACCESS_TOKEN = " " ACCESS_TOKEN_SECRET = " " twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET,ACCESS_TOKEN, ACCESS_TOKEN_SECRET) init(" ")#Pushoher kulanımı için... print "#".ljust(30,"#") webbrowser.open_new_tab("https://twitter.com/@...")#webbrowserda hesabınızın otomatik açılması sağlar k = PyQuery("https://twitter.com/@...") print k('title').html() print "#".ljust(30,"#") #Takip ettiği kişi sayısını verir print "Takip ettiği kişi sayısı:" user = twitter.get_user_timeline() print user[0]['user']['friends_count'] print "#".ljust(30,"#") ##Takipçi sayısını verir print "Takipçi sayısı..........:"
def __init__(self, config): self.config = config init(self.config['API_TOKEN'])
import os import time import sys from pushover import init, Client init("<token>") client = Client("<user-key>").send_message("Hello!", title="Hello") os.system('clear') deviceIP = 10.0.0.201 #raw_input("Enter the IP address to listen for: ") cacheFolder = "cache/" cacheFileName = time.time() filePath = cacheFolder + str(cacheFileName) def checkForDevice(): # See if the device has connected to the network systemCommand = "sudo arp-scan -l > " + filePath os.system(systemCommand) with open(filePath) as fileObj: for line in fileObj.readlines(): if deviceIP in line: success = True break else: success = False return success def delayPrint(text): print text time.sleep(2)
def send_message(message): init(apiKey) Client(userKey).send_message(message, title="Weather Forecast")
def send_push_notification(application_token, user_key, message, title): init(application_token) Client(user_key).send_message(message, title=title)
def send_pushover(user_token,title,message,device=None): init(os.environ['pushover_api_key']) Client(user_token).send_message(message, title=title,device=device) return
def SendNotification(pushover_keys, title, msg): if (pushover_keys!=None): init(pushover_keys["app_key"]) # Pushover API key for MiningSwitcher client=Client(pushover_keys["user_key"]).send_message(msg, title=title, priority=1)