Beispiel #1
0
def once_a_day(sendmail):
    global lval
    global hcode
    global diff

    log.info("main", "once_a_day")

    # -----------------------------calculate diff
    for i in range(20):
        try:
            if float(values[i]) > float(lval[i]):
                diff[i] = "▲"
                hcode[i] = "▲"
            elif float(values[i]) < float(lval[i]):
                diff[i] = "▼"
                hcode[i] = "&#9660;"
            else:
                diff[i] = "●"
                hcode[i] = "&#9679;"
        except Exception:
            diff[i] = "-"
            hcode[i] = "-"
    lval = list(values)
    savelval()

    # -----------------------------send mail
    if sendmail == 1:
        mail.send(gethtmltable(True))
    return
Beispiel #2
0
    def expose_with_timeout(self,
                            exptime=1.0,
                            exptype=1,
                            expmeter=None,
                            timeout=None):
        if timeout == None:
            timeout = exptime + 60.0

        kwargs = {"exptime": exptime, "exptype": exptype, "expmeter": expmeter}
        thread = threading.Thread(target=self.expose, kwargs=kwargs)
        thread.name = 'kiwispec'
        thread.start()
        thread.join(timeout)
        if thread.isAlive():
            mail.send(
                "The SI imager timed out",
                "Dear Benevolent Humans,\n\n" +
                "The SI imager has timed out while exposing. This is usually "
                +
                "due to an improperly aborted exposure, in which case someone "
                +
                "needs to log into KIWISPEC-PC, click ok, and restart main.py\n\n"
                "Love,\n,MINERVA",
                level='serious',
                directory=self.directory)
            self.logger.error("SI imager timed out")
            sys.exit()
            return False
        return True
Beispiel #3
0
def main():
    """
    Runs the system status check and sends alerts to set email.
    :return: None
    """
    def is_reported(entry):
        """
            Receive an alert entry and decide whether a mail needs to be sent.
            :param entry: The alert entry.
            :type entry: Dict
            :return: True if a mail needs to be sent, False otherwise.
            :raises KeyError: In case the dictionary doesn't have the correct keys.
            :raises TypeError: In case the entry is not a dictionary.
            """
        if type(entry) is dict:
            if "reported" in entry and "updated" in entry:
                if entry["reported"] == entry["updated"]:
                    return True
            else:
                raise KeyError(
                    "No 'reported' or 'updated' fields in the dict!")
        else:
            raise TypeError("Entry has to be a dictionary!")
        return False

    # The alerts that will be mailed.
    mail_content = []

    status_report = check_status()

    # Check the status report and decide about which alerts a mail needs to be sent.
    # If the reported time == updated time we will send a mail:
    for key in status_report:
        if key == "resolved":
            # Resolved alerts
            for alert in status_report["resolved"]:
                mail_content.append("{} status is resolved.".format(alert))
        # Since 'processes' is a nested dictionary, we need to iterate over it's content.
        elif key == "processes":
            for process in status_report[key]:
                if is_reported(status_report[key][process]):
                    mail_content.append("Process {} is DOWN.".format(process))
        else:
            if is_reported(status_report[key]):
                mail_content.append(
                    "{} value is above it's threshold: {}.".format(
                        key, status_report[key]["value"]))

    # If there are any alerts to send:
    if mail_content:
        # The alerts, as a readable string.
        mail_body = "\n".join(mail_content)
        # Debug text, which can be written to a log when the script is ran as a cronjob.
        print "DEBUG: Mail content: {}".format(mail_body)
        mail.send('*****@*****.**', config.settings["email"]["address"],
                  mail_body, config.settings["email"]["smtp_server"])

    # Remove the 'resolved' list from the status report before saving.
    status_report.pop("resolved", None)
    save_report(status_report)
Beispiel #4
0
def alarmer():
  now = datetime.datetime.now()
  now_ten = now + datetime.timedelta(minutes = 12)
  alarmData = db['Alarm']
  personData = db['Person']
  avtaleData = db['Avtale']

  for alarm in alarmData:
    notifi = dict(alarm)
    alarmTime = notifi['Tidspunkt']

    aid = notifi['Avtale_AvtaleID']
    pid = notifi['Person_Ansattnummer']
    varsel = notifi['Varselstekst']

    if(now_ten > alarmTime ): #if now + 12minutes is after the alarm time, then send mail
      #Send mail og slett alarm!
      email = dict(personData.find_one(Ansattnummer=pid))['Epost']
      avtale = dict(avtaleData.find_one(AvtaleID=aid))
      tittel = avtale['Tittel']
      start = str(avtale['Starttidspunkt'])

      varsel = "Automatisk alarm for avtale: " + tittel + "\n" + "start: " + start +  "\n\n" + varsel

      send(email, '*****@*****.**', 'Alarm: Avtale', varsel)
      delete(pid,aid)
Beispiel #5
0
def find_house(url, history_list):
    req = gen_req(url)
    r = urllib2.urlopen(req).read()
    soup = BeautifulSoup(r, "html.parser")
    # print soup.prettify()
    trs = soup.find_all('tr', class_='')
    for tr in trs:
        title_a = tr.findChild('a', class_='')
        link = title_a['href']
        text = str(title_a)
        if 'title' in text:
            m = re.search('title=\"((.|\n)*)\"', text)
            if not m:
                continue
            title = m.group(1)
            for target in targets:
                if target.encode('utf8') in title:
                    id_str = re.search('.*topic/(.*)/', link)
                    if id_str:
                        id_int = int(id_str.group(1))
                        if id_int in history_list:
                            break
                        print title
                        print link
                        send(mail_sender, mail_receiver,
                             title.decode('utf8') + '\n' + link)
                        history_list.append(id_int)
                        print '-------------------------------------------------------'
                    else:
                        print link

    return history_list
Beispiel #6
0
    def si_recover(self):
        try:
            self.recover_attempts += 1
        except AttributeError:
            self.recover_attempts = 1

        if self.recover_attempts == 1:
            #S let's just try again? seems dangerous, could try a short exposure or something
            return True

        if self.recover_attempts == 2:
            #S now restart si image
            self.logger.info('si imager failed, attempting recovery ' +
                             str(self.recover_attempts))

            if self.si_image_restart():
                self.logger.info('restarted si image, and continuing')
            else:
                #S should we make a hold here, like a file that needs to be deleted?
                self.logger.exception('failed to restart si image')
                subject = 'Failed to restart SI Image'
                body = "Dear benevolent humans,\n\n"+\
                    "The SI Image software on Kiwispec failed to restart when attempting a recovery. "+\
                    "I need you to restart the software, and investigate why I went into recovery "+\
                    "in the first place.\n\n Love,\n MINERVA"
                mail.send(subject,
                          body,
                          level='serious',
                          directory=self.directory)
                return False
Beispiel #7
0
def send_mail(mails, msg):
    try:
        mail.send(mails, msg)
        logging.info('Report was sent to emails: %r' % (mails,))
    except Exception as e:
        logging.error('Report was NOT sent to emails : %r, error: %r' % (
            mails, str(e)))
Beispiel #8
0
def send_email():
    msg = Message('Hello',
                  sender='*****@*****.**',
                  recipients=['*****@*****.**'])
    msg.body = "This is the email body"
    mail.send(msg)
    return "Sent"
Beispiel #9
0
    def test_send_message(self):
        message = Message.Message()
        message["To"] = "you"
        message["Cc"] = "them"
        message["From"] = "me"
        message["Subject"] = "hello"
        message.set_payload("Hello everybody!")

        smtp_info = {
            'server': 'stmp.foo.com',
            'port': 25,
            'user': '******',
            'password': '******'
        }

        mail.send(from_address="me",
                  to_addresses="you",
                  cc_addresses="them",
                  subject="hello",
                  body="Hello everybody!",
                  smtp_info=smtp_info)

        self.assertEquals("me", test_data.mail_from_address)
        self.assertEquals(["you", "them"], test_data.mail_to_address)
        self.assertEquals(message.as_string(), test_data.mail_message)
def output_results(folder, config_map, debug):
    # Get the SMTP config
    smtp_server = config_map['global']['smtp']['server']
    smtp_tls = config_map['global']['smtp']['tls']
    smtp_port = config_map['global']['smtp']['port']
    smtp_user = config_map['global']['smtp']['user']
    smtp_pass = config_map['global']['smtp']['password']
    smtp_to = config_map['global']['smtp']['to_addr']
    smtp_from = config_map['global']['smtp']['from_addr']
    smtp_cc = config_map['global']['smtp']['cc_addrs']
    email_template_file = config_map['global']['smtp']['template']
    email_subject = config_map['global']['smtp']['subject']
    values = {}
    values['reportGenerationDate'] = datetime.datetime.now().strftime(
        "%Y-%m-%d")
    values['teamCosts'] = str(get_team_totals(config_map, folder, debug))
    template = mail.EmailTemplate(template_name=email_template_file,
                                  values=values)
    server = mail.MailServer(server_name=smtp_server,
                             username=smtp_user,
                             password=smtp_pass,
                             port=smtp_port,
                             require_starttls=smtp_tls)
    msg = mail.MailMessage(from_email=smtp_from,
                           to_emails=[smtp_to],
                           cc_emails=smtp_cc,
                           subject=email_subject,
                           template=template)
    print("Sending email to %s" % smtp_to)
    mail.send(mail_msg=msg, mail_server=server)
def outputResults(folder,configMap,debug):

    # Get the SMTP config
    smtp_server = configMap['global']['smtp']['server']
    smtp_tls = configMap['global']['smtp']['tls']
    smtp_port = configMap['global']['smtp']['port']

    smtp_user = configMap['global']['smtp']['user']
    smtp_pass = configMap['global']['smtp']['password']
    smtp_to = configMap['global']['smtp']['to_addr']
    smtp_from = configMap['global']['smtp']['from_addr']
    smtp_cc = configMap['global']['smtp']['cc_addrs']

    email_template_file = configMap['global']['smtp']['template']
    email_subject = "AWS Team Cost Summary for all teams"

    log("Sending email to %s" % smtp_to)

    values = {}
    values['startDate'] = getStartDate(configMap)
    values['endDate'] = getEndDate(configMap)
    values['reportGenerationDate'] = datetime.datetime.now().strftime("%Y-%m-%d")
    values['teamCosts'] = str(getTeamTotals(configMap,folder,debug))

    template = mail.EmailTemplate(template_name=email_template_file, values=values)
    server = mail.MailServer(server_name=smtp_server, username=smtp_user, password=smtp_pass, port=smtp_port, require_starttls=smtp_tls)

    msg = mail.MailMessage(from_email=smtp_from, to_emails=[smtp_to], cc_emails=smtp_cc,subject=email_subject,template=template)
    mail.send(mail_msg=msg, mail_server=server)
    def run(self):
        if self.ext == ".py":
            # use now running python version, think multiple python installed and now use python3.6 to run
            python_path = sys.executable
            #print("use the absolute path of python to run", python_path)
            print('\n[{}] [Sys]     Started!\n'.format(
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            with open(r'./stat/daliy_total.txt', 'w') as f:
                f.write('0')
            self.p = subprocess.Popen(
                [python_path, '%s' % self.cmd],
                stdin=sys.stdin,
                stdout=sys.stdout,
                stderr=sys.stderr,
                shell=False)
            for i in range(ITER):

                time.sleep(PERIOD * 60)
                with open(r'./stat/daliy_total.txt', 'r') as f:
                    amount = f.readline()
                print(
                    '\n[{}] [Sys]     Running for {} mins --Got {} lotteries\n'
                    .format(
                        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        str((i + 1) * PERIOD), amount))

            with open(r'./stat/log_total.txt', 'a') as f:
                f.write('[{}] Got {} lotteries in total\n'.format(
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    amount))
            self.p.kill()
            time.sleep(3)
            if arg.mail == 1:
                send()
            return 1
Beispiel #13
0
def recover():
    if request.method == 'POST':
        uuid = users.get_uuid(userdb, request.form['email'])
        if uuid is not None:
            newpass = password.generate()
            if users.set_password(userdb, session['uuid'], newpass):
                subject = gettext("SUPERHUB Project :: New Password")
                content = gettext(
                    "The password for the following email address: {email} was reset. You should now be able to log into the journey diary and record your journeys using the password: {newpass}."
                ).format(email=request.form['email'], newpass=newpass)
                mail.send(app.config['email_address'],
                          app.config['email_password'], request.form['email'],
                          subject, content)

                msg = gettext("An email was sent to {arg}").format(
                    arg=request.form['email'])
            else:
                msg = gettext(
                    "We were not able to update the password for this account. Please contact [email protected]"
                )
        else:
            msg = gettext(
                "There is no SUPERHUB account associated with the email address:"
            )
        flash(msg)
        return redirect(url_for('.root'))
    return render_template('recover.html')
Beispiel #14
0
def main():
    #读取用户名,密码
    if len(sys.argv) == 3:
        username = sys.argv[1]
        passwd = sys.argv[2]
    else:
        print "error input parameter: %s" % (len(sys.argv) - 1)
        sys.exit(1)
    print ">>>>>>>>>>>>用户名: %s<<<<<<<<<<<" % username
    print "================LOG================="
    start = datetime.datetime.now()
    startStr = start.strftime('%Y-%m-%d %H:%M:%S')
    print "开始时间: %s" % startStr
    ret = tryBook(username, passwd)
    end = datetime.datetime.now()
    endStr = end.strftime('%Y-%m-%d %H:%M:%S')
    print "结束时间: %s" % endStr
    print "共耗时:%s秒" % (end - start).seconds
    #邮件通知结果
    msg = ''
    if ret:
        msg = "%s,wonderful!book finished!" % username
    else:
        msg = "%s,sorry, book failed!please check your code!" % username
    mail.send(msg)
    print "=================END=================="
def send_mail(recipients, subject, plain, html=None, sender=None):
    if sender is None:
        sender = current_app.config.get('DEFAULT_MAIL_SENDER')

    msg = Message(subject, body=plain, html=html,
                  sender=sender, recipients=recipients)
    mail.send(msg)
Beispiel #16
0
def admin_attendees_mail_all():
    try:
        attendees = db.Person.select()
        form = forms.MailForm()

        if flask.request.method == 'POST':
            if form.validate_on_submit():
                subject = '[%s] %s' % (config.SITE_TITLE, form.subject.data)
                mail.send(
                    [p.email for p in attendees],
                    subject=subject,
                    body=form.body.data,
                )

                flask.flash(
                    u"Sent '%s' to %d attendees" %
                    (subject, attendees.count()), 'info')

            for field, errors in form.errors.items():
                for error in errors:
                    flask.flash(
                        u"Problem with '%s': %s" %
                        (getattr(new_poi, field).label.text, error), 'error')

            return flask.redirect(
                flask.url_for('nerf-herder frontend.admin_attendees'))

    except Exception, e:
        flask.flash(str(e), 'error')
Beispiel #17
0
def send_email(config, errors):

    template = config['ERROR_CONTENT']
    msg = MIMEText(template.format(message=errors), 'plain')
    msg['Subject'] = config['ERROR_SUBJECT']

    send(config, msg, config['ERROR_SEND_TO'])
Beispiel #18
0
    def vent(self):

        ipdb.set_trace()

        timeout = 1200.0

        # close the vent valve
        self.logger.info("Closing the vent valve")
        self.benchpdu.ventvalve.off()

        # close the pump valve
        self.logger.info("Closing the pump valve")
        self.benchpdu.pumpvalve.off()

        # turn off the pump
        self.logger.info("Turning off the pump")
        self.benchpdu.pump.off()

        spec_pressure = self.get_spec_pressure()
        self.logger.info("Spectrograph pressure is " + str(spec_pressure) +
                         " mbar")

        if spec_pressure < 500.0:
            mail.send("The spectrograph is pumped (" + str(spec_pressure) +
                      " mbar and attempting to vent!",
                      "Manual login required to continue",
                      level='Debug',
                      directory=self.directory)
            self.logger.error(
                "The spectrograph is pumped (" + str(spec_pressure) +
                " mbar and attempting to vent; manual login required to continue"
            )
            ipdb.set_trace()
            time.sleep(60)

            # TODO: make hold file to restart thread

    # open the vent valve
        self.logger.info("Opening the vent valve")
        self.benchpdu.ventvalve.on()

        t0 = datetime.datetime.utcnow()
        elapsedtime = 0.0
        spec_pressure = self.get_spec_pressure()
        while spec_pressure < 500.0:
            elapsedtime = (datetime.datetime.utcnow() - t0).total_seconds()
            self.logger.info('Waiting for spectrograph to vent (Pressure = ' + str(self.get_spec_pressure())\
                + ' mbar; elapsed time = '+ str(elapsedtime) + ' seconds)')
            spec_pressure = self.get_spec_pressure()

    # TODO: monitor pressure during venting and create smarter error condition
        if elapsedtime < timeout:
            time.sleep(5)
        else:
            self.logger.error("Error venting the spectrograph")
            return

        self.logger.info("Venting complete; spectrograph pressure is " +
                         str(spec_pressure) + ' mbar')
Beispiel #19
0
def send(content='', title='agileutil_alarm', mail_to='*****@*****.**'):
    try:
        mail.send(from_addr='*****@*****.**',
                  to_addr=mail_to,
                  title=title,
                  content=content)
    except:
        pass
Beispiel #20
0
def test():
    to_addr = '*****@*****.**'
    subject = 'test'
    body = 'test'

    msg = create_message(to_addr, subject, body)
    send(to_addr, msg)
    return "Sent"
Beispiel #21
0
def send_notification(updated, device, who):
    kind = "Update to" if updated else "Addition of"
    body = "See the record at %s/device.py?id=%d\r\n" % (get_base_url(False),
                                                         device.id)
    mail.send("Hardware Operations Team <*****@*****.**>",
              "Hardware Operations Notifier <*****@*****.**>",
              "%s hardware record for %s by %s" % (kind, device.name, who),
              body)
	def pump(self):

		timeout = 1200

		if self.get_spec_pressure() > 500:
			mail.send("The spectrograph is at atmosphere!","Manual login required to continue")
			self.logger.error("The spectrograph is at atmosphere! Manual login required to continue")

			# TODO: make hold file to restart thread
			ipdb.set_trace()

		# close the vent valve
		self.logger.info("Closing the vent valve")
		self.benchpdu.ventvalve.off()

		# close the pump valve
		self.logger.info("Closing the pump valve")
		self.benchpdu.pumpvalve.off()

		# turn on the pump
		self.logger.info("Turning on the pump")
		self.benchpdu.pump.on()

		# wait until the pump gauge reads < 100 ubar
		t0 = datetime.datetime.utcnow()
		elapsedtime = 0.0
		pump_pressure = self.get_pump_pressure()
		while pump_pressure > 0.1:
			elapsedtime = (datetime.datetime.utcnow() - t0).total_seconds()
			self.logger.info('Waiting for tube to pump down (Pressure = ' + str(pump_pressure) + 'mbar ; elapsed time = '+ str(elapsedtime) + ' seconds)')
			if elapsedtime < timeout:
				time.sleep(5)
			else:
				self.logger.error("Error pumping down the spectrograph")
				return
			pump_pressure = self.get_pump_pressure()


		# open the pump valve
		self.benchpdu.pumpvalve.on()
		self.logger.info("Pump gauge at " + str(pump_pressure) + " mbar; pumping down the spectrograph")

		# TODO: wait for pressure to go below some value??    
		t0 = datetime.datetime.utcnow()
		elapsedtime = 0.0
		spec_pressure = self.get_spec_pressure()
		while spec_pressure > 10:
			elapsedtime = (datetime.datetime.utcnow() - t0).total_seconds()
			self.logger.info('Waiting for spectrograph to pump down (Pressure = ' + str(spec_pressure) + ' mbar; elapsed time = '+ str(elapsedtime) + ' seconds)')
			if elapsedtime < timeout:
				time.sleep(5)
			else:
				self.logger.error("Error pumping down the spectrograph")
				return
			spec_pressure = self.get_spec_pressure()

		self.logger.info("Spectrograph at " + str(spec_pressure) + " mbar; done")
Beispiel #23
0
 def send_email(self, subject, text, duration):
     print 'Sending email'
     email_from = self.config['email']['sender']
     email_to = self.config['email']['recipient']
     smtp_host = self.config['email']['smtp_host']
     text += '\nDone in %s' % self.duration_to_hms(duration)
     text += '\n--\nContinuum'
     mail.send(subject=subject, text=text, sender=email_from,
               recipients=[email_to], smtp_host=smtp_host)
Beispiel #24
0
def dealMessage(eventType,event):
    global ignoreList
    path=os.path.join(event.path,event.name)
    for r in ignoreList:
        if(re.search(r,path)):
            return None
    message=u"时间:%s 事件:%s 路径:%s"%(time.strftime("%Y%m%d %H:%M:%S"),eventType,path.decode("UTF-8"))
    log.write(message)
    mail.send(message) 
Beispiel #25
0
def email(name, address, template, params):
    mail.send(
        template["sender_name"],
        template["sender_address"],
        name,
        address,
        template["subject"] % params,
        template["html"] % params,
    )
Beispiel #26
0
def checkout(id):
    if request.method == 'GET':
        product = session.query(Products). \
            filter(Products.id == id).first()
        return render_template("checkout.html", product=product)
    elif request.method == 'POST':
        print(request.form['tel'])
        tel = request.form['tel']
        send(tel=tel, id=id)
        return redirect("https://money.yandex.ru/quickpay/confirm.xml")
Beispiel #27
0
def checkToken():
    msg = ""
    users = getUsers()
    for user in users:
        token = user["token"]
        if (not token or len(token) == 0):
            msg += "用户:{0} token失效,请重新获取;\r\n".format(user["phone"])

    if (len(msg) > 0):
        mail.send('美团申请系统告警', msg)
Beispiel #28
0
def root():
    if request.method == 'POST':
        button = request.form['button']
        if button  == 'join':
            if request.form['password'] == request.form['password_confirmation']:
                if users.get_uuid(userdb, request.form['email']) is not None:
                    
                    msg = (gettext("An account already exists for that email address. Please either use another email address or use the recover password feature."))
                    app.logger.warn("Account already exists for "+str(request.form['email']))
                else:

                    lang = request.accept_languages.best_match(LANGUAGES.keys())

                    uuid = users.add_user(userdb, request.form['email'], request.form['password'], request.form['first_name'], request.form['last_name'], lang)
                
                    subject = gettext("SUPERHUB Project :: New Journey Diary Account")
                    content = gettext("A new SUPERHUB Journey Diary account has been created for the following email address: {kwarg}. You should now be able to log into the journey diary and record your journeys.").format(kwarg=request.form['email'])

                    # Added a toggle for the email confirmation service, as it was causing problems on my server. You can re-enable it in the config.
                    if (app.config['send_mail'] == "True"):
                        mail.send(app.config['email_address'], app.config['email_password'], request.form['email'], subject, content)
                        msg = gettext("An email has been sent to {kwarg} so that you can verify your email address. However you can log into your account immediately.").format(kwarg=request.form['email'])
                    else:
                        msg = gettext("A confirmation email could not be sent at this time. You can still sign in to your account right away")
                        app.logger.warn("Confirmation email was not sent to " +str(request.form['email'])+" as outgoing mail is disabled. See config.")
                    
                    logline = { 'type':'New user reqistration', 'timestamp': str(datetime.now().isoformat()), 'data': {'email': request.form['email'], 'uuid':uuid}, 'payload': None}                    
                    app.logger.info( json.dumps(logline) )
            else:
                msg = gettext("The supplied passwords do not match. Please ensure that you type the same password into both the password box and the confirmation box.")

            flash(msg)
           
        elif button == 'login':
            if check_auth(request.form['email'], request.form['password']):
                session['email'] = request.form['email']
                session['uuid'] = users.get_uuid(userdb, session['email'])
                session['logged_in'] = True
                return redirect(request.args['next'] if 'next' in request.args else url_for('.dashboard'))
            
            msg = gettext("The supplied password was incorrect")
            flash(msg)
            return render_template('index.html')

    try:
        if session['cookie_notified']:
            return render_template('index.html')
    except KeyError:
        alertlist = [
            {
                "msg":gettext('This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.'),
                "type":"cookie_notification",
            }
        ]
        return render_template('index.html', alertlist = alertlist)
Beispiel #29
0
def insert_members_form():
    if(request.method == 'POST'):
        params = request.get_json(force=True)
        print(params)
        name = params['name']
        contact = params['contact']
        email=params['email']
        send(email)
		#return render_template('mail.py')
    else:
        return "Hello World"
Beispiel #30
0
def process_diagnotics(documents: list[dict], api_key: str):
    for doc in documents:
        ref = doc['ref']
        emails = mail_interval.get_email_send_datetime()
        if validity.is_correct(doc):
            continue
        if not validity.is_ready_for_email(ref, emails):
            continue
        if ENVIRONMENT != 'dev':
            mail.send(doc, api_key)
        mail_interval.update(ref)
Beispiel #31
0
def contact():
    form = ContactForm()

    if form.validate() == False:
        flash('All fields are required.')
        return render_template('contact.html', form=form)
    else:
        print(request.form['email'])
        msg = create_message(request.form['email'],
                             "Thank you for your applying", str(request.form))
        send(msg)
        return render_template('success.html')
Beispiel #32
0
    def test_send_message(self):
        message = Message.Message()
        message["To"] = "you"
        message["Cc"] = "them"
        message["From"] = "me"
        message["Subject"] = "hello"
        message.set_payload("Hello everybody!")

        mail.send("me", "you", "them", "hello", "Hello everybody!")
        self.assertEquals("me", test_data.mail_from_address)
        self.assertEquals(["you", "them"], test_data.mail_to_address)
        self.assertEquals(message.as_string(), test_data.mail_message)
Beispiel #33
0
def check_page():
    page = crawl(configuration['targetURL'])  # .decode("utf8")
    page_hash = md5(page)
    c = load()
    if not c['hash'] == page_hash:
        print("HASH CHANGED! (" + page_hash + ")")

        # Run a background thread to archive the page in the web archive
        start_new_thread(crawl, ("https://web.archive.org/save/" +
                                 configuration['targetURL'], False))

        # Check if the file is online and we didn't sent the mail already (if so send it)
        match = parse(page.decode('utf8'))
        if match is not None and not c['mailSent']:
            print(
                "FILE IS ONLINE! Sending mails ... (and we didn't sent them already)"
            )
            docx = crawl(match)
            for person_details in configuration['details']:
                variables = {
                    "name": person_details['name'],
                    "year": person_details['targetYear'],
                    "quarter": person_details['quarter'],
                    "mail": person_details['mail'],
                    "streetAndCity": person_details['streetAndCity'],
                    "phone": person_details['phone'],
                    "matrikelnr": person_details['matrikelnr']
                }
                res = parser.update_document_contents(docx, person_details)
                res_filename = "Antrag Wohnheimzimmer " + variables[
                    'quarter'] + " " + variables['year'] + ".docx"
                mail.send(configuration['mail'], variables, res, res_filename)
            c['mailSent'] = True

        # Send a mail regardless of the above that there is a change
        notification_conf = {
            "body":
            "Something changed! Go and visit " + configuration['targetURL'],
            "subject":
            "IMPORTANT | The watched website has changed! Go check it immediately!",
            "recipient": configuration['mail']['notificationRecipient'],
            "server": configuration['mail']['server']
        }
        if c['mailSent']:
            notification_conf[
                'body'] += "\n\n Oh and btw I already sent your reservation request ;)\n\n Have a good one!\n - AccommodationBot"
        mail.send(notification_conf)

        c['hash'] = page_hash
    else:
        print("Boring old same page...")

    save(c)
def main():
    """Fonction d'entrée du programme."""

    csv_file, jinja_file, send, yes, verbose = _get_parser()

    printv = printif(verbose)
    printn = printif(not yes and verbose)

    printv("Parsing teams ... ", end="")

    teams = team.Teams(csv_file)

    printv(f"Done : {len(teams.teams)} teams found.\n")
    printv("Parsing template ... ", end="")

    content = [
        template.render(jinja_file, {
            "teams": teams,
            "team": t,
            "opp": teams.get_by_id(t.id_opp)
        }) for t in teams.teams
    ]

    printv("Done.\n")

    printn("### First mail :")
    printn(mail.send(send=False, **content[0]))

    if send and not yes:
        send = input("Do you really want to send mails ? [y/N] : ")
        valid = {
            "yes": True,
            "y": True,
            "ye": True,
            "no": False,
            "n": False,
            "": False,
            "oui": True,
            "o": True,
            "non": False
        }
        if send in valid:
            send = valid[send]
        else:
            send = False
    else:
        send = send or yes

    if send:
        for c in content:
            mail.send(send=send, **c)

    return 0
def outputResults(team_name, configMap, plugin_results, debug):

    if debug: pprint.pprint(plugin_results)

    # Get the SMTP config
    smtp_server = configMap['global']['smtp']['server']
    smtp_tls = configMap['global']['smtp']['tls']
    smtp_port = configMap['global']['smtp']['port']

    smtp_user = configMap['global']['smtp']['user']
    smtp_pass = configMap['global']['smtp']['password']
    smtp_from = configMap['global']['smtp']['from_addr']
    smtp_cc = configMap['global']['smtp']['cc_addrs']

    email_template_file = configMap['global']['smtp']['template']
    email_to_addr = getToAddr(team_name, configMap)
    email_subject = "Team %s AWS Cost Report for %s to %s" % (
        team_name, getStartDate(configMap), getEndDate(configMap))

    log("Sending email to %s for team %s" % (email_to_addr, team_name))

    values = {}
    values['teamName'] = team_name
    values['startDate'] = getStartDate(configMap)
    values['endDate'] = getEndDate(configMap)
    values['reportGenerationDate'] = datetime.datetime.now().strftime(
        "%Y-%m-%d")
    values['totalCost'] = "{0:.2f}".format(
        getTotalTeamCost(configMap, plugin_results, debug))
    values['sharedSummaryCosts'] = getSharedSummaryCosts(
        configMap, plugin_results, debug)
    values['taggedCosts'] = getIndividualCosts(configMap, plugin_results,
                                               debug)
    values['sharedDetailCosts'] = getSharedDetailCosts(configMap,
                                                       plugin_results, debug)

    template = mail.EmailTemplate(template_name=email_template_file,
                                  values=values)
    server = mail.MailServer(server_name=smtp_server,
                             username=smtp_user,
                             password=smtp_pass,
                             port=smtp_port,
                             require_starttls=smtp_tls)

    msg = mail.MailMessage(from_email=smtp_from,
                           to_emails=[email_to_addr],
                           cc_emails=smtp_cc,
                           subject=email_subject,
                           template=template)
    mail.send(mail_msg=msg, mail_server=server)

    # Write the output to disk so other scripts can use it if needed
    writeTeamCosts(team_name, configMap, plugin_results, debug)
Beispiel #36
0
def main():
    f = subprocess.Popen(['tail','-F',filename],\
            stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    p = select.poll()
    p.register(f.stdout)

    while True:
        if p.poll(1):
            line = f.stdout.readline()
            if is_ntp_bot(line):
                mail.send(line)
        time.sleep(0.5)
Beispiel #37
0
    def test_send_message(self):
        message = Message.Message()
        message["To"] = "you"
        message["Cc"] = "them"
        message["From"] = "me"
        message["Subject"] = "hello"
        message.set_payload("Hello everybody!")

        mail.send("me", "you", "them", "hello", "Hello everybody!")
        self.assertEquals("me", test_data.mail_from_address)
        self.assertEquals(["you","them"], test_data.mail_to_address)
        self.assertEquals(message.as_string(), test_data.mail_message)
Beispiel #38
0
 def recover(self):
     self.logger.error(
         "Called the recovery but we have no recovery procedure!")
     if self.red: specname = 'MRED'
     else: specname = 'Kiwispec'
     mail.send(
         specname + " spectrograph software crashed",
         "Dear Benevolent humans,\n\n" + "The " + specname +
         " spectrograph software has crashed and I have no recovery procedure for this. Good luck!\n\n"
         + "Love,\nMINERVA",
         level='serious',
         directory=self.directory)
     sys.exit()
Beispiel #39
0
def root():
    if request.method == 'POST':
        button = request.form['button']
        if button  == 'join':
            if request.form['password'] == request.form['password_confirmation']:
                if users.get_uuid(userdb, request.form['email']) is not None:
                    
                    msg = (gettext("An account already exists for that email address. Please either use another email address or use the recover password feature."))
                    app.logger.warn("Account already exists for "+str(request.form['email']))
                else:

                    lang = request.accept_languages.best_match(LANGUAGES.keys())

                    uuid = users.add_user(userdb, request.form['email'], request.form['password'], request.form['first_name'], request.form['last_name'], lang)
                
                    subject = gettext("SUPERHUB Project :: New Journey Diary Account")
                    content = gettext("A new SUPERHUB Journey Diary account has been created for the following email address: {kwarg}. You should now be able to log into the journey diary and record your journeys.").format(kwarg=request.form['email'])

                    mail.send(app.config['email_address'], app.config['email_password'], request.form['email'], subject, content)

                    msg = gettext("An email has been sent to {kwarg} so that you can verify your email address. However you can log into your account immediately.").format(kwarg=request.form['email'])
                    
                    logline = { 'type':'New user reqistration', 'timestamp': str(datetime.now().isoformat()), 'data': {'email': request.form['email'], 'uuid':uuid}, 'payload': None}                    
                    app.logger.info( json.dumps(logline) )
            else:
                msg = gettext("The supplied passwords do not match. Please ensure that you type the same password into both the password box and the confirmation box.")

            flash(msg)
           
        elif button == 'login':
            if check_auth(request.form['email'], request.form['password']):
                session['email'] = request.form['email']
                session['uuid'] = users.get_uuid(userdb, session['email'])
                session['logged_in'] = True
                return redirect(request.args['next'] if 'next' in request.args else url_for('.dashboard'))
            
            msg = gettext("The supplied password was incorrect")
            flash(msg)
            return render_template('index.html')

    try:
        if session['cookie_notified']:
            return render_template('index.html')
    except KeyError:
        alertlist = [
            {
                "msg":gettext('This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.'),
                "type":"cookie_notification",
            }
        ]
        return render_template('index.html', alertlist = alertlist)
Beispiel #40
0
def send_mail():
  d = request.query.decode()
  print(d['to'])
  print(d['subject'])
  print(d['msg'])
  send_to = d['to'].replace('[space]', ' ')
  send_from = '*****@*****.**'
  send_subject = d['subject'].replace('[space]', ' ')
  send_msg = d['msg'].replace('[space]', ' ')
  try:
    send(send_to, send_from, send_subject, send_msg)
    return respond(200, 'Mail sent', None)
  except:
    traceback.print_exc()
    return respond(134, 'Error: mail not sent', None)
Beispiel #41
0
def send_smtp(msg, params):
    """
    Send a message using smtp

    Parameters:
        msg     - text message
        params  - to: destination address
    
    Returns:
        True
    """
    import mail
    mail.send(serverURL=settings.SMTP['server'], 
        sender=settings.SMTP['sender'],
        to=params['to'],
        subject=settings.SMTP['subject'],
        text=msg)
    return True
Beispiel #42
0
def recover():
    if request.method == 'POST':
        uuid = users.get_uuid(userdb, request.form['email'])
        if uuid is not None:
            newpass = password.generate()
            if users.set_password(userdb, session['uuid'], newpass):
                subject = gettext("SUPERHUB Project :: New Password")
                content = gettext("The password for the following email address: {email} was reset. You should now be able to log into the journey diary and record your journeys using the password: {newpass}.").format(email=request.form['email'], newpass=newpass)
                mail.send(app.config['email_address'], app.config['email_password'], request.form['email'], subject, content)

                msg = gettext("An email was sent to {arg}").format(arg=request.form['email'])
            else:
                msg = gettext("We were not able to update the password for this account. Please contact [email protected]")
        else:
                msg = gettext("There is no SUPERHUB account associated with the email address:")     
        flash(msg)
        return redirect(url_for('.root'))
    return render_template('recover.html')
Beispiel #43
0
 def reg(self, i):
   email = i.email
   password = hashlib.md5(i.password).hexdigest()
   authen_key = hashlib.md5(email + str(random.randint(0, 100))).hexdigest()[:8]
   db_xpmanager.insert('user', 
     email = email,
     password = password
     authen_key = authen_key)
   msg = '''
   <html>
     <body>
     <p>
     Hi %s,
     </p>
     <p>
         Welcome use <strong><i>XP Manager</i></strong>, your authen key is <storng><i>%s</i></strong>
     </p>
   ''' % (email.split('@')[0], authen_key)
   mail.send('*****@*****.**', email, '[xpmanager] user active', msg)
    def test_send_message(self):
        message = Message.Message()
        message["To"] = "you"
        message["Cc"] = "them"
        message["From"] = "me"
        message["Subject"] = "hello"
        message.set_payload("Hello everybody!")

        smtp_info = {'server': 'stmp.foo.com',
                     'port': 25,
                     'user': '******',
                     'password': '******'}

        mail.send(from_address="me", to_addresses="you", cc_addresses="them",
                  subject="hello", body="Hello everybody!", smtp_info=smtp_info)

        self.assertEquals("me", test_data.mail_from_address)
        self.assertEquals(["you", "them"], test_data.mail_to_address)
        self.assertEquals(message.as_string(), test_data.mail_message)
Beispiel #45
0
def send_mail():
    if request.method == "POST":
        to_email_address = request.form['email']
        category = request.form['template']
        severity = request.form['severity']
        from_email_address = '*****@*****.**' # switch out to official email
        # update here to switch templates
        selected_template = which_MailContent_obj(category, severity)
        subject = selected_template.subject
        content = selected_template.content
        result = mail.send(to_email_address, from_email_address, subject, content)
        print str(result)
        return to_email_address
def outputResults(team_name,configMap,plugin_results,debug):

    if debug: pprint.pprint(plugin_results)

    # Get the SMTP config
    smtp_server = configMap['global']['smtp']['server']
    smtp_tls = configMap['global']['smtp']['tls']
    smtp_port = configMap['global']['smtp']['port']

    smtp_user = configMap['global']['smtp']['user']
    smtp_pass = configMap['global']['smtp']['password']
    smtp_from = configMap['global']['smtp']['from_addr']
    smtp_cc = configMap['global']['smtp']['cc_addrs']

    email_template_file = configMap['global']['smtp']['template']
    email_to_addr = getToAddr(team_name,configMap)
    email_subject = "Team %s AWS Cost Report for %s to %s" % (team_name,getStartDate(configMap),getEndDate(configMap))

    log("Sending email to %s for team %s" % (email_to_addr,team_name))

    values = {}
    values['teamName'] = team_name
    values['startDate'] = getStartDate(configMap)
    values['endDate'] = getEndDate(configMap)
    values['reportGenerationDate'] = datetime.datetime.now().strftime("%Y-%m-%d")
    values['totalCost'] = "{0:.2f}".format(getTotalTeamCost(configMap,plugin_results,debug))
    values['sharedSummaryCosts'] = getSharedSummaryCosts(configMap,plugin_results,debug)
    values['taggedCosts'] = getIndividualCosts(configMap,plugin_results,debug)
    values['sharedDetailCosts'] = getSharedDetailCosts(configMap,plugin_results,debug)

    template = mail.EmailTemplate(template_name=email_template_file, values=values)
    server = mail.MailServer(server_name=smtp_server, username=smtp_user, password=smtp_pass, port=smtp_port, require_starttls=smtp_tls)

    msg = mail.MailMessage(from_email=smtp_from, to_emails=[email_to_addr], cc_emails=smtp_cc,subject=email_subject,template=template)
    mail.send(mail_msg=msg, mail_server=server)

    # Write the output to disk so other scripts can use it if needed
    writeTeamCosts(team_name,configMap,plugin_results,debug)
Beispiel #47
0
def signup():
    form = UserForm(request.form)

    if not form.validate_on_submit():
        return render_template('signup.html', form=form)

    user = User()
    form.populate_obj(user)
    passwd = form.password.data # un-encrypted

    if not Whitelist.allowed(user.email):
        flash(u"Desværre - du skal have en email fra et godkendt uddannelsessted", 'error')
        return render_template('signup.html', form=form)

    token = ValidationTokens(user=user,
                             type=ValidationTokens.CREATE_USER,
                             password=passwd)

    db.session.add(user)
    db.session.add(token)

    db.session.commit()

    link = '%s?token=%s' % (url_for(verify.__name__, _external=True), token.token)
    msg = render_template('email_verification.txt', user=user, link=link)

    mail.send(receivers=[u'%s <%s>' % (user.username, user.email)],
              subject=u'Bekræft din email adresse til Iftek-skyen',
              text=msg)

    flash(u"""Fedt, du er blevet oprettet!<br /><br />
For at aktivere din konto, skal du bekræfte din email adresse.<br /><br />
Vi har sendt en email med et link<br /><br />
Ses snart i skyen!""")

    return redirect(url_for(flash_message.__name__))
Beispiel #48
0
	def report(self, event):
		dial = wx.MessageDialog(self, 'Email report will be sent to [email protected].',
				'Confirm', wx.OK | wx.CANCEL | wx.ICON_QUESTION)
		result = dial.ShowModal()
		dial.Destroy()
		if result == wx.ID_OK:
			global logFile
			result = mail.send('*****@*****.**', logFile)
			if result == 13:
				dial = wx.MessageDialog(None, 'Report file does not exist!',
					'Error', wx.OK | wx.ICON_ERROR)
				dial.ShowModal()
				dial.Destroy()
			if result == 0:
				#dial = wx.MessageDialog(None, 'Report sent.',
				#	'Information', wx.OK | wx.ICON_INFORMATION)
				#dial.ShowModal()
				#dial.Destroy()
				self.notice("Report was sent successfully.")
		self.showSearch()
Beispiel #49
0
        high1.grid(row=2,column=3,columnspan=1)
        last.grid(row=3,column=0,columnspan=2,ipady=20)
        last1.grid(row=3,column=2,columnspan=2)
root.update()
while True :
    time.sleep(10)
    info=fetch.info_fetch()
    balance=info['balance']/100000000
    balausd=float(balance*info['last'])
    balausd=round(balausd,2)
    v1.set(info['last'])
    v2.set(info['low'])
    v3.set(info['high'])
    v4.set(balance)
    v5.set(balausd)
    time_elapsed=time.clock()-start
    if(time_elapsed>7200.0):
        start=time.clock()
        mail.send()
    root.update()
        
mainloop()        






    

Beispiel #50
0
def send_mail(to, subject, text=None, html=None):
    mail.send(to, subject, text=None, html=None)
Beispiel #51
0
 def _send_mail(self, mail):
     self.notebook.remove_page(self.notebook.page_num(mail.widget))
     mail.send()
	filename = config.path+item[0]+'.'+dt+'.sql.gz'	

	if config.attach & find(item[0], config.attach_databases):
		email_attach.append(filename)


	if item[0] != 'mysql' and item[0] != 'information_schema' and item[0] != 'performance_schema' : 
	
		timestamp = datetime()
		print 'Iniciando o backup de '+item[0]+' em '+timestamp 	
		
		os.system('mysqldump --add-drop-database -u'+config.mysql_user+' -p'+config.mysql_password+' --database '+item[0]+' | gzip > '+filename)

		size = os.path.getsize(filename) # tamanho do arquivo
		size = size/1024*1024		 # tamanho em MB
		timestamp = datetime() 
		
		mensagem = 'Backup '+filename+' finalizado em '+timestamp+'. Tamanho do arquivo: '+str(size)+' MB' 

		print mensagem

		email_mensagem += mensagem+ "\n"

# Send email to inform
if config.use_mail:
	mail.send(email_mensagem, email_attach)

if config.use_rsync:
	print 'Iniciando sincronização via Rsync'
	os.system('rsync -avz --progress '+config.path+' '+config.remote_user+'@'+config.remote_host+':'+config.remote_path)
Beispiel #53
0
	def mail(self,login):
		if mail.send(self.uname,self.passwd,self.email,login):
			return 1
		return 0
Beispiel #54
0
def process_cmd(nick, msg):    
    """Splits the message, processes the
    commands and does all the relevant
    functions required.
    
    Should reverse the 'rank' if 
    statements but it's not much of
    a problem.
    """
    cmd = msg.split(" ")
    rank = v.getrank(nick)
    if len(cmd) == 1:
        log("*" + cmd[0].capitalize() + "* | nick: " + nick, m_type="COMMAND", colour=Fore.CYAN)
        #ACTION_LOG.info(Fore.MAGENTA + "COMMAND " + Fore.RESET + " " + cmd[0] + " | nick: " + nick)
    else:
        log("*" + cmd[0].capitalize() + "* | args: " + " ".join(cmd[1:]) + " | nick: " + nick, m_type="COMMAND", colour=Fore.CYAN)
        #ACTION_LOG.info(Fore.MAGENTA + "COMMAND " + Fore.RESET + " " + cmd[0] + " | args: " + " ".join(cmd[1:]) + " | nick: " + nick)
    
    try:
        # regular user
        # rank = 1
        if rank >= 1:
            #! emotes !#
            if cmd[0] == "fliptable": c.say("(╯°□°)╯︵ ┻━┻")
            elif cmd[0] == "puttableback": c.say("┬─┬ ノ( ゜-゜ノ)")
            elif cmd[0] == "ohyou": c.say("¯_(ツ)_/¯")
            elif cmd[0] == "FLIPTABLE": c.say("(ノಠ益ಠ)ノ彡┻━┻")
            elif cmd[0] == "fff": c.say("ლ(ಠ益ಠლ)")
            elif cmd[0] == "disapprove": c.say("ಠ_ಠ")
            elif cmd[0] == "crie": c.say("ಥ_ಥ")
            elif cmd[0] == "lenny": c.say("( ͡° ͜ʖ ͡°)")
            elif cmd[0] == "dongers": c.say("ヽ༼ຈل͜ຈ༽ノ")
            elif cmd[0] == "raise": c.say("ヽ༼ຈل͜ຈ༽ノ")
            elif cmd[0] == "butterfly": c.say("Ƹ̵̡Ӝ̵̨̄Ʒ")
            elif cmd[0] == "partytime": c.say("┏(-_-)┛┗(-_- )┓┗(-_-)┛┏(-_-)┓")
            elif cmd[0] == "fliptables": c.say("┻━┻︵ \(°□°)/ ︵ ┻━┻")
            elif cmd[0] == "polarbear": c.say("ˁ˚ᴥ˚ˀ")
            elif cmd[0] == "gun": c.say("︻╦╤─")
            elif cmd[0] == "pirate": c.say("✌(◕‿-)✌")
            elif cmd[0] == "happybirthday": c.say("¸¸♬·¯·♩¸¸♪·¯·♫¸¸Happy Birthday To You¸¸♬·¯·♩¸¸♪·¯·♫¸¸")
            elif cmd[0] == "sunglasses": c.say("( •_•) ( •_•)>⌐■-■ (⌐■_■)")
            elif cmd[0] == "rage": c.say("t(ಠ益ಠt)")
            elif cmd[0] == "cards": c.say("[♥]]] [♦]]] [♣]]] [♠]]]")
            elif cmd[0] == "gimme": c.say("༼ つ ◕_◕ ༽つ")
            elif cmd[0] == "monocle": c.say("ಠ_ರೃ")
            elif cmd[0] == "ghost": c.say("‹’’›(Ͼ˳Ͽ)‹’’›")
            elif cmd[0] == "why": c.say("ლ(`◉◞౪◟◉‵ლ)")
            elif cmd[0] == "praise": c.say("し(*・∀・)/♡\(・∀・*)ノ")
            elif cmd[0] == "lennyy": c.say(" ̿̿ ̿̿ ̿̿ ̿'̿'\̵͇̿̿\з=( ͡° ͜ʖ ͡°)=ε/̵͇̿̿/’̿’̿ ̿ ̿̿ ̿̿ ̿̿ ")
            # tears can be potentially dangerous, limited to admin +
            elif cmd[0] == "tears" and rank >= 3: c.say(" Ỏ̷͖͈̞̩͎̻̫̫̜͉̠̫͕̭̭̫̫̹̗̹͈̼̠̖͍͚̥͈̮̼͕̠̤̯̻̥̬̗̼̳̤̳̬̪̹͚̞̼̠͕̼̠̦͚̫͔̯̹͉͉̘͎͕̼̣̝͙̱̟̹̩̟̳̦̭͉̮̖̭̣̣̞̙̗̜̺̭̻̥͚͙̝̦̲̱͉͖͉̰̦͎̫̣̼͎͍̠̮͓̹̹͉̤̰̗̙͕͇͔̱͕̭͈̳̗̭͔̘̖̺̮̜̠͖̘͓̳͕̟̠̱̫̤͓͔̘̰̲͙͍͇̙͎̣̼̗̖͙̯͉̠̟͈͍͕̪͓̝̩̦̖̹̼̠̘̮͚̟͉̺̜͍͓̯̳̱̻͕̣̳͉̻̭̭̱͍̪̩̭̺͕̺̼̥̪͖̦̟͎̻̰_á»")
            
            #! other !#
            elif cmd[0] == "rps":
                target = cmd[1]
                global rps
                rps = games.RockPaperScissors(nick, target)
                c.msg(nick + " has challenged you to a game of rock, paper scissors.", target)
                c.msg("To participate, use " + f.BLUE + "/msg Oracle ?[rock/paper/scissors] (use /imsg if you're in-game)", target)
                c.msg("You have 30 seconds.", target)
                c.msg("You have challenged " + target + " to a game of rock, paper scissors.", nick)
                c.msg("To participate, use " + f.BLUE + "/msg Oracle ?[rock/paper/scissors] (use /imsg if you're in-game)", nick)
                c.msg("You have 30 seconds.", nick)
                
            
            elif cmd[0] == "rock" or cmd[0] == "paper" or cmd[0] == "scissors":
                if rps != None:
                    if rps.guess(cmd[0], nick):
                        c.msg("Decision accepted", nick)
                        c.msg("Your opponent has made a decision", rps.get_opponent(nick))
                    else:
                        c.msg("You're not in this RPS game!", nick)
                else:
                    c.msg("There is no RPS game at the moment.", nick)
                    
            elif cmd[0] == "a":
                global trivia
                trivia.guess(cmd[1:], nick)
            
            elif cmd[0] == "help" or cmd[0] == "what":
                if(len(cmd) < 2): help_(nick, "no")
                else: help_(nick, cmd[1])
                
            elif cmd[0] == "cb": cb(cmd[1:], nick)
            
            elif cmd[0] == "pick":
                c.say(nick + ": " + misc.pick(cmd[1:]))
                
            elif cmd[0] == "diamonds":
                if config.get('rick-roll'):
                    gags.rick_roll(nick, cmd[1])
                else:
                    c.msg(f.WHITE + "64 diamonds have been credited to the Minecraft account " + f.RED + nick + f.WHITE + ".", nick)
                    time.sleep(5)
                    c.msg("Just kidding.", nick)
                    c.msg("This command has been disabled in the config.", nick)
                    
            elif cmd[0] == "ayylmao":
                c.say("http://puu.sh/6wo5D.png")
                
            elif cmd[0] == "score":
                if cmd[1] == "check":
                    if len(cmd) > 2 and rank >= 3:
                        c.msg(cmd[2] + " has " + str(score.get(cmd[2])) + " points.", nick)
                    else:
                        c.msg("Your have " + str(score.get(nick)) + " points.", nick)
                elif cmd[1] == "top":                        
                    list = score.get_leader_boards()
                    amount = int(cmd[2]) if len(cmd) > 2 else 5
                    i = 1
                    for line in list:
                        c.msg(str(i) + ". " + line[0] + " - " + str(line[1]), nick)
                        i += 1
                        if i > amount:
                            break
                            
            elif cmd[0] == "resolve":
                data = socket.gethostbyname_ex(" ".join(cmd[1:]))
                c.say(" ".join(cmd[1:]) + " resolved to " + repr(data[2]))
                
            #! server !#
            elif cmd[0] == "events":
                results = e.get()
                
                if results:
                    c.say(f.BOLD + "Event: " + results[0] + " || " + f.BOLD + "Time" + f.BOLD + ": " + results[1] + " UTC")
                else:
                    c.say(f.BOLD + "No events found" + f.BOLD + " - there may be none planned.")
                    
            elif cmd[0] == "utc":
                c.say(e.utc() + " UTC")
                
            elif cmd[0] == "nether":
                c.msg(misc.netherposition(int(cmd[1]), int(cmd[2]), int(cmd[3])), nick)
                
            elif cmd[0] == "overworld":
                c.msg(misc.overworldposition(int(cmd[1]), int(cmd[2]), int(cmd[3])), nick)
      
            #! personal !#
            elif cmd[0] == "mail":
                try:
                    if cmd[1].lower() == "check":
                        if not m.check(nick):
                            c.msg("You have no mail.", nick)
                        else:
                            c.msg("Use ?mail read [mail]: "+ ", ".join(m.check(nick)), nick)
                            
                    elif cmd[1].lower() == "send":
                        text = " ".join(cmd[4:])
                        if m.send(nick, cmd[2], cmd[3], text):
                            c.msg("Message sent.", nick)
                        else:
                            c.msg("Message failed to send.", nick)
                            
                    elif cmd[1].lower() == "read":
                        c.msg(m.read(nick, cmd[2]), nick)
                        
                    elif cmd[1].lower() == "delete" or cmd[1].lower() == "del":
                        if m.delete(nick, cmd[2]):
                            c.msg("Message deleted.", nick)
                        else:
                            c.msg("Message not deleted.", nick)
                            
                    else:
                        c.msg("Usage: ?mail [check|send|read|delete]", nick)
                        
                except:
                    traceback.print_exc()
                    c.msg("Usage: ?mail [check|send|read|delete]", nick)
                    
            elif cmd[0] == "notes":
                try:
                    if cmd[1].lower() == "new":
                        text = " ".join(cmd[3:])
                        if n.new(cmd[2], text):
                            c.msg("Note successfully created.", nick)
                        else:
                            c.msg("Note already exists with that file name", nick)
                            
                    elif cmd[1].lower() == "delete":
                        if n.delete(cmd[2]):
                            c.msg("Note successfully deleted.", nick)
                        else:
                            c.msg("Deletion failed", nick)
                            
                    elif cmd[1].lower() == "edit":
                        text = " ".join(cmd[3:])
                        n.edit(cmd[2], text[1])
                        
                    elif cmd[1].lower() == "listall":
                        c.msg(" ".join(n.listall()), nick)
                        
                    elif cmd[1].lower() == "search" or cmd[1].lower() == "list":
                        c.msg(" ".join(n.find(cmd[2])), nick)
                        
                    elif cmd[1].lower() == "get":
                        c.msg(nick + ": " + n.get(cmd[2]), nick)
                        
                    else:
                        c.msg("Usage: ?notes [new|delete|edit|listall|search|get]", nick)
                except:
                    traceback.print_exc()
                    c.msg("Usage: ?notes [new|delete|edit|listall|search|get]", nick)
                    
            elif cmd[0] == "eval":
                try:
                    sm = " ".join(cmd[1:])
                    c.say(sm + " = " + str(eval(sm)))
                except:
                    traceback.print_exc()
        else:
            c.msg("Seems like you don't have access to these commands. Message an admin for help.", nick)
            
        #! moderator !#
        # rank = 2
        if rank >= 2:
            if cmd[0] == "say":
                c.say(format.replace(" ".join(cmd[1:])))
            
            elif cmd[0] == "ATTENTION":
                global ATTENTION
                ATTENTION = True
                c.getusers()
                
            elif cmd[0] == "ban" :
                v.setvar(nick, cmd[1], "rank", 0)
                c.msg("User: "******" has been banned.", nick)
                
            elif cmd[0] == "kick":
                if len(cmd) < 3:
                    c.kick(cmd[1], "")
                    c.msg("User kicked.", nick)
                else:
                    c.kick(cmd[1], " ".join(cmd[2:]))
                    c.msg("User kicked for " + " ".join(cmd[2:]) + ".", nick)
        
        #! admin !#
        # rank = 3
        if rank >= 3:
            if cmd[0] == "close":
                c.stop(nick)
                EXIT = True
                
            elif cmd[0] == "restart" :
                c.restart(nick)
                
            elif cmd[0] == "reload":
                log("Reload issued by " + nick, m_type="RELOAD", colour=Fore.YELLOW, reset=False)
                reload_()
                c.say(f.YELLOW + "Reload complete.")
                
            elif cmd[0] == "sreload":
                reload_()
                c.msg(f.YELLOW + "Silent reload complete.", nick)
                
            elif cmd[0] == "setrank":
                v.setvar(cmd[1], "rank", int(cmd[2]))
                c.msg(cmd[1] + "'s rank set to " + cmd[2] + ".", nick)
                
            elif cmd[0] == "mode":
                c.mode(cmd[1:])
                
            elif cmd[0] == "getrank":
                c.msg(cmd[1] + "'s rank is " + str(v.getvar(cmd[1], "rank")) + ".", nick)
                
            elif cmd[0] == "flood":
                if cmd[1] == "reset":
                    spam.clear()
                    c.msg("Cleared FLOOD dictionary", nick)
                elif cmd[1] == "decrement":
                    spam.decrement()
                    c.msg("FLOOD decrement performed", nick)
                    
            elif cmd[0] == "randompoints":
                if cmd[1] == "run":
                    randompoints.poll_users()
                    time.sleep(1)
                    randompoints.reward()
                
            elif cmd[0] == "trivia":
                if cmd[1] == "new":
                    c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] New round started by " + f.BLUE + nick)
                    trivia._runnable()
                elif cmd[1] == "off":
                    trivia.disable()
                    c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] Disabled by " + f.BLUE + nick)
                elif cmd[1] == "on":
                    if trivia._getdisabled():  
                        del trivia
                        trivia = games.trivia()
                        c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] Re-enabled by " + f.BLUE + nick)
                elif cmd[1] == "info":
                    c.msg(trivia.getinfo(), nick)
                    
            elif cmd[0] == "score":
                if cmd[1] == "reset":
                    if score.reset(cmd[2]):
                        c.msg("Successfully reset " + cmd[2] + "'s score.", nick)
                    else:
                        c.msg("Reset failed.", nick)
                elif cmd[1] == "add":
                    points = score.add(cmd[2], cmd[3])
                    if not points:
                        c.msg("Points failed to add.", nick)
                    else:
                        c.msg("Sucessfully added points, " + cmd[2] + " now has " + str(points) + " points.", nick)
                        
            elif cmd[0] == "ignore":
                try:
                    IGNORE_LIST.append(cmd[1])
                    c.msg("Successfuly added " + cmd[1] + " to ignore list.", nick)
                except:
                    c.msg("Ignore unsuccessful.", nick)
                
            elif cmd[0] == "pardon":
                try:
                    del ingore_list[cmd[1]]
                    c.msg("Successfully pardoned " + cmd[1] + ".", nick)
                except:
                    c.msg("Pardon unsuccessful. Perhaps " + cmd[1] + " is not currently being ignored.", nick)
                        
        #! developer !#
        # rank = 4
        if rank >= 4:
            if cmd[0] == "makevar":
                target = cmd[1]
                
                if(v.makevarfile(target)):
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - New var file created for " + target + " by " + nick)
                    c.msg("VAR file successfully created for " + target, nick)
                else:
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - Var file creation failed - " + nick)
                    c.msg("VAR file failed to create for " + target, nick)
                    
            elif cmd[0] == "getvar":
                response = v.getvar( cmd[1], cmd[2])
                c.msg("VAR: %s = %s" % (cmd[2], response),nick)
                    
            elif cmd[0] == "listvar":
                response = v.listvar(cmd[1])
                c.msg(response, nick)
                
            elif cmd[0] == "setvar":
                if(v.setvar(cmd[1], cmd[2], int(cmd[3]))):
                    c.msg("VAR: %s set to %s for %s" % (cmd[2], cmd[3], cmd[1]), nick)
                else:
                    c.msg("Setting of variable failed.", nick)
                    
            elif cmd[0] == "deletevar":
                if(v.deletevarfile(cmd[1])):
                    c.msg("VAR file successfully deleted.", nick)
                else:
                    c.msg("VAR file deletion failed.", nick)
                
            elif cmd[0] == "resetvar":
                target = cmd[1]
                
                if(v.deletevarfile(target)):
                    c.msg("VAR file successfully deleted.", nick)
                else:
                    c.msg("VAR file deletion failed.")
                    
                if(v.makevarfile(target)):
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - New var file created for " + target + " by " + nick)
                    c.msg("VAR file successfully created for " + target, nick)
                else:
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - Var file creation failed - " + nick)
                    c.msg("VAR file failed to create for " + target, nick)
                    
            elif cmd[0] == "formats" :
                c.say(vars(f))
                    
            elif cmd[0] == "cls":
                os.system("cls")
                
            elif cmd[0] == "join":
                join(nick)
                
            elif cmd[0] == "joinn":
                join(cmd[1])
                
            elif cmd[0] == "raw":
                c.raw(cmd[1:])
                
            elif cmd[0] == "config":
                if cmd[1] == "reload":
                    try:
                        config.reload()
                        c.msg("Config reloaded.", nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error reloading config", nick)
                elif cmd[1] == "set":
                    try:
                        config.set(cmd[2], cmd[3:])
                        c.msg("Config set.", nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error setting config", nick)
                elif cmd[1] == "get":
                    try:
                        c.msg(config.get(cmd[2]), nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error getting config", nick)
                        
            elif cmd[0] == "testlog":
                log("No string test")
                log("Action test", l_type='action', m_type="TESTLOG", colour=Fore.GREEN)
                if len(cmd) > 1:
                    log(' '.join(cmd[1:]), colour=Fore.GREEN, m_type="TESTLOG")
                    
            elif cmd[0] == "exec":
                try:
                    exec " ".join(cmd[1:])
                except:
                    c.say(traceback.print_exc())
                        
    except SystemExit:
        return
        
    except:
        # any and every error will throw this
        traceback.print_exc()
        c.msg("Oops! Something went wrong. Please contact an admin for help.",nick)
message_count = queue.method.message_count

# Connect to MySQL
dbh = MySQLdb.connect(
	config.get('mysql', 'host'),
	config.get('mysql', 'user'),
	config.get('mysql', 'pass'),
	config.get('mysql', 'db'))
cur = dbh.cursor(MySQLdb.cursors.DictCursor)

if message_count == 0:
	cur.execute("SELECT * FROM proxy")
	rows = cur.fetchall()
	for row in rows:
		channel.basic_publish(
				exchange='',
				routing_key=queue_name,
				body=json.dumps(row),
				properties=pika.BasicProperties(
					delivery_mode=2))
		print " [x] Sent %s:%s@%s:%s" % (row['username'], row['password'], row['host'], row['port'])
else:
	msg = " [!] There is %s jobs left in queue" % message_count
	print msg
	mail.send('*****@*****.**', '[Checker][Fail] Create check proxy jobs', msg)

# Close connections
rabbit.close()
dbh.close()

Beispiel #56
0
        logging.error(ex.message)
        return

    posturl = "http://www.hncsjj.gov.cn/cstv2/weixinclwfcx/wxclwfcx.action"
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko", "Referer": "http://www.hncsjj.gov.cn/cstv2/weixin/oauth.action?code=00106ce9715f0ff135ef5f5ff6dcb0dY&state=ajcstweixin"}
    carnumber = str(cpd) + str(hm)
    data = {"carwfcxbean.carType": zl, "carwfcxbean.carNumber": carnumber, "carwfcxbean.fdjh": fdj}
    try:
        p = s.post(posturl, data=data, headers=headers, timeout=10)
    except Exception,ex:
        logging.error(ex.message)
        return
    content = p.content
    result = re.search(r"\bform0\b", content)
    if result:
        soup = BeautifulSoup(content)
        plist = soup.find_all("p")
        body = ""
        for p in plist:
            body += str(p)
        body = "".join(body.split(" "))
        body = body.replace(r'<p style="width: 100%;height: 20px;"></p>', '')
        body = body.replace(r'</p><p align="right">', ',')
        body = body.replace(r'累计扣分', ',累计扣分')
        body = body.replace(r'<span style="color:#4299C7;font-size: 20px">', ',<span style="color:red">')
        body = body.replace(r'</span>20', '</span>,20')
        print body.encode('gbk')
        mail.send(toemail, str(cpd) + str(hm) + '违章查询结果', body)
    else:
        return
Beispiel #57
0
import os
import urllib2

from datetime import date
from datetime import datetime

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

import paas
from models import Job
from models import db
import mail

today = date.today()
now = datetime.now()

jobs = Job.query\
    .filter(Job.hour <= now.hour)\
    .filter((Job.last_run < today ) | (Job.last_run == None))\
    .all()

for j in jobs:
    try:
        j.last_run = now
        db.session.add(j)
        urllib2.urlopen(j.url).read()
    except Exception, e:
        mail.send(receivers=[j.user.email], subject=u'Fejl ved kørsel af job', text=str(e))

db.session.commit()
Beispiel #58
0
def reset_password():
    try:
        del session['username']
    except KeyError:
        pass

    g.user = None

    token = request.args.get('token')
    now = datetime.datetime.now()

    if token:
        try:
            token = ValidationTokens.query.filter_by(token=token).one()
        except sqlalchemy.orm.exc.NoResultFound:
            flash(u"Beklager, kunne ikke nulstille kodeordet. Linket kan kun bruges en gang", 'error')
            return redirect(request.script_root, 302)

        if token.created + PASSWORD_RECOVERY_VALIDITY < now:
            flash(u"Beklager, linket er udløbet.", 'error')
            return redirect(request.script_root, 302)

        form = VerifiedResetForm(request.form)
        if form.validate_on_submit():
            password = form.password.data
            token.user.password = password

            db.session.add(token.user)
            db.session.delete(token)
            db.session.commit()

            token.user.set_password(password)

            session['username'] = token.user.email
            flash('Dit kodeord er blevet opdateret!')
            return redirect('/', 303)
        else:
            return render_template('reset-password.html', form=form)

    form = RequestResetForm(request.form)
    if form.validate_on_submit():
        email = form.email.data
        user = User.query.filter_by(email=email).one()

        try:
            token = ValidationTokens(user=user,
                                     type=ValidationTokens.CREATE_USER)
            db.session.add(token)
            db.session.commit()
        except:
            db.session.delete(token)
            db.session.commit()
            raise

        link = (url_for('reset_password', _external=True) +
                '?token=' + token.token)

        msg = render_template('reset-password.txt', user=user, link=link)

        mail.send(receivers=[u'%s <%s>' % (user.username, user.email)],
                  subject='Nyt kodeord',
                  text=msg)

        flash(u"Vi har sendt en besked til din email! Klik på linket i beskeden for at nulstille dit kodeord")

        return redirect('/')
    else:
        return render_template('reset-password.html', form=form)