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: # strip title of post and assemble message
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 get_client_for_admin(): if not config.get('PUSHOVER_TOKEN'): return None client = pushover.Client(config['PUSHOVER_ADMIN_KEY'], api_token=config['PUSHOVER_TOKEN']) return client
import pushover PUSHOVER_USER_KEY = "enterkeyhere" PUSHOVER_APP_TOKEN = "entertokenhere" sshlogin = open('monitorlog', 'r').read() pushover.init(PUSHOVER_APP_TOKEN) pushover.Client(PUSHOVER_USER_KEY).send_message("Login " + sshlogin)
def alert(message, title="wateralarm"): pushover.Client(cfg["user"], api_token=cfg["api_token"]).send_message(message, title=title) print(message)
args = parser.parse_args() # Login RH # ROBINHOOD_USERNAME = '' # ROBINHOOD_PASSWORD = '' # Read API infos from config config_paht = args.configfile if os.path.exists(config_paht): with open(config_paht, 'r') as f: info = json.load(f) ALPHAVANTAGE_API_TOKEN = info['alphavantage']['key'] PUSHOVER_TOKEN = info['pushover']['token'] PUSHOVER_USERKEY = info['pushover']['key'] po_client = pushover.Client(PUSHOVER_USERKEY, api_token=PUSHOVER_TOKEN) g_ts = TimeSeries(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') g_ti = TechIndicators(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') g_sp = SectorPerformances(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') PO_TITLE = "Robinhood" REFRESH_SECURITIES_INTERVAL = 4 # minutes INTRADAY_SIGNAL_INTERVAL = 15 # minutes MAX_API_RETRIES = 3 slow_interval = 'daily' fast_interval = '15min' ema_fast_period = 12 ema_slow_period = 26 series_type = 'close'
if not api_key: l("Error: you must supply a UserKey|AppToken") sys.exit(1) api_keys = api_key.split("|") if len(api_keys) != 2: l("Error: Missing user key or app key") sys.exit(1) user_key = api_keys[0] app_token = api_keys[1] # Try to login with AcessToken try: po = pushover.Client(user_key, api_token=app_token) except (pushover.UserError) as exc: l("Error: Can't connect to Pushover with User Key [%s]." % user_key) sys.exit(1) # Try to send the notification try: po.send_message(message, title=subject) except (pushover.RequestError) as exc: l("Error: Can't send notification to Pushover devices: %s" % rlb(str(exc))) sys.exit(1) # Exit with success l("Success: Message sent with UserKey [%s] to AppToken [%s]" % (user_key, app_token)) sys.exit(0)
def statusDownload(self, mt): currenttimestamp = datetime.now().replace(tzinfo=None) status = mt.getPumpStatus() last_entry_cur = self.db.all_events.find({ "type": "PumpStatusEvent" }).sort("timestamp", pymongo.DESCENDING).limit(1) try: last_entry = last_entry_cur.next() except StopIteration: last_entry = None print("Last entry: {}".format(last_entry)) print("Writing: {}".format(status)) to_write = { "type": "PumpStatusEvent", "timestamp": currenttimestamp, "hour": currenttimestamp.hour, "sensorBGL": status.sensorBGL if status.StatusCgm \ else None, "trendArrow": status.trendArrow, "trendArrowValue": status.trendArrowValue, "sensorBGLTimestamp": status.sensorBGLTimestamp, "activeInsulin": status.activeInsulin, "currentBasalRate": status.currentBasalRate, "tempBasalRate": status.tempBasalRate, "tempBasalPercentage": status.tempBasalPercentage, "tempBasalMinutesRemaining": status.tempBasalMinutesRemaining, "batteryLevelPercentage": status.batteryLevelPercentage, "insulinUnitsRemaining": status.insulinUnitsRemaining, "sensorStatus": status.sensorStatus, "sensorStatusValue": status.sensorStatusValue, "sensorCalibrationMinutesRemaining": status.sensorCalibrationMinutesRemaining \ if status.StatusCgm \ else None, "sensorBatteryPercent": status.sensorBatteryPercent \ if status.StatusCgm \ else None, "sensorControl": status.sensorControl, "sensorControlValue": status.sensorControlValue, "StatusCgm": status.StatusCgm, "StatusTempBasal": status.StatusTempBasal, "StatusInsulinDelivery": status.StatusInsulinDelivery, "StatusBolusingDual": status.StatusBolusingDual, "StatusBolusingSquare": status.StatusBolusingSquare, "StatusBolusingNormal": status.StatusBolusingNormal, "StatusSuspended": status.StatusSuspended, "lastBolusAmount": status.lastBolusAmount, "lastBolusTimestamp": status.lastBolusTimestamp, "bolusWizardBGL": status.bolusWizardBGL, "sensorRateOfChangePerMin": status.sensorRateOfChangePerMin, } self.db.all_events.insert_one(to_write) to_write = { "type": "PumpStatusEventRaw", "timestamp": currenttimestamp, "hour": currenttimestamp.hour, "statusRaw": status.wholePayloadHex } self.db.all_events.insert_one(to_write) # if there is a configuration for pushover, then we send some notifications if os.path.isfile(os.path.expanduser("~/.pushoverrc")): import pushover # ignore if sensor not present if status.StatusCgm: if status.sensorBGL & 0x200 == 0 \ and status.trendArrow != "Calibration needed": # high sugar value and no active insulin if status.sensorBGL is not None \ and status.sensorBGL > 250 \ and (status.activeInsulin < 1.0 or (currenttimestamp - status.lastBolusTimestamp > datetime.timestamp(hours=1))): print("Notifying high sugar level.") ret = pushover.Client().send_message( "High sugar {} and low active insulin {}".format( status.sensorBGL, status.activeInsulin), title="High sugar level. Correction needed.", url="https://paulonet.eu/bgmonitor/", priority=1) print(ret) # low sugar value if status.sensorBGL is not None \ and status.sensorBGL < 60 \ and status.sensorBGL + 15 * status.sensorRateOfChangePerMin < 70: print("Notifying low sugar level.") predicted = status.sensorBGL + int( 15 * status.sensorRateOfChangePerMin) ret = pushover.Client().send_message( "Low sugar {}. In 15 minutes predicted {}.".format( status.sensorBGL, predicted if predicted >= 40 else '<40'), title="Low sugar level.", url="https://paulonet.eu/bgmonitor/", priority=1) print(ret) # calibration coming soon if status.sensorCalibrationMinutesRemaining > 0 \ and status.sensorCalibrationMinutesRemaining <= 10: calibrationdatetime = currenttimestamp + timedelta( minutes=status.sensorCalibrationMinutesRemaining) print("Notifying calibration needed soon.") ret = pushover.Client().send_message( "Calibration in {} minutes at {:%-H:%M}.".format( status.sensorCalibrationMinutesRemaining, calibrationdatetime), title="Calibration soon", url="https://paulonet.eu/bgmonitor/") print(ret) # calibration time passed if status.sensorStatusValue & 0x04 != 0 \ and status.sensorCalibrationMinutesRemaining == 0 \ and status.trendArrow == "Unknown trend" \ and not ( last_entry is not None \ and last_entry["StatusCgm"] \ and last_entry["trendArrow"] == "Unknown trend" and last_entry["sensorCalibrationMinutesRemaining"] == 0): print("Notifying calibration needed NOW.") ret = pushover.Client().send_message( "Calibration already passed!", title="Calibration needed!", url="https://paulonet.eu/bgmonitor/", priority=1) print(ret) # calibration needed in the evening if datetime.now().time() > time(23, 00) \ and (datetime.now() + timedelta(minutes=status.sensorCalibrationMinutesRemaining)).time() < time(7, 00) \ and status.sensorStatusValue != 0x00 : print("Evening calibration needed.") ret = pushover.Client().send_message( "Next calibration planned at {:%-H:%M}.".format( (datetime.now() + timedelta( minutes=status. sensorCalibrationMinutesRemaining)).time()), title="Evening calibration needed!", url="https://paulonet.eu/bgmonitor/", priority=1) print(ret) # battery change needed in the evening if datetime.now().time() > time(22, 00) \ and status.batteryLevelPercentage <= 25: print("Consider battery change.") ret = pushover.Client().send_message( "Current battery level: {}%.".format( status.batteryLevelPercentage), title="Consider battery change.", url="https://paulonet.eu/bgmonitor/", priority=1) print(ret)
#Bootstrap file if not existing if not os.path.isfile(PERSIST_STATE): print("Bootstraping persistence...") with open(PERSIST_STATE, "w") as f: f.write("open") f.close() print("Requesting pixel state...") r = requests.get(PIXELSTATE).json() if 'state' not in r: print("Given JSON seems to be broken. Missing state key. Exit.") sys.exit(1) f = open(PERSIST_STATE, "r+") if f.read() == r['state']: #No state change print("No state change. Nothing to do here. Exit.") sys.exit(0) print("Sending Push notification for pixel state change") pushover.init(os.environ['PUSHOVER_TOKEN']) pushover.Client(os.environ['PUSHOVER_USER']).send_message("Pixelbar is now " + r['state'], title="Pixelbar") f.seek(0) f.write(r['state']) f.truncate() f.close() print("Done.")
while True: # Take a photo print('Taking a photo') camera.capture('/home/pi/latest.jpg') # Ask OpenALPR what it thinks analysis = alpr.recognize_file("/home/pi/latest.jpg") # If no results, no car! if len(analysis['results']) == 0: print('No number plate detected') # Has a car left? if last_seen is not None: pushover.Client(PUSHOVER_USER_KEY).send_message( last_seen + " left", title="Driveway") last_seen = None else: number_plate = analysis['results'][0]['plate'] print('Number plate detected: ' + number_plate) # Has there been a change? if last_seen is None: pushover.Client(PUSHOVER_USER_KEY).send_message( number_plate + " has arrived", title="Driveway") elif number_plate != last_seen: pushover.Client(PUSHOVER_USER_KEY).send_message( number_plate + " arrived and " + last_seen + " left", title="Driveway")
import urllib.request import json import pushover def read_token(ftoken): # Set the correct path with open(ftoken, 'r') as f: return f.readline().strip() if __name__ == '__main__': # Acquire information about the device # Public ip ipify_token = read_token('.ipify-token') url = "https://geo.ipify.org/api/v1?apiKey={api_key}".format( api_key=ipify_token) request = urllib.request.urlopen(url).read().decode('utf8') ipdata = json.loads(request) # Local information hostname = socket.gethostname() local_ip = socket.gethostbyname(hostname) # Send notification title = "Startup Notifier: '{dev}' is online".format(dev=hostname) message = "{dev} is online and connected with IP {ip_pub}, localized in {city}, {country} ({lat} N, {long} E)." \ .format(dev=hostname,ip_pub=ipdata['ip'], city=ipdata['location']['city'], country=ipdata['location']['country'], lat=ipdata['location']['lat'], long=ipdata['location']['lng']) po_client = pushover.Client(config_path='.pushoverrc') po_client.send_message(message, title=title, timestamp=True)
def pushover(self, title): pushover.init(configuration.PUSHOVER_TOKEN) client = pushover.Client(configuration.PUSHOVER_CLIENT_ID) client.send_message(title, title=title, priority=1)
# 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
def __init__(self, *args, **kwargs): self.wrapped_class = pushover.Client(*args, **kwargs)
def __init__(self, user_key, api_token, *args, **kwargs): super().__init__(*args, **kwargs) self.client = pushover.Client(user_key, api_token=api_token)
def main(args): run_id = args.id or datetime.now().strftime("%Y%m%d%H%M%S") seed = args.seed or np.random.randint(1000) noise = args.noise or 'gaussian' verbose = args.verbose run_dir = Path(__file__).parent / 'runs' / 'optimizer' / run_id run_dir.mkdir(parents=True, exist_ok=True) # store arguments with open(run_dir / 'config.json', 'w') as f: json.dump(args.__dict__, f, indent=4, sort_keys=True) # prepare checkpoints checkpoint_path = run_dir / 'checkpoint.pkl' callbacks = [CheckpointSaver(str(checkpoint_path.resolve()), compress=9) ] # keyword arguments will be passed to `skopt.dump` if verbose: callbacks.append( VerboseCallback( n_total=args.n_calls + (0 if args.from_checkpoint else args.n_random_starts))) # prepare search space search_space = [ Real(1e-06, 0.1, "log-uniform", name='lr'), Real(0.01, 0.5, "log-uniform", name='inv_mom'), Real(1e-07, 0.01, "log-uniform", name='lr_decay'), Real(0.1, 0.8, "uniform", name='dropout'), Real(1e-07, 0.001, "log-uniform", name='l2'), Real(0.1, 0.99, "uniform", name='alpha'), Real(0, 1, "uniform", name='ce_ratio'), Integer(16, 256, name='bs'), Integer(0, 1, name='bn'), Integer(0, 1, name='augment'), Categorical(['min', 'max'], name='resize_mode'), # Real(1e-5, 100, "log-uniform", name='loss_param_1'), # Integer(0, 16, name='num_unfrozen'), # Integer(1, 3, name='loss_param_1'), # Integer(8, 128, name='loss_param_2'), # Integer(1, 3, name='data_ratio'), # Integer(1, 3, name='batch_repeats'), # Categorical(['all', 'knn', 'kfn', 'ksd'], name='con_filt_type'), # Categorical(['all', 'knn', 'kfn', 'ksd'], name='pen_con_filt_type'), ] if verbose: print('Search space:') pprint(space2dict(search_space)) # prepare objective function obj_fun = make_obj_fun(search_space) # obj_fun = make_obj_fun_dummy(search_space) # get previous search if args.from_checkpoint: cp_path = Path(args.from_checkpoint) / 'checkpoint.pkl' if not cp_path.is_file(): raise ValueError( """ from_checkpoint should point to a .pkl file. Got: '{}'""" .format(args.from_checkpoint)) if verbose: print('Continuing from checkpoint: {}'.format(cp_path.resolve())) res = load(str(cp_path.resolve())) # ensure that same space keys are used for i, dim in enumerate(res.space.dimensions): if not (dim.name == search_space[i].name and type(dim) == type(search_space[i])): raise ValueError(""" The checkpoint search dimensions don't match the new search dimensions. Checkpoint dimensions: {} New dimensions: {} """.format(space2dict(res.space.dimensions), space2dict(search_space))) ok_dim_inds = [ i for i, x in enumerate(res.x_iters) if all(search_space[j].low <= d and d <= search_space[j].high for j, d in enumerate(x)) ] x0 = [res.x_iters[i] for i in ok_dim_inds] y0 = [res.func_vals[i] for i in ok_dim_inds] add_search_args = {'x0': x0, 'y0': y0, 'n_random_starts': 0} else: add_search_args = {'n_random_starts': args.n_random_starts} common_search_args = { 'func': obj_fun, 'dimensions': search_space, 'acq_func': args.acq_func, 'n_calls': args.n_calls, 'noise': noise, 'random_state': seed, 'callback': callbacks } search_args = {**common_search_args, **add_search_args} # perform search res = gp_minimize(**search_args) # print some statistics if verbose: print("x^*=") pprint(res.x) print("f(x^*)={}".format(res.fun)) # notify that search is done pushover.Client(user_key=os.getenv('NOTIFICATION_USER'), api_token=os.getenv('NOTIFICATION_TOKEN')).send_message( "Finished search with ID='{}'".format(args.id), title="Hyper parameter search")
# These should come from a conf file, the TOKEN, command_prefix, and owner_id (and others if need be) conf_data = json.load(open("conf_files/conf.json")) if conf_data["TOKEN"] == "" or conf_data["command_prefix"] == "" or conf_data[ "owner_id"] == "": print("You need to set up conf.json!") exit(1) TOKEN = conf_data["TOKEN"] intents = discord.Intents().all() client = commands.Bot(command_prefix=conf_data["command_prefix"], intents=intents) client.owner_id = int(conf_data["owner_id"]) psh_data = conf_data['pushover'] if psh_data['user_key'] != "" and psh_data['api_key'] != "": client.pshovr = pushover.Client(user_key=psh_data['user_key'], api_token=psh_data['api_key']) else: client.pshovr = None mongoconf = conf_data['mongodb'] mongoengine.connect( host=f"mongodb://{mongoconf['user']}:{mongoconf['password']}@" f"{mongoconf['ipport']}/{mongoconf['db']}?authSource=admin", ) print("Connected to MongoDB!") client.remove_command("help") sentry_sdk.init(conf_data["sentry_sdk"], traces_sample_rate=1.0) for extension in conf_data["modules"]: try: