Пример #1
0
def main():
    init_logging()
    logging.debug("Starting at: " + datetime.now().strftime("%c"))

    data = load_json(JSON_FILE)

    try:
        check_data(data)
    except AssertionError:
        logging.error("Data error! Sending email...")
        sendemail('Cryptotraitor ERROR', "Unexpected json data:\n%s" % data)
        return
    
    last_order = data[-1]
    action = last_order[0]
    price = last_order[2]
    time = parser.parse(last_order[3])
    now = datetime.now()

    logging.debug("Now: " + now.strftime("%Y/%m/%d %H:%M:%S"))
    logging.debug("Last order time: " + time.strftime("%Y/%m/%d %H:%M:%S"))
    logging.debug("Last order action: " + action + " @ " + price)
    
    # Test send an email
    if (now - time) <= timedelta(minutes = TRADE_THRESHOLD):
        logging.debug("Ready to " + action)
        try:
            createOrder(action)
        except:
            logging.error("Order failed! Sending email...")
            e = sys.exc_info()[0]
            sendemail('Cryptotraitor ERROR', e)
        return            
    else:
        logging.debug('Order stale, exiting...')
Пример #2
0
def send_email(directory):
    email_name, email_user, email_pswd, mailto, body = get_vars(droid)
    subject = 'Break-in attempt at %s - sending now that I have interwebs' % directory
    images = os.listdir(os.path.join(BACKUP_IMAGES_PATH, directory))
    images = [os.path.join(BACKUP_IMAGES_PATH, directory, x) for x in images]

    try:
        emailer.sendemail(email_name, email_user, email_pswd, mailto, subject, body, images)
    except Exception as err:
        with open(os.path.join(LOG_PATH, FAILED_EMAIL_LOG), 'a') as f:
            f.write('%s\n' % str(err))
        droid.makeToast('email failed')
Пример #3
0
def createOrder(action):
    # Load keys and create an API object
    handler = btceapi.KeyHandler()
    nonce = random.randint(0, 100000000)
    handler.addKey(BTCE_KEY, BTCE_SECRET, nonce)

    key = handler.getKeys()[0]
    if LIVE_TRADING:
        logging.debug("**LIVE TRADING**")
    else:
        logging.debug("**SIMULATED TRADING**")
    logging.debug("Trading with key %s" % key)
    api = btceapi.TradeAPI(key, handler)

    # Create a trader that handles BTC/USD trades in the given range.
    trader = orderbot.CryptoTrader(api, "btc_usd", action, logging.debug, LIVE_TRADING)

    # Create a bot and add the trader to it.
    bot = btcebot.Bot()
    bot.addTrader(trader)

    # Add an error handler so we can print info about any failures
    bot.addErrorHandler(onBotError)  

    # Update every 10 seconds
    bot.setCollectionInterval(10)
    bot.start()
    print "Running; press Ctrl-C to stop"

    if action == "SELL":
        curr = "btc"
    elif action == "BUY":
        curr = "usd"

    try:
        while 1:
            bal = trader.getBal(curr)
            logging.debug("Balance is %s " % bal + curr.upper())
            if bal < btceapi.min_orders['btc_usd']:
                logging.debug(action + " complete!")
                sendemail('Cryptotraitor order - ' + action, 'BTC: ' + str(trader.getBal('btc'))
                          + '\nUSD: ' + str(trader.getBal('usd')))
                bot.stop()
                break
            time.sleep(10)
            
    except KeyboardInterrupt:
        print "Stopping..."
    finally:    
        bot.stop()
Пример #4
0
def initializescan(url, email):
    report = Report(url)
    scanner = Scanner()
    try:
        results = scanner.scan(url)
        report.update_results(str(results))
    except Exception as e:
        report.update_results(str(e))

    with app.app_context():
        emailtext = f'''
      Your report is ready.\n
      Simply follow the link below to see your website's results.
      \n\n
      http://allgreencode.s3-website.eu-west-2.amazonaws.com/reports/{report.hashid}
      \n\n
      www.allgreencode.com
      '''
        sendemail(f'Your scan is ready! - {str(datetime.datetime.today())}',
                  recipients=[email],
                  email_text=emailtext)
    return
Пример #5
0
    '''
    If we don't have an internet connection, we can backup the images so that a second task that runs every 10 minutes
    can check for unsent images, and send when a connection is available
    '''
    curr_time = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
    backup_path = os.path.join(BACKUP_IMAGES_PATH, curr_time)
    os.makedirs(backup_path)
    for image in images:
        file_name = os.path.basename(os.path.normpath(image))
        new_image_path = os.path.join(backup_path, file_name)
        os.rename(image, new_image_path)

if __name__ == '__main__':
    if os.path.exists(LOG_PATH) == False:
        os.makedirs(LOG_PATH)
    
    droid = android.Android()
    email_name, email_user, email_pswd, mailto, subject, body, attachments_list = get_vars(droid)
    if(emailer.internet_is_on()):
        try:
            emailer.sendemail(email_name, email_user, email_pswd, mailto, subject, body, attachments_list)
        except Exception as err:
            with open(os.path.join(LOG_PATH, FAILED_EMAIL_LOG), 'a') as f:
                f.write(str(err))
            droid.makeToast('email failed')
            sys.exit(1)
    else:
        curr_time = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
        with open(os.path.join(LOG_PATH, MAIN_LOG), 'a') as f:
            f.write('%s -- No internet connection. Backing up images for later sending.\n' % curr_time)
        backup_images(attachments_list)
db = shelve.open('addresses', writeback=True)
# Initial populating database
# db['alice'] = {'email': '*****@*****.**', 'chores': []}
# db['ben'] = {'email': '*****@*****.**', 'chores': []}
# db['david'] = {'email': '*****@*****.**', 'chores': []}
# db['shawn'] = {'email': '*****@*****.**', 'chores': []}

chores = ['dishes', 'bathroom', 'vacuum', 'walk dog']

# Loop through addresses
for name in db:
    # Choose a random chore. If chore done before, choose another one.
    while True:
        randomChore = random.choice(chores)
        if randomChore not in db[name]['chores']:
            break

    # Record down chore in chores list for person, & remove chore from chores list
    db[name]['chores'].append(randomChore)
    chores.remove(randomChore)
    print("{} will do {}.".format(name, randomChore))

    # Send email to person with assigned chore
    message = "Subject: Chore for the Week\nDear {}, you are chosen to do the chore: {}. Enjoy and work hard!".format(
        name, randomChore)
    emailer.sendemail(smtpObj, db[name]['email'], message)

# Closing db, logging out of gmail
db.close()
emailer.logout(smtpObj)