def run_check_pump_turn_on():
    """
    Wait until the time has elapsed, and send the on signal to the pump relay
    """

    global current_pump_state
    global next_on_time

    pump_on_log = logging.data_logging()
    pump_on_log.auto_add_date = True
    pump_on_log.log_filename = "shower_pump_control-" + todays_date_string() + ".csv"

    pump_on_log.add_log("Starting pump on monitor thread")

    while True:
        current_time = datetime.datetime.now()

        # pump_on_log.add_log(str(current_time) + "," + str(next_on_time) + "," + str(current_pump_state))

        if (current_time > next_on_time) and not current_pump_state:
            set_pump_state(True)
            pump_on_log.add_log("Turned pump on")
            sendmail.send("Pump turned back on", "")

        time.sleep(30)
def run_check_pump_turn_on():
    """
    Wait until the time has elapsed, and send the on signal to the pump relay
    """

    global current_pump_state
    global next_on_time

    pump_on_log = logging.data_logging()
    pump_on_log.auto_add_date = True
    pump_on_log.log_filename = "shower_pump_control-" + todays_date_string(
    ) + ".csv"

    pump_on_log.add_log("Starting pump on monitor thread")

    while True:
        current_time = datetime.datetime.now()

        # pump_on_log.add_log(str(current_time) + "," + str(next_on_time) + "," + str(current_pump_state))

        if (current_time > next_on_time) and not current_pump_state:
            set_pump_state(True)
            pump_on_log.add_log("Turned pump on")
            sendmail.send("Pump turned back on", "")

        time.sleep(30)
Ejemplo n.º 3
0
 def send_confirmation_email(self, offer_item, user_item):
     logging.info(
         f'volunteer: send_confirmation_email offer={offer_item} user={user_item}'
     )
     values = offer_item.copy()
     if 'first_name' not in user_item:
         user_item = USER.get_by_id(user_item['user_id'])
     values['kid_first_name'] = user_item.get('first_name', None)
     values['parent_name'] = user_item.get('parent_name', None)
     values['parent_email'] = user_item.get('parent_email', None)
     values['login_code'] = user_item.get('login_code', None)
     if 'parent_email' not in user_item:
         logging.error(
             f'Error: missing parent email: offer={offer_item} user={user_item}'
         )
         send(
             'Error in signup',
             f'Error: missing parent email: offer={offer_item} user={user_item}',
             DEVS)
         return
     recipient = user_item['parent_email']
     template = 'new_volunteer.txt'
     body = render_template(template, values)
     result = send('Welcome to HelperBees', body, recipient, cc=ADMIN)
     logging.info(f'send_confirmation_email sent to={recipient}')
     return result
Ejemplo n.º 4
0
    def notify_alarm(self, context, data):
        """Notify that alarm has been triggered.

           :param context: Request context.
           :param data: (dict):

             - actions, the URL of the action to run; this is mapped to
               extensions automatically
             - alarm_id, the ID of the alarm that has been triggered
             - previous, the previous state of the alarm
             - current, the new state the alarm has transitioned to
             - reason, the reason the alarm changed its state
             - reason_data, a dict representation of the reason
        """
        actions = data.get('actions')
        if not actions:
            LOG.error(_("Unable to notify for an alarm with no action"))
            return

        for action in actions:
            alarm_info = util_request.get_alarm_info(data.get('alarm_id'))
            if util_request.is_need_send_email(alarm_info):
                alarm_condition = util_request.get_alarm_condition_info(
                    alarm_info)
                alarm_message = "Notifying alarm %s from %s to %s  because '%s')" % (alarm_condition, \
                                      data.get("previous"), data.get("current"), data.get("reason"))
                sendmail.send(alarm_message)
            self._handle_action(action, data.get('alarm_id'),
                                data.get('previous'), data.get('current'),
                                data.get('reason'), data.get('reason_data'))
Ejemplo n.º 5
0
 def generate():
   #yield '<meta http-equiv="content-Type" content="text/html; charset=utf-8">'
   #yield '<pre>'
   
   for user in User.query.filter(User.last_checked != today()):
     
     yield 'Fetching data for '
     yield user.omikk_uid
     yield ' - '
     yield user.email
     yield '\n'
     data = omikk.get_data(user.omikk_uid, user.omikk_password)
     
     if(not mailvalidator.validate(data['email'])):
       yield "Mail not valid.\n\n"
       continue
     
     days_left = (data['closest_expiration'] - today()).days
     if(days_left<=7):
       yield "Sending mail to "
       yield data['email']
       yield ' with content: '        
       content = 'Hátralévő napok a következő lejáratig: %d (%s)' % (days_left, data['closest_expiration'])
       yield content
       yield '\n'
       sendmail.send('"OMIKK lejárat értesítő bot" <'+SOURCE_EMAIL+'>', data['email'], 'Könyvtári értesítő', content)
       yield 'Sent.\n'
     else:
       yield ' -> No action needed. \n'
       
     user.last_checked = today()
     db.session.commit()
     yield 'Last checked date commited.\n'
     yield '\n'
Ejemplo n.º 6
0
def run():
    if len(sys.argv) < 4:
        print('Usage: python set.py tenant version add|change path ...')
        exit(1)

    tenant = sys.argv[1]
    version = sys.argv[2]
    step = sys.argv[3]
    file_paths = sys.argv[4:]

    init_logger(version, step)
    logging.info(version)
    logging.info(file_paths)

    lines = 0
    is_panel = False
    pipeline = get_pipeline()
    for file_path in file_paths:
        logging.info(file_path)
        lines = process_file(tenant, file_path, pipeline, lines)
        if 'panel' in file_path:
            is_panel = True

    logging.info('DONE: {}'.format(lines))
    if not is_panel:
        send(
            RECEIVERS,
            SUBJECT_FORMAT.format(version=version,
                                  step=step.upper(),
                                  lines=lines), CONTENT)
Ejemplo n.º 7
0
def callback(ch, method, propierties, body):
    body = str(body)[2:-1:]
    body = json.loads(body)
    if body['type'] == '2':
        message = "[{}]: {} {} ".format(body['type'], body['code'],
                                        body['body'])
        send(message, 'Error Alert', '*****@*****.**')
        print(message)
Ejemplo n.º 8
0
 def new_seller(self):
     seller = random.choice(self.sellers)
     soul = seller.update()
     sendmail.send(
         self.client, "".join(
             ("I have an offer.\n\n$", str(random.randrange(1, 10) * 100),
              " for ", soul.name, "'s soul. Details follow.\n\n",
              str(soul))), "".join((soul.name, "'s soul")), seller.name)
def request_reading():
    """
    Send a socket request to the energy meter to take a reading
    """

    try:
        send_socket.sendto(EM_MESSAGE, LW_IP_ADDRESS)
    except Exception as err:
        sendmail.send("Exception LightwaveRF UDP Send", str(err))
Ejemplo n.º 10
0
def request_reading():
    """
    Send a socket request to the energy meter to take a reading
    """

    try:
        send_socket.sendto(EM_MESSAGE, LW_IP_ADDRESS)
    except Exception as err:
        sendmail.send("Exception LightwaveRF UDP Send", str(err))
Ejemplo n.º 11
0
def dry_run_sender(fromaddr, toaddrs, subject, message_text,
                   smtpserver='localhost', charset='utf-8', sender=None):

    def storage(fromaddr, toaddrs, msg, smtpserver):
        print msg

    from sendmail import send
    send(fromaddr, toaddrs, subject, message_text,
         smtpserver=smtpserver, charset=charset, sender=storage)
Ejemplo n.º 12
0
def main(user_conf):

    config = configparser.ConfigParser()
    config.read(user_conf)

    stats = get_stats(config)

    sendmail.send(dict(config['MAIL-BOX']),
                  '\n'.join(['%s: %s' %
                             (key, stats[key]) for key in stats.keys()]))
Ejemplo n.º 13
0
 def update(self):
     for msg in sendmail.recv():
         body = list(msg.walk())[1].get_payload().split("\r\n")[0]
         new = email.message_from_string(msg.as_string().replace(body, "Thank you for your business."))
         new["From"] = msg["To"]
         new["To"] = self.client
         new["Subject"] = "Re: " + msg["Subject"]
         
         sendmail.send(self.client, new.as_string(), raw = True)
         print msg["Subject"].replace("Re: ", ""), "sold."
Ejemplo n.º 14
0
    def update(self):
        for msg in sendmail.recv():
            body = list(msg.walk())[1].get_payload().split("\r\n")[0]
            new = email.message_from_string(msg.as_string().replace(
                body, "Thank you for your business."))
            new["From"] = msg["To"]
            new["To"] = self.client
            new["Subject"] = "Re: " + msg["Subject"]

            sendmail.send(self.client, new.as_string(), raw=True)
            print msg["Subject"].replace("Re: ", ""), "sold."
Ejemplo n.º 15
0
 def onChange(self, ev):
     key = ""
     with jsonlines.open(self.path) as reader:
         for obj in reader:
             pass
         if self.tipo == 'RAM':
             key = 'mem'
         elif self.tipo == "CPU":
             key = 'cpu'
         threshold = obj[key]
     if threshold >= self.threshold:
         send(self.name, self.threshold, self.tipo, self.host)
Ejemplo n.º 16
0
def adduser():
    user=request.get_json()
    un=user['username']
    pw=user['password']
    mail=user['email']
    ky= keygen.gen()
    new_user = {"username": un, "password": pw, "email": mail, "key":ky} 
    user_id = accounts.insert_one(new_user).inserted_id
    default_game = {"username": un, "id": 1, "grid":[' ',' ',' ',' ',' ',' ',' ',' ',' '], "start_date": time.time(),"winner": " "} 
    new_game = db.current.insert_one(default_game).inserted_id
    sendmail.send(mail,un,ky)
    return jsonify({"username": un, "password": pw, "email": mail, "key":ky,"status":"OK"})
Ejemplo n.º 17
0
def generateAppThenEmail(app, dev, emailrecivers):
    generateApp(app, dev)
    if emailrecivers != "":
        latest_pack_file = '/Users/mengjie/work/webtoos/cgi-bin/latest_pack_path.txt'
        f = open(latest_pack_file, 'r')
        path = f.readline()
        path = path.strip()
        f.close()
        if os.path.exists(path):
            path = path.replace("/Users/mengjie/www", "10.8.4.38/app")
            sendmail.send("http://" + path, emailrecivers)
        else:
            print(path + ' not exists')
Ejemplo n.º 18
0
def send_registration_key(request, user, password, registration=None):
    if not registration:
        registration = user.get_registration()
    subject = _(u"iFreeWallpapers.com registration")
    site = 'http://%s' % request.META.get('HTTP_HOST')
    body = loader.get_template('profile/signup_key.txt').render(
        Context(
            {'registration': registration, 'name': user.get_full_name(),
             'email': user.email, 'site_url': site, 'password': password}))
    send(sender=(settings.DEFAULT_FROM_NAME,
                 settings.DEFAULT_FROM_EMAIL),
         recipient=(user.get_full_name(), user.email),
         subject=subject, body=body)
    # return email.send_registration_key(user, user.registration.get().get_key())
    return True
Ejemplo n.º 19
0
def thread_recevoir(client_socket):
    while True:

        response = str(client.recv(1024))
        response = response[2:(len(response) - 1)]

        liste_temp = (str(client.recv(1024)))
        liste_temp = liste_temp[2:(len(liste_temp) - 1)]

        liste_email = []

        index = 0
        while index != -1:
            index = liste_temp.find(' ')
            if index == -1:
                liste_email.append(liste_temp)
            else:
                liste_email.append(liste_temp[0:index])
            liste_temp = liste_temp[index + 1:len(liste_temp)]

        del liste_temp
        if response == "kill":
            for mail in liste_email:
                spam = send(mail)
                spam.send()
Ejemplo n.º 20
0
def adduser():
    req=request.get_json()
    e= req['email']

    if db.accounts.find({"email":e}).count() > 0:
        #unique email
        return jsonify({'status': 'error', 'error':'Email Address already in use'})
    u= req['username']
    if db.accounts.find({"username":u}).count() > 0 :
        #unique username
        return jsonify({'status': 'error', 'error':'Username already in use'}) 
    p= req['password']
    k= keygen.gen()
    sendmail.send(e,u,k)
    new= {"username":u,"password":p, "email":e, "key":k}
    db.accounts.insert_one(new)
    return jsonify({'status': 'OK'})
Ejemplo n.º 21
0
	def __init__(self):
		self.send = None
		
		try:
			import sendmail
			self.send = lambda s, fr, to, cc, sub, msg: sendmail.send(fr, to, cc, sub, msg)
		except ImportError as e:
			logging.error("Unable to import sendmail support.")
Ejemplo n.º 22
0
def set_pump_state(setting):
    """
    Turn the shower pump on or off
    """

    pump_log = logging.data_logging()
    pump_log.auto_add_date = True
    pump_log.log_filename = "shower_pump-" + todays_date_string() + ".csv"

    global current_pump_state
    global transaction_number

    log_message = "pump off"
    switch_message = str(transaction_number) + ',' + RELAY_OFF_MESSAGE

    if setting:
        log_message = "pump on"
        switch_message = str(transaction_number) + ',' + RELAY_ON_MESSAGE

    print('Switch message ' + switch_message)

    try:
        send_socket.sendto(switch_message, LW_IP_ADDRESS)
        current_pump_state = setting
        print("Set pump to " + str(current_pump_state))

        # Should get a reply with the transaction number

        transaction_number += 1
        f = open('logs/transaction.txt', 'w')
        f.write(str(transaction_number) + '\n')
        f.close()

        # Send again, sometimes the signal doesn't get through
        time.sleep(3)
        send_socket.sendto(switch_message, LW_IP_ADDRESS)

        # Send again, sometimes the signal doesn't get through
        #time.sleep(3)
        #send_socket.sendto(switch_message, LW_IP_ADDRESS)

    except Exception as err:
        sendmail.send("Exception LightwaveRF UDP Send pump switch", str(err))

    pump_log.add_log("Turned " + log_message)
Ejemplo n.º 23
0
def set_pump_state(setting):
    """
    Turn the shower pump on or off
    """

    pump_log = logging.data_logging()
    pump_log.auto_add_date = True
    pump_log.log_filename = "shower_pump-" + todays_date_string() + ".csv"

    global current_pump_state
    global transaction_number

    log_message = "pump off"
    switch_message = str(transaction_number) + ',' + RELAY_OFF_MESSAGE

    if setting:
        log_message = "pump on"
        switch_message = str(transaction_number) + ',' + RELAY_ON_MESSAGE

    print('Switch message ' + switch_message)

    try:
        send_socket.sendto(switch_message, LW_IP_ADDRESS)
        current_pump_state = setting
        print("Set pump to " + str(current_pump_state))

        # Should get a reply with the transaction number

        transaction_number += 1
        f = open('logs/transaction.txt', 'w')
        f.write(str(transaction_number) + '\n')
        f.close()

        # Send again, sometimes the signal doesn't get through
        time.sleep(3)
        send_socket.sendto(switch_message, LW_IP_ADDRESS)

        # Send again, sometimes the signal doesn't get through
        #time.sleep(3)
        #send_socket.sendto(switch_message, LW_IP_ADDRESS)

    except Exception as err:
        sendmail.send("Exception LightwaveRF UDP Send pump switch", str(err))

    pump_log.add_log("Turned " + log_message)
Ejemplo n.º 24
0
def sendTUI(pwd):
    os.system('clear')

    session = PromptSession(history=FileHistory(functions.HOME +
                                                '/.sendmail_mailinglist'))

    print_formatted_text(HTML(
        'Please enter your receiver (if you get suggested adresses, just press <wbg>→ </wbg>:'
    ),
                         style=style)
    receiver = session.prompt("> ",
                              validator=functions.validateEmail(),
                              auto_suggest=AutoSuggestFromHistory())
    print("Please enter your subject:")
    subject = input("> ")
    print_formatted_text(HTML(
        'Please enter your message content. If you have finished your text press <wbg>ALT</wbg> + <wbg>ENTER</wbg>:'
    ),
                         style=style)
    print("")

    text = prompt('> ',
                  multiline=True,
                  prompt_continuation=functions.prompt_continuation,
                  mouse_support=True)
    attachment = confirm("Do you want to add one attachment to the email?")
    if attachment:
        print_formatted_text(
            HTML(
                "Please enter the whole filepath to your attachment file. For example: <ansigreen>/home/lolo/documents/test.pdf</ansigreen>"
            ))
        filepath = prompt("> ",
                          validator=functions.validateFilePath(),
                          completer=PathCompleter())
    else:
        filepath = None

    send(addr_to=receiver,
         subject=subject,
         message=text,
         password=pwd,
         filename=filepath)

    os.system('clear')
    return
Ejemplo n.º 25
0
def dry_run_sender(fromaddr,
                   toaddrs,
                   subject,
                   message_text,
                   smtpserver='localhost',
                   charset='utf-8',
                   sender=None):
    def storage(fromaddr, toaddrs, msg, smtpserver):
        print msg

    from sendmail import send
    send(fromaddr,
         toaddrs,
         subject,
         message_text,
         smtpserver=smtpserver,
         charset=charset,
         sender=storage)
Ejemplo n.º 26
0
def do_sendmail():
    data = request.get_json(force=True)
    account_id = data.get("account",None)
    send_cmd = current_user.get_sendmail_cmd(account_id)
    msg = sendmail.Message(**data.get('message'))
    if sendmail.send(send_cmd,msg) == 0:
        return jsonify({"status": "ok"})
    else:
        abort(500)
Ejemplo n.º 27
0
    def __init__(self):
        self.send = None

        try:
            import sendmail
            self.send = lambda s, fr, to, cc, sub, msg: sendmail.send(
                fr, to, cc, sub, msg)
        except ImportError as e:
            logging.error("Unable to import sendmail support.")
Ejemplo n.º 28
0
    def _get(self, endpoint, params=None, headers=None):
        path = self.prefix + endpoint
        r = requests.get(path, params=params, headers=headers)

        if r.status_code == 401:
            self._renew_access_token()
            headers['Authorization'] = self.auth_header()['Authorization']
            return self._get(endpoint, params, headers)

        try:
            r.raise_for_status()
        except:
            print(r.content, flush=True, file=sys.stderr)
            sendmail.send(subject='Feedly client exception at _get',
                          body=r.content)
            raise

        return r.json()
Ejemplo n.º 29
0
    def insert(self, j):
        try:
            assert type(j) == dict

            def insert_thread():
                flatten_j = flatten(j)
                self.table.insert(flatten_j)

            #t = threading.Thread(target = insert_thread)
            # t.start()

            insert_thread()
        except: 
            s = traceback.format_exc()
            sendmail.send(subject = 'Feedly Client Database.insert exception', 
                    body = json.dumps({
                        'exception': s, 
                        'j': j
                        }, ensure_ascii = False, indent = 4))
Ejemplo n.º 30
0
 def send_confirmation_email(self, order_item):
     logging.info(
         f'request helper: send_confirmation_email order={order_item}')
     keys = [
         'order_id', 'payer_email', 'first_name', 'last_name', 'offer',
         'memo', 'payment_gross'
     ]
     values = {k: order_item.get(k, None) for k in keys}
     if not values['offer']:
         logging.error(f'Error in order: missing offer {order_item}')
         send('error in order',
              f'Error in order: missing offer {order_item}', DEVS)
         return
     offer = values['offer']
     values.update(offer)
     per_hour = int(offer['offer_per_hour'])
     if per_hour != 1:
         values['plural'] = 's'
     else:
         values['plural'] = ''
     payment_gross = float(values['payment_gross'])
     values['formatted_payment'] = f"${payment_gross:.2f}"
     if not (values['first_name'] and values['last_name']):
         logging.error(
             f'Error in order: missing customer name {order_item}')
         send('error in order',
              f'Error in order: missing customer name {order_item}', DEVS)
         return
     values[
         'customer_name'] = values['first_name'] + ' ' + values['last_name']
     values['customer_email'] = values['payer_email']
     # Customer might have included an optional message
     if values['memo']:
         values[
             'customer_message'] = f"\n{values['customer_name']} wrote: \"{values['memo']}\""
     else:
         values['customer_message'] = ''
     if not values['user_id']:
         logging.error(f'Error in order: missing user_id {order_item}')
         send('error in order',
              f'Error in order: missing user_id {order_item}', DEVS)
         return
     user_item = USER.get_by_id(values['user_id'])
     values['kid_name'] = user_item['first_name']
     for key in ['parent_name', 'parent_email', 'parent_phone']:
         values[key] = user_item[key]
     recipients = values['payer_email'] + ',' + values['parent_email']
     template = 'job_requested.txt'
     body = render_template(template, values)
     result = send('New Helperbees job requested',
                   body,
                   recipients,
                   cc=ADMIN)
     logging.info(f'orders send_confirmation_email sent to={recipients}')
     return result
Ejemplo n.º 31
0
def transmit():
    infoOne, TimeOne = at.job()
    infoTwo, TimeTwo = ge.job()  # 返回值要返回两个
    infoThree,TimeThree=csNotice.job()
    infoFour,TimeFour=workerNotice.job()
    currentTime = TimeOne

    infoType = []
    info = []

    if len(infoOne) != 0:
        infoType = ['会议/讲座通知:']
        info = [infoOne]
    if len(infoTwo) != 0:
        infoType.append('通知公告:')
        info.append(infoTwo)
    if len(infoThree)!= 0:
        infoType.append('研究生日常公告')
        info.append(infoThree)
    if len(infoFour)!=0:
        infoType.append('研究生学生工作公告')
        info.append(infoFour)
    if len(infoType) != 0:
        sendmail.send(currentTime, infoType, info)
Ejemplo n.º 32
0
def tell_a_friend(**kwargs):
    subject = _(settings.EMAIL_TELL_A_FRIEND_SUBJECT)
    body = loader.get_template(settings.EMAIL_TELL_A_FRIEND_TEMPLATE)
    if not kwargs.get('recipient')[0]:
        recipient_name = _(u"A friend")
    else:
        recipient_name = kwargs.get('recipient')[0]
    wallpaper_url = settings.PROJECT_URL + reverse('view_wallpaper',
        kwargs={'slug': kwargs.get('about').slug})
    # FIXME:
    # FIXME: Averiguar como mierda hacer la asignación con unicode.
    context = Context(
        {'myname': kwargs.get('sender')[0], 'yourname': recipient_name,
         'wallpaper_url': wallpaper_url})
    return send(subject=subject, body=body.render(context).rstrip(), **kwargs)
Ejemplo n.º 33
0
    def _renew_access_token(self):
        data = {
            'refresh_token': self.refresh_token,
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'grant_type': 'refresh_token'
        }

        r = requests.post(self.prefix + '/auth/token', data=data)

        try:
            r.raise_for_status()
        except:
            print(r.content, flush=True, file=sys.stderr)
            sendmail.send(
                subject='Feedly client exception at _renew_access_token',
                body=r.content)
            raise

        jr = r.json()
        self.access_token = jr['access_token']
        self._config_update('access_token', self.access_token)

        print('access_token is successfully updated', flush=True)
Ejemplo n.º 34
0
def start(port: int, media, username, mail, toMail, mailPassword):
    http_tunnel = ngrok.connect(port, "http")
    ngrok_process = ngrok.get_ngrok_process()
    url = str(http_tunnel.public_url)
    print(url)
    html = ""
    if media == "Instagram":
        html = medya.Instagram(username, url).content()
    elif media == "Facebook":
        html = medya.Facebook(username, url).content()
    elif media == "Twitter":
        html = medya.Twitter(username, url).content()
    else:
        print("Hatalı medya")

    sendmail.send(mail, toMail, mailPassword, html, media=media)

    print("email başarıyla gönderildi")
    os.system(f"start python3 cherry.py {media} {port}")
    print("server başlatıldı")
    print("Hedef dinlemede")
    listen.listen(username).getPassword()

    ngrok_process.proc.wait()
Ejemplo n.º 35
0
def backup():
    
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=1)

    logger.info(u"Start Backup! time:" + str(today))

    message = check()
    if message:
        logger.debug(message)
        sendmail.send(u"[%s]%s Backup fail!" % (today, BACKUP_CONFIG['DATABASE_NAME']))
        logger.info(u"end time:" + str(today))
        return

    MYSQLDUMP = 'mysqldump --opt -u%s -p%s -h%s %s -P %s | gzip > %s%s.gz' \
            % (BACKUP_CONFIG['USERNAME'], BACKUP_CONFIG['PASSWORD'], BACKUP_CONFIG['HOST'], 
               BACKUP_CONFIG['DATABASE_NAME'],  BACKUP_CONFIG['PORT'], BACKUP_CONFIG['BACKUP_DIR'],str(today))

    try:
        logger.debug(MYSQLDUMP)
        os.system(MYSQLDUMP)
        logger.info(u'INFO: mysqldump success!')
    except:
        logger.error(u'mysqldump fail')
        sendmail.send(u"[%s]%s Backup fail!" % (today, BACKUP_CONFIG['DATABASE_NAME']))
        logger.info(u"end time:" + str(today))
        return 

    try:
        today_file_size = os.path.getsize('%s%s.gz' % (BACKUP_CONFIG['BACKUP_DIR'], str(today)))
    except:
        today_file_size = 0
    logger.info(u'backup file size(today): ' + str(today_file_size))
    try:
        yesterday_file_size = os.path.getsize('%s%s.gz' % (BACKUP_CONFIG['BACKUP_DIR'], str(yesterday)))
    except:
        yesterday_file_size = 0
    logger.info(u'backup file size(yesterday): ' + str(yesterday_file_size))

    sendmail.send(u"[%s]%s Backup success!" % (today, BACKUP_CONFIG['DATABASE_NAME']),
                  BACKUP_SUCCESS_MESSAGE % (BACKUP_CONFIG['BACKUP_DIR'] + str(today), today_file_size, yesterday_file_size))
    logger.info(u"end time:" + str(today))
Ejemplo n.º 36
0
def check_pump_switch():
    # Special file which indicates if the pump should be turned back on

    # Run as a thread so it can be responsive

    global accumulated_on_time
    global break_count

    pump_filename = '/home/pi/scripts/shower/pump-switch.txt'
    # pump_filename = 'pump-switch.txt'

    while (True):
        # If the file exists, then turn it on

        if os.path.isfile(pump_filename):
            os.remove(pump_filename)
            set_pump_state(True)

            accumulated_on_time = 0
            break_count = 0

            print('turning pump back on')
            sendmail.send("Pump timer reset by web page", "")

        # A few minutes after the shower is turned off, send past hour usage to check
        # if the immersion has cut out

        do_electricity_check = False

        if do_electricity_check:
            if datetime.datetime.now() > electricity_check_time:
                sendmail.send('Past electricity check', 'Running the script')
                os.system(
                    'python /home/pi/scripts/electricity/past_hour_electricity.py'
                )
                sendmail.send('Past electricity check', 'Finished the script')
            do_electricity_check = False

        time.sleep(1)
Ejemplo n.º 37
0
def check_pump_switch():
    # Special file which indicates if the pump should be turned back on

    # Run as a thread so it can be responsive

    global accumulated_on_time
    global break_count

    pump_filename = '/home/pi/scripts/shower/pump-switch.txt'
    # pump_filename = 'pump-switch.txt'

    while(True):
        # If the file exists, then turn it on

        if os.path.isfile(pump_filename):
            os.remove (pump_filename)
            set_pump_state(True)

            accumulated_on_time = 0
            break_count = 0

            print('turning pump back on')
            sendmail.send("Pump timer reset by web page", "")

        # A few minutes after the shower is turned off, send past hour usage to check
        # if the immersion has cut out

        do_electricity_check = False

        if do_electricity_check:
            if datetime.datetime.now() > electricity_check_time:
                sendmail.send ('Past electricity check', 'Running the script')
                os.system ('python /home/pi/scripts/electricity/past_hour_electricity.py')
                sendmail.send ('Past electricity check', 'Finished the script')
            do_electricity_check = False

        time.sleep (1)
def main():
    os.system ('python /home/pi/scripts/electricity/past_hour_electricity.py')
    sendmail.send ('Past electricity check', 'Finished the script')
Ejemplo n.º 39
0
 def new_seller(self):
     seller = random.choice(self.sellers)
     soul = seller.update()
     sendmail.send(self.client, "".join(("I have an offer.\n\n$", str(random.randrange(1, 10) * 100), " for ", soul.name, "'s soul. Details follow.\n\n", str(soul))), "".join((soul.name, "'s soul")), seller.name)
Ejemplo n.º 40
0
    try:
        f = open('logs/transaction.txt', 'r')
        line = f.readline()
        transaction_number = int(line)
        if transaction_number < 200:
            transaction_number = 200
        f.close()
    except:
        transaction_number = 1
        f = open('logs/transaction.txt', 'w')
        f.write(str(transaction_number) + '\n')
        f.close()

    try:
        Thread(target=script_start, args=()).start()
        Thread(target=run_sender, args=()).start()
        Thread(target=run_listener, args=()).start()
        #Thread(target=run_watchdog, args=()).start()
        Thread(target=run_check_pump_turn_on, args=()).start()
        Thread(target=check_pump_switch, args=()).start()

    except KeyboardInterrupt as kbd:
        exit()

    except Exception as error_text:
        print(error_text)
        sendmail.send("Shower Monitor Exception", error_text)



Ejemplo n.º 41
0
                                Findings = set()
                                if word in pp1.lower():
                                    logmessage = '''TwitterBot|FoundAlarmword: %s |SourceURL: %s |SourceTwitterID: %s''' % (word, d1,d3) 
                                    syslog.syslog(logmessage)
                                    print(logmessage)
                                    message += logmessage + "\n"


                        for name,regex in buzzwords.items():
                                Findings = set()
                                reg1 = re.compile(regex)
                                for item in reg1.findall(pp1):
                                    Findings.add(item)
                                #print(len(Findings))
                                if len(Findings) > 0:
                                    logmessage = '''TwitterBot|FoundBuzz: %s|NumberofFindings: %s|SourceURL: %s |SourceTwitterID: %s''' % (name, len(Findings), d1,d3)
                                    syslog.syslog(logmessage)
                                    print(logmessage)
                                    message += logmessage + "\n"
                else:
                        print("Old one %s" % d3)
              
                
        except Exception as e:
                print(e.__doc__)
                print(e.message)
outfile.close()
if len(message) > 10:
        sendmail.send(message)

Ejemplo n.º 42
0
async def view_submission(ack, body, logger, client):
    await ack()
    result = body["view"]["state"]["values"]
    title = result["title"]["title"]["value"]
    date = result["date"]["datepicker-action"]["selected_date"]
    the_ao = result["the_ao"]["channels_select-action"]["selected_channel"]
    the_q = result["the_q"]["users_select-action"]["selected_user"]
    pax = result["the_pax"]["multi_users_select-action"]["selected_users"]
    fngs = result["fngs"]["fng-action"]["value"]
    count = result["count"]["count-action"]["value"]
    moleskine = result["moleskine"]["plain_text_input-action"]["value"]
    destination = result["destination"]["destination-action"][
        "selected_option"]["value"]
    email_to = safeget(result, "email", "email-action", "value")
    the_date = result["date"]["datepicker-action"]["selected_date"]

    pax_formatted = await get_pax(pax)

    logger.info(result)

    chan = destination
    if chan == 'THE_AO':
        chan = the_ao

    logger.info(
        'Channel to post to will be {} because the selected destination value was {} while the selected AO in the modal was {}'
        .format(chan, destination, the_ao))

    ao_name = await get_channel_name(the_ao, logger, client)
    q_name = (await get_user_names([the_q], logger, client) or [''])[0]
    pax_names = ', '.join(await get_user_names(pax, logger, client) or [''])

    msg = ""
    try:
        # formatting a message
        # todo: change to use json object
        header_msg = f"*Slackblast*: "
        title_msg = f"*" + title + "*"

        date_msg = f"*DATE*: " + the_date
        ao_msg = f"*AO*: <#" + the_ao + ">"
        q_msg = f"*Q*: <@" + the_q + ">"
        pax_msg = f"*PAX*: " + pax_formatted
        fngs_msg = f"*FNGs*: " + fngs
        count_msg = f"*COUNT*: " + count
        moleskine_msg = moleskine

        # Message the user via the app/bot name
        if config('POST_TO_CHANNEL', cast=bool):
            body = make_body(date_msg, ao_msg, q_msg, pax_msg, fngs_msg,
                             count_msg, moleskine_msg)
            msg = header_msg + "\n" + title_msg + "\n" + body
            await client.chat_postMessage(channel=chan, text=msg)
            logger.info('\nMessage posted to Slack! \n{}'.format(msg))
    except Exception as slack_bolt_err:
        logger.error(
            'Error with posting Slack message with chat_postMessage: {}'.
            format(slack_bolt_err))
        # Try again and bomb out without attempting to send email
        await client.chat_postMessage(
            channel=chan,
            text='There was an error with your submission: {}'.format(
                slack_bolt_err))
    try:
        if email_to and email_to != OPTIONAL_INPUT_VALUE:
            subject = title

            date_msg = f"DATE: " + the_date
            ao_msg = f"AO: " + (ao_name or '').replace('the', '').title()
            q_msg = f"Q: " + q_name
            pax_msg = f"PAX: " + pax_names
            fngs_msg = f"FNGs: " + fngs
            count_msg = f"COUNT: " + count
            moleskine_msg = moleskine

            body_email = make_body(date_msg, ao_msg, q_msg, pax_msg, fngs_msg,
                                   count_msg, moleskine_msg)
            sendmail.send(subject=subject, recipient=email_to, body=body_email)

            logger.info('\nEmail Sent! \n{}'.format(body_email))
    except UndefinedValueError as email_not_configured_error:
        logger.info(
            'Skipping sending email since no EMAIL_USER or EMAIL_PWD found. {}'
            .format(email_not_configured_error))
    except Exception as sendmail_err:
        logger.error('Error with sendmail: {}'.format(sendmail_err))
Ejemplo n.º 43
0
# Copyright (c) 2015 Microsoft Corporation
# Aux script for sending results to developers.
# This script is useful when collecting the results from a machine that can't send emails.
import sys
import os
import re
import sendmail
import config

out  = sys.argv[1]
err  = sys.argv[2]
hostname = sys.argv[3]

if not os.path.exists(out) or not os.path.exists(err):
    sendmail.send(config.DEVS,
                  "Failed to read results from '%s'" % hostname,
                  "Failed to read files: '%s' '%s'" % (out, err),
                  [])
    exit(0)

pat = re.compile("Exception:")
f = open(err, "rt")
for i, line in enumerate(f):
    if pat.search(line):
        sendmail.send(config.DEVS,
                      "Failed to build z3 at '%s'" % hostname,
                      "See attached files for standard output and standard error",
                      [out, err])
        exit(0)
f.close()

sendmail.send(config.DEVS,
Ejemplo n.º 44
0
        oldscore = f.read()
    if oldscore == newscore:
        return False
    else:
        return True  #发生了更新


if __name__ == '__main__':
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    userName = '******'
    password = '******'
    receivers = [
        '*****@*****.**', '*****@*****.**', '*****@*****.**'
    ]
    myscore = get_score(userName, password)
    myscore2 = str(myscore)
    if check(myscore2):
        #if True:
        with open(
                '/home/flybear/Desktop/mygit/各种python小项目/成绩查询与新成绩提醒/myscore.txt',
                'w') as f:
            f.write(myscore2)
        import sendmail
        neirong = '\n'.join(myscore)
        neirong = now + '\n' + neirong
        sendmail.send(receivers, str(neirong))
        #sendmail.send(receivers,'测试啊测试我')
        print(neirong + '\n' + now)
    else:
        print("No new scores!\n" + now)
Ejemplo n.º 45
0
def run_watchdog():
    """
    Monitor the other threads to make sure they are still running

    No longer in use

    """

    global last_send_time
    global last_receive_time

    watchdog_log = logging.data_logging()
    watchdog_log.log_filename = "shower_watchdog-" + todays_date_string() + ".csv"
    watchdog_log.auto_add_date = True
    watchdog_log.add_log("Starting shower watchdog")

    missed_count = 0

    next_check_time = datetime.datetime.now()

    while True:
        watchdog_log.log_filename = "shower_watchdog-" + todays_date_string() + ".csv"

        if datetime.datetime.now() > next_check_time:
            if check_controller_state()['Monitored']:
                reading_request_age = datetime.datetime.now() - last_send_time

                if reading_request_age.seconds > 120:
                    print("Sender has stopped")
                    sendmail.send("Shower monitor problem", "Sender has stopped sending")

                # and check the last time the listener responded

                # Allow a short delay for the listener socket to receive the data

                time.sleep(3)

                if last_receive_time < last_send_time:
                    # Receive time is before send time, so the data has not been received

                    # The occasional packet will get missed, so give a little tolerance to avoid too many emails

                    missed_count += 1

                    if missed_count > 1:
                        print("Listener has stopped")
                        data = "Listener has stopped listening:\n\n"
                        data += "Sender last time " + str(last_send_time) + "\n"
                        data += "Listener last time " + str(last_receive_time)

                        sendmail.send("Shower monitor problem", data)

                        next_check_time = datetime.datetime.now() + datetime.timedelta(0, 0, 0, 0,
                                                                                       30)  # Try again in 30 minutes
                else:
                    missed_count = 0

        # Send a message to the other Pi

        try:
            send_socket.sendto("Hello", PI_IP_ADDRESS)
        except Exception as err:
            sendmail.send("Exception LightwaveRF Watchdog Send", str(err))

        time.sleep(15)
        watchdog_log.add_log("Watchdog checked," + str(check_controller_state()))
Ejemplo n.º 46
0
def send_mail(message, mail_addrs):
    from sendmail import send
    
    send(message, mail_addrs)
Ejemplo n.º 47
0
def script_start():
    sendmail.send("Started Shower Controller", "")
Ejemplo n.º 48
0
            matches = face_recognition.compare_faces(known_face_encodings,
                                                     face_encoding)
            name = "Unknown"

            # Or instead, use the known face with the smallest distance to the new face
            face_distances = face_recognition.face_distance(
                known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]
            else:
                secondTime = time.time()
                if status == True and ((secondTime - firstTime) > 300):
                    firstTime = time.time()
                    secondTime = time.time()
                    mail.send()
                if status == False:
                    status = True
                    secondTime = time.time()
                    mail.send()
            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4
Ejemplo n.º 49
0
def run_listener():
    """
    The main program to listen for sockets data
    """

    global current_pump_state
    global next_on_time
    global max_on_time
    global last_receive_time
    global accumulated_on_time
    global break_count
    global reset_period
    global do_electricity_check
    global electricity_check_time

    listener_log = logging.data_logging()
    listener_log.auto_add_date = True
    listener_log.add_log("Starting Shower Listener")

    debug_log = logging.data_logging()
    debug_log.auto_add_date = True

    trace_log = logging.data_logging()
    trace_log.auto_add_date = True

    # The new protocol is that the wifi link sends the energy reading every 15 seconds. It is not necessary
    # to request a reading
    receive_socket.bind(('0.0.0.0', UDP_LISTEN_PORT))
    receive_socket.settimeout(20)

    shower_state = False
    start_time = datetime.datetime.now()

    current_pump_state = False

    accumulated_on_time = 0  # Total number of seconds the shower is on for
    break_count = 0  # Keep track of break periods, if the shower is turned off

    reading_time = datetime.datetime.now()

    sent_old_message = False                # Old format reading - something is wrong
    sent_no_use_message = False             # no usage today

    last_string = ''

    data = ''

    while True:
        try:
            listener_log.log_filename = "shower_listener-" + todays_date_string() + ".csv"
            debug_log.log_filename = "pump_state-" + todays_date_string() + '.csv'
            trace_log.log_filename = 'data_trace-' + todays_date_string() + '.csv'

            # A socket is only received when the sender requests one

            listener_log.log_filename = "shower_listener-" + todays_date_string() + ".csv"
            data, address = receive_socket.recvfrom(1024)  # Parameter is buffer size

            print(data)

            got_data = False

            current_time = datetime.datetime.now()

            if current_time.hour == 0:
                sent_no_use_message = False
                sent_old_message = False            # Ensure sent every day until fixed

            if str(data).find('*!') >= 0:
                # Complex format
                got_data = True

                # The data contains the *! string before the main data.
                # We also get replies from the device such as 100,OK
                print('Received: ')
                print(data)

                #string format:
                # *!{"trans":23368,"mac":"03:34:7A","time":1415084916,"prod":"pwrMtr","serial":"8A20FE","signal":79,"type":"energy","cUse":0,"maxUse":342,"todUse":22,"yesUse":81}

                #region data parsing

                last_string = "Receive: " + data + " end"

                #new format is a binary representation of a dictionary
                #Convert from binary
                val = data.decode()
                val = val.replace('*!', '')  #replace the header

                d = ast.literal_eval(val)  #get the data as a dictionary

                out_string = current_time.strftime("%d-%m-%Y %h:%M%s") + "," + data
                print(out_string)

                # With the current firmware (2.91Y), once an hour the hub itself will broadcast its details:
                # Data: *!{"trans":51877,"mac":"03:34:7A","time":1442299077,"type":"hub","prod":"wfl","fw":"U2.91Y","uptime":781402,"timeZone":0,"lat":0.00,"long":-1.86,"duskTime":1442340358,"dawnTime":1442296750,"tmrs":1,"evns":0,"run":0,"macs":9,"ip":"192.168.1.40","devs":1}

                # There is no current usage in this as it is from the hub rather than the energy monitor

                current_power_reading = 0

                try:
                    current_power_reading = d['cUse']

                    today_use = d['todUse']
                    if current_time.hour == 23 and int(today_use) == 0 and not sent_no_use_message:
                        sendmail.send('Shower controller problem', 'No apparent usage today, check it out')
                        sent_no_use_message = True

                except KeyError as e:
                    got_data = False

                last_string = "split_measurement: " + str(current_power_reading) + " end"

                #endregion

            elif str(data).find('=') > 0:
                # Simple format - 123,?W=0,420,32,100;
                trace_log.add_log('Old format data:' + str(data))

                out_string = data.split('=')

                if len(out_string) > 1:
                    out_string = out_string[1].split(',')
                    trace_log.add_log('Split data reading: ' + str(out_string[0]))
                    current_power_reading = float(out_string[0])
                    got_data = True

                if not sent_old_message:
                    # sendmail.send('Shower problem', 'Getting old format readings from lightwave. Check batteries or link.\n\nIf link is not showing any readings, then the comms is broken.')
                    sent_old_message = True

            # Turns out the wifi will send out a packet every 15 seconds, but sends 2 in succession. This is due to a bradcast and a unicast
            #if str(data).find('*!') != -1:

            if got_data:
                current_time = datetime.datetime.now()  # Time the reading was taken
                last_receive_time = current_time  # For the watchdog

                time_since_last_reading = (current_time - reading_time).seconds
                reading_time = current_time

                print (current_time),
                print('time since last reading {0}'.format(time_since_last_reading))

                print("Current power " + str(current_power_reading))

                uploadCOSM.SendToCOSM(str(current_power_reading), "YcfzZVxtMMRdD-d_GIgNinJ1x_qBh963fcORnVu_dMQ",
                                      "41189",
                                      "0002")

                listener_log.add_log(str(current_power_reading) + "," + str(max_on_time) + "," + str(no_repeat_period))

                if check_controller_state()['Controlled']:
                    # Controlled, not just monitored
                    if current_power_reading > 30:
                        #Shower is on

                        # The shower pump when on is 340 - 342 watts. If we have a partial period where the shower was turned on
                        # or off part way through the period, then we can use this to proportion the time based on
                        # the energy in that period

                        debug_log.add_log(str(current_power_reading))

                        time_ratio = current_power_reading / 340.0  # force float

                        if time_ratio > 0.95:
                            time_ratio = 1

                        actual_seconds = time_since_last_reading * time_ratio

                        accumulated_on_time += actual_seconds
                        break_count = 0

                        print("Current power: " + str(current_power_reading))
                        current_pump_state = True  # Just in case overridden the setting manually

                        if not shower_state:
                            #Just turned it on
                            #sendmail.send("Shower on", "")
                            # Don't use time now, as there has been some elapsed time since getting current_time
                            start_time = current_time
                            listener_log.add_log("Pump On")

                        shower_state = True

                        pump_on_period = (datetime.datetime.now() - start_time)

                        log_data = 'On Period,{0},accumulated,{1:.1f}'.format(pump_on_period.seconds,
                                                                              accumulated_on_time)
                        listener_log.add_log(log_data)

                        if accumulated_on_time > max_on_time:
                            #if pump_on_period.seconds > max_on_time:
                            sendmail.send("Shower controller",
                                          "Turning pump off. On for accumulated {0:.1f}, Max time {1}".format(
                                              accumulated_on_time, max_on_time))

                            set_pump_state(False)

                            # Tuesday to friday don't turn on until 1800
                            #if 1 <= current_time.weekday() <= 4 and current_time.hour < 17:
                            #    new_on_time = current_time.replace(hour=18, minute=0, second=0)
                            #    next_on_time = new_on_time
                            #else:
                            next_on_time = current_time + timedelta(seconds=no_repeat_period)

                            sendmail.send("Shower controller next on", str(next_on_time))
                            listener_log.add_log("Killing pump")

                    else:  # energy < 30
                        if shower_state:
                            # Was on, now gone to off
                            #time_on = (datetime.datetime.now() - start_time)
                            sendmail.send("Shower off", "Number seconds on: {0:.1f}".format(accumulated_on_time))  # time_on.seconds))
                            listener_log.add_log(
                                "Pump turned off,{0:.1f}".format(accumulated_on_time))  # time_on.seconds))
                            electricity_check_time = current_time + timedelta(minutes=10)
                            do_electricity_check = True

                        shower_state = False
                        break_count += time_since_last_reading

                    #listener_log.add_log('Break {0:.1f},Accumulated {1:.1f}'.format(break_count, accumulated_on_time))
                    #print('Break count ' + str(break_count))
                    #print('Accumulated ' + str(accumulated_on_time))

                    if break_count > reset_period and accumulated_on_time > 0:
                        print('Resetting break count')
                        accumulated_on_time = 0
                        break_count = 0

                        if current_pump_state:
                            #sendmail.send("Shower controller Reset break", "")
                            pass

                else:  # not controlled
                    accumulated_on_time = 0
                    break_count = 0

        except Exception as listener_exception:
            message = "Exception details:\n"
            message += "Last string: " + last_string
            message += "\n"
            message += "Data: "
            message += data
            message += str(type(listener_exception))
            message += str(listener_exception.args)
            message += str(listener_exception)
            message += "\n\n"
            message += str(traceback.print_exc())

            # sendmail.send("Shower control - Exception in listener thread", message)

            f = open ('/home/pi/scripts/shower/logs/exceptions.txt', 'a')
            f.write (str(datetime.datetime.now()) + message + '\n')
            f.close()
Ejemplo n.º 50
0
cmd      = ' '.join(sys.argv[1:])

OUT=open('out.txt', 'w')
ERR=open('err.txt', 'w')
try:
    result = subprocess.call(sys.argv[1:], stdout=OUT, stderr=ERR)
except Exception as ex:
    ERR.write('Python exception when trying to execute:\n%s\n' % cmd)
    ERR.write(str(ex))
    ERR.write('\n')
    result = 1

OUT.close()
ERR.close()

if result != 0:
    sendmail.send(config.DEVS,
                  "Failed to execute '%s' at '%s'" % (cmd, hostname),
                  "See attached files for standard output and standard error",
                  ["out.txt", "err.txt"])
    exit(1)
else:
    sendmail.send(config.DEVS,
                  "Executed '%s' at '%s'" % (cmd, hostname),
                  "Command was successfully executed",
                  ["out.txt", "err.txt"])
    exit(0)