Exemple #1
0
 def post(self):
     claims = get_jwt_claims()
     user_id = claims['id']
     parser = reqparse.RequestParser()
     parser.add_argument('nama_toko', location='json', required=True)
     parser.add_argument('deskripsi', location='json', required=True)
     args = parser.parse_args()
     # GET USER_ID AND USER FULLNAME FROM USER
     user = User.query.get(user_id)
     if user.designer_status == False:
         user.designer_status = True
         db.session.add(user)
         toko = Toko(user.id, args['nama_toko'], args['deskripsi'],
                     user.username)
         db.session.add(toko)
         db.session.commit()
         # SEND EMAIL VIA GMAIL API
         signature = gmail.get_signature()
         message = register_html.message.format(user.full_name) + signature
         subject = "YOUR STORE : {} IS OFFICIALLY OPEN! (TEESIGNR)".format(
             args['nama_toko'])
         gmail.send_email("TEESIGNR", user.email, subject, message)
         return {
             "status": "register berhasil",
             "toko": marshal(toko, Toko.response_fields)
         }, 200, {
             'Content-type': 'application/json'
         }
     else:
         return {
             "status": "register gagal",
             "message": "kamu sudah punya toko"
         }, 400
Exemple #2
0
def job():
    print("Exporting New Relic dashboard...")
    dashboard = exporter(
        guid=config["dashboard"]["guid"],
        file_type=config["dashboard"]["file_type"],
        width=int(config["dashboard"]["width"]),
        height=int(config["dashboard"]["height"]),
    )

    print("Authenticating with Google...")
    service = get_service()

    for email in config["email"]["to"]:
        print("Creating message...")
        message = create_message_with_attachment(
            sender=config["email"]["sender"],
            to=email,
            subject=config["email"]["subject"],
            message_text=config["email"]["text"],
            file=dashboard,
        )

        print("Sending email...")
        send_email(message=message, user_id="me", session=service)

    print("Done!")
def email_dates(dates):
    dates_text = '\n'.join(d.strftime('%H:%M, %d %B %Y') for d in dates)
    url = 'https://driverpracticaltest.direct.gov.uk'
    text = str.format('The following dates have been found:\n\n{}\n\nTest site URL: {}', dates_text, url)

    address = load_options()['email']

    send_email(address, address, 'Practical test dates', text)
Exemple #4
0
def email_dates(dates):
    dates_text = '\n'.join(d.strftime('%H:%M, %d %B %Y') for d in dates)
    url = 'https://driverpracticaltest.direct.gov.uk'
    text = str.format(
        'The following dates have been found:\n\n{}\n\nTest site URL: {}',
        dates_text, url)

    address = load_options()['email']

    send_email(address, address, 'Practical test dates', text)
def calculate_cost(team, to_email):
    cd = boto3.client(
        'ce',
        aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY[team],
        aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY[team],
        region_name='us-east-1')

    results = []

    token = None
    while True:
        if token:
            kwargs = {'NextPageToken': token}
        else:
            kwargs = {}
        data = cd.get_cost_and_usage(TimePeriod={
            'Start': start,
            'End': end
        },
                                     Granularity='DAILY',
                                     Metrics=['UnblendedCost'],
                                     GroupBy=[{
                                         'Type': 'DIMENSION',
                                         'Key': 'LINKED_ACCOUNT'
                                     }, {
                                         'Type': 'DIMENSION',
                                         'Key': 'SERVICE'
                                     }],
                                     **kwargs)
        results += data['ResultsByTime']
        token = data.get('NextPageToken')
        if not token:
            break

    print('\t'.join([
        'TimePeriod', 'LinkedAccount', 'Service', 'Amount', 'Unit', 'Estimated'
    ]))

    total_cost = 0
    for result_by_time in results:
        for group in result_by_time['Groups']:
            amount = group['Metrics']['UnblendedCost']['Amount']
            total_cost += float(amount)
            unit = group['Metrics']['UnblendedCost']['Unit']
            print(result_by_time['TimePeriod']['Start'], '\t',
                  '\t'.join(group['Keys']), '\t', amount, '\t', unit, '\t',
                  result_by_time['Estimated'])

    rounded_total_cost = round(total_cost, 2)
    print('Total Cost ' + str(rounded_total_cost))

    gmail.send_email(team, to_email, start, args.end, rounded_total_cost)
Exemple #6
0
def remove_world_readable_buckets(event, context):
    """removes AllUsers or AllAuthenticatedUsers permissions from Google Cloud Buckets"""
    alert = False
    world_bucket_total = []

    # open tempfile
    findings = TemporaryFile()
    opener = 'Hello, \n\nBelow are Google Cloud Storage World-Readable Permission Issues:\n\n'
    findings.write(bytes(opener, 'UTF-8'))

    logging.info('-----Checking for world-readable bucket permissions-----')
    for project_name in get_projects():
        storage_client = storage.Client(project=project_name)
        buckets = storage_client.list_buckets()

        try:
            for bucket in buckets:
                policy = bucket.get_iam_policy()
                for role in policy:
                    members = policy[role]

                    for member in members:
                        if member == 'allUsers' or member == 'allAuthenticatedUsers':
                            alert = True
                            if bucket.name not in world_bucket_total:
                                world_bucket_total.append(bucket.name)
                            logging.warning(
                                '"{0}" permissions were removed from Bucket "{1}" in project "{2}"'
                                .format(member, bucket.name, project_name))
                            data = '"{0}" permissions were removed from Bucket "{1}" in project "{2}"' \
                                   '\n'.format(member, bucket.name, project_name)
                            findings.write(bytes(data, 'UTF-8'))

                            policy = bucket.get_iam_policy()
                            policy[role].discard(member)
                            bucket.set_iam_policy(policy)

        except Exception as err:
            logging.error(err)

    if alert is False:
        logging.info('No world-readable Bucket permissions found')

    else:
        # write tempfile to email body and delete
        findings.seek(0)
        email_body = findings.read().decode()
        send_email(email_body)
        print(email_body)
        findings.close()
Exemple #7
0
def remove_default_service_accounts(event, context):
    """removes Default Service Accounts from Google Cloud Platform"""
    alert = False

    # open tempfile
    findings = TemporaryFile()
    opener = 'Hello, \n\nBelow are Google Cloud Platform Default Service Accounts that were removed:\n\n'
    findings.write(bytes(opener, 'UTF-8'))

    logging.info('-----Checking for Default User Accounts-----')
    for project in get_projects():
        project_name = 'projects/' + project
        try:
            service = discovery.build('iam', 'v1', cache_discovery=False)
            request = service.projects().serviceAccounts().list(name=project_name)
            response = request.execute()
            accounts = response['accounts']

            for account in accounts:
                serviceaccount = account['email']

                if 'gserviceaccount.com' in serviceaccount and 'iam' not in serviceaccount:
                    alert = True
                    service_account = project_name + '/serviceAccounts/' + serviceaccount
                    delete_request = service.projects().serviceAccounts().delete(name=service_account)
                    delete_request.execute()
                    logging.warning('Default Service Account "{0}" deleted from project "{1}"'.
                                    format(serviceaccount, project))
                    data = '{0} removed from {1}\n\n'.format(serviceaccount, project)
                    findings.write(bytes(data, 'UTF-8'))
        except KeyError:
            logging.info('No Service Accounts found in project "{0}"'.format(project))

        except Exception as err:
            logging.error(err)

    if alert is False:
        logging.info('No Default Service Accounts found')

    else:
        # write tempfile to email body and delete
        findings.seek(0)
        email_body = findings.read().decode()
        send_email(email_body)
        findings.close()
Exemple #8
0
def update_usercase(case_id, user_id):
    """Checks for user in database and adds if new - returns new usercase obj"""

    # check if the usercase exists already
    case_user_check = validate_usercase(case_id, user_id)

    # if the relationship doesn't exist - create it
    if case_user_check is None:
        #create an association in the usercases table
        user_case = UserCase(case_id=case_id, user_id=user_id)
        user = User.query.get(user_id)
        send_email(user.email, None, "add_to_case")
        db.session.add(user_case)
        db.session.commit()

    # return case_user_check so we can determine if the association is new or not
    # if case_user_check is None - we can use that in the add-users route
    return case_user_check
Exemple #9
0
def index():
    user = None
    if request.method == 'POST':
        user = get_or_create_user(empresa=request.form['empresa'], email=request.form['email'])
        if user:
            src_root = os.path.abspath(os.path.dirname(__file__))
            file_path = os.path.abspath("%s/static/img/exemplo-fichaponto.jpg" % src_root)
            body = """
            <p>
                Mande o seu primeiro email para [email protected] falando em cada linha:<br>
                a área de tarefa - descrição única da tarefa - quantidade de horas gastas.
            </p>
            <p>
                Veja um exemplo em anexo do usuário guilherme.bruzzi da empresa ejcm (domínio ejcm.com.br).
            </p>
            """
            send_email(to=[user.email], subject="Bem vindo ao Ficha Ponto", body=body, file_path=file_path)

    return render_template("index.html", user=user)
Exemple #10
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('email', location='json', required=True)
     args = parser.parse_args()
     user = User.query.filter_by(email=args['email']).first()
     if user is not None:
         random_pass = lupa_pass.randomStringDigits(6)
         hashed_pass = hashlib.md5(random_pass.encode()).hexdigest()
         user.password = hashed_pass
         db.session.add(user)
         db.session.commit()
         signature = gmail.get_signature()
         message = lupa_pass.message.format(
             user.full_name, random_pass) + signature
         subject = "IMPORTANT! RESET PASSWORD FOR TEESIGNR"
         gmail.send_email("*****@*****.**",
                          args["email"], subject, message)
         return {"status": "Password baru sudah terkirim ke email"}, 200, {'Content-Type': 'application/json'}
     else:
         return {"status": "Gagal", "message": "E-mail tidak terdaftar"}, 401
Exemple #11
0
    def OnEventConnect(self, nErrCode):
        """
        통신 연결 상태 변경시 이벤트

        :param nErrCode: 에러 코드 - 0이면 로그인 성공, 음수면 실패, 에러코드 참조
        """
        print("OnEventConnect received")
        
        if nErrCode == 0:
            print("로그인 성공")
            # 계좌번호 저장
            self.account = self.get_login_info("ACCNO")
            log.info("계좌번호 : " + self.account)
            
            # 다이나믹 종목 정보 요청
            #self.get_dynamic_subject_info()
            self.get_dynamic_subject_code()

            # 초기 데이터 요청
            #self.request_min_info('CLH17', dbsubject.info['CLH17']['시간단위'], "")
            #self.request_min_info('GCG17', dbsubject.info['GCG17']['시간단위'], "")
            
            # 종목 정보 로그 찍기
            #log.info("참여 종목 : %s" % dbsubject.info.values())


        else:
            c_time = "%02d%02d" % (time.localtime().tm_hour, time.localtime().tm_min)

            # 로그인 실패 로그 표시 및 에러코드별 에러내용 발송
            err_msg = "에러코드별 메시지"
            log.critical(err_msg)

            if int(c_time) >= 800 or int(c_time) < 700:
                # 메일 발송
                gmail.send_email('[긴급' + str(c_time) + '] 해동이 작동 중지', '에러코드')

                # 자동이 재시작 로직 작성
                pass

            self.quit()
Exemple #12
0
def send_result(meseum, url, dates, hrefs):
    content = '%s\r\n%s\r\n%s' % (meseum, url, ', '.join(dates))
    
    # me == the sender's email address
    # you == the recipient's email address
    me = '*****@*****.**'
    you = '*****@*****.**'
    
    for herf in hrefs:
        href = 'http://www.libraryinsight.net/' + herf
        
        if buy_ticket(href):
            subject = '%s is revserved now' % meseum
            send_email(subject, me, [you], content)
            return True
        else:
            subject = '%s is not revserved but available now' % meseum
            send_email(subject, me, [you], content)
            return True
    
    return False
Exemple #13
0
def get_user_by_email(email):
    """Creates new user and returns new or exisiting user object"""

    #check if a user with that email exists already
    #gets the user object for that email address
    user_check = db.session.query(User).filter(User.email == email).first()

    # if user already exists associate the user with the new case
    if user_check is None:
        #if the user is not registered - add them to the database
        #they can add their password and name when they officially register
        # make all emails lowercase to reduce doubled entries
        user_check = User(email=email.lower())
        # send email to notify user they have been added
        send_email(email, None, "new_user")
        #prime user to be added to db
        db.session.add(user_check)
        #commit user to db
        db.session.commit()

    return user_check
Exemple #14
0
    def post(self):
        policy = PasswordPolicy.from_names(
            length=6
        )

        parser = reqparse.RequestParser()
        parser.add_argument('full_name', location='json', required=True)
        parser.add_argument('email', location='json', required=True)
        parser.add_argument('username', location='json', required=True)
        parser.add_argument('password', location='json', required=True)
        args = parser.parse_args()

        validation = policy.test(args['password'])
        check_email = User.query.filter_by(email=args['email']).first()
        check_username = User.query.filter_by(
            username=args['username']).first()
        if check_email is not None:
            return {"status": "register gagal", "message": "email sudah terdaftar"}, 400, {"Content-type": "application/json"}
        if check_username is not None:
            return {"status": "register gagal", "message": "username sudah terpakai"}, 400, {"Content-type": "application/json"}
        if validation == []:
            hashed_pass = hashlib.md5(args['password'].encode()).hexdigest()
            user = User(args['full_name'], args['email'],
                        args['username'], hashed_pass)
            db.session.add(user)
            db.session.commit()
            app.logger.debug('DEBUG : %s', user)
            # Send Email using gmail API
            signature = gmail.get_signature()
            message = register_html.message.format(
                args['full_name']) + signature
            subject = "WELCOME {}, TO TEESIGNR!".format(args['full_name'])
            gmail.send_email("*****@*****.**",
                             args["email"], subject, message)
            return {"status": "register berhasil", "user": marshal(user, User.response_fields)}, 200, {'Content-type': 'application/json'}
        else:
            return {"status": "register gagal", "message": "password tidak valid"}, 400, {"Content-type": "application/json"}
Exemple #15
0
def reset_password(login_credentials):
    print("Entering forgot_password..")
    # Declare the output dictionary
    reset_password_response = declare_reset_response_dictionary(
        login_credentials)
    # Declare the output dictionary
    entityKind = utilities.get_value_by_entityKind_and_key(
        env['config_entityKind'], "datastore_kind_users")['config_value']
    reset_password_response['is_valid_login_response'] = isValidLogin(
        "reset_password", entityKind, login_credentials['username'].lower(),
        login_credentials['forgot_password_answer'])
    # Check if the user got authenticate from isValidLogin
    if not reset_password_response['is_valid_login_response']['userDetails']:
        reset_password_response['result'] = False
        reset_password_response[
            'message'] = "Invlid response from isValidLogin."
        return reset_password_response

    # Get the email attributes from Config
    email_attributes = utilities.get_value_by_entityKind_and_key(
        env['config_entityKind'], "email_attributes")['config_value']
    # Send the email with the password in clear text
    emailTo = reset_password_response['is_valid_login_response'][
        'userDetails']['email']
    emailCC = email_attributes['admin_email_id']
    emailSubject = email_attributes['password_reset_email_subject']
    decrypted_password = utilities.decrypt_password(
        reset_password_response['is_valid_login_response']['userDetails']
        ['password'])['decrypted_password']
    emailBody = "{}\n\n\n{}".format(
        email_attributes['password_reset_email_body'], decrypted_password)
    email = gmail.send_email(emailTo, emailCC, emailSubject, emailBody)
    if not email['result']:
        reset_password_response['result'] = False
        reset_password_response['message'] = email['message']
        return reset_password_response

    # Take the password and forgot password question/answer off from the response
    reset_password_response['is_valid_login_response']['userDetails'][
        'password'] = None
    reset_password_response['is_valid_login_response']['userDetails'][
        'forgot_password_answer'] = None
    return reset_password_response
Exemple #16
0
def send_reminders(due_reminders, email, password):
    for reminder in due_reminders:
        send_email(email, password, reminder.address, reminder.message,
                   "Your email reminder has arrived!")
Exemple #17
0
def download_all_files(clips, vid_name, user, vid_type, curr_time, stitch=False):
    """Download selected clips and save as a zip"""

    # get data
    user_email = user.email
    user_id = user.user_id

    # get date of zip
    date_zipped = curr_time

    # if we are stitching clips together make a list to hold them
    if stitch is True:
        stitch_clips = []

    # get a url to use in the email without the static prefix
    zip_url = "zips/{}/{}_{}.zip".format(user_id, vid_name, date_zipped)

    # make sure a folder exists for where we will save the zip
    zip_dest = "static/zips/{}/".format(user_id)
    # if it doesn't exist, make the folder
    if not os.path.exists(zip_dest):
        os.makedirs(zip_dest)

    # make zip with either all individual clips or one stitched clip
    with zipfile.ZipFile("static/"+zip_url, 'w') as clipzip:
        for clip in clips:
            if vid_type == "clip":
                # our query returns a tuple (clip_name, clip_id)
                file_name = clip.clip_name
            elif vid_type == "video":
                file_name = clip.vid_name

            # make a save location for the downloaded clips in the temp folder
            save_loc = 'static/temp/'+file_name

            print "\n\n\n\n\n\n\n", file_name, save_loc, "\n\n\n\n\n\n\n"
            # if we don't have it stored in temp, download it
            if not os.path.exists(save_loc):
                # connect to aws
                s3 = boto3.resource('s3')
                s3.meta.client.download_file(BUCKET_NAME, file_name, save_loc)

            # if we aren't stitching add the individual file to the zip
            if stitch is False:
                clipzip.write(save_loc, vid_name+"/"+file_name)
            else:
                # otherwise add the videofiles to a clip list
                clip_vf = VideoFileClip(save_loc)
                stitch_clips.append(clip_vf)

        # if we are stitching create composite clip
        if stitch is True:
            # concat videos
            stitched_clip = concatenate_videoclips(stitch_clips)

            # make full path with filename
            stitched_url = 'static/temp/'+vid_name+'_compilation.mp4'

            # save the stitched video
            stitched_clip.write_videofile(stitched_url)

            # add the stitched video to the zip
            clipzip.write(stitched_url, vid_name+"/"+vid_name+'_compilation.mp4')

    # get the url for the email
    email_url = url_for('static', filename=zip_url)

    # send email to user that their zip is ready
    send_email(user_email, email_url, 'file_notice')
    log.init(os.path.dirname(os.path.abspath(__file__).replace('\\', '/')))
    res.init(os.path.dirname(os.path.abspath(__file__).replace('\\', '/')))

    d.mode = 0

    if len(sys.argv) == 1:
        print('실제투자(1), 테스트(2), DB Insert(3)')
        d.mode = int(input())

    else:
        d.mode = int(sys.argv[1])

    # cmd.init()
    if d.get_mode() == 1:

        try:
            kw = kiwoom.api()
        except Exception as err:
            body = str(err) + '\n'
            body = body + str(sys.exc_info()[0])
            gmail.send_email("[긴급] 해동이 작동중지.", body)

    elif d.get_mode() == 2:
        tester.init()

    elif d.get_mode() == 3:
        kw = dbinsert.api()

    else:
        print('잘못된 입력입니다.')
Exemple #19
0
    def post(self):
        # Seharusnya mengambil value seperti total harga dari respond checkout keranjang (patch) dan beli barang
        claims = get_jwt_claims()
        user_id = claims['id']
        parser = reqparse.RequestParser()
        parser.add_argument('nama_penerima', location='json', required=True)
        parser.add_argument('no_telepon', location='json', required=True)
        parser.add_argument('alamat_penerima', location='json', required=True)
        parser.add_argument('metode_pembayaran',
                            location='json', required=True)
        args = parser.parse_args()
        detail_pemesanan = DetailPemesanan(
            user_id, args['nama_penerima'], args['no_telepon'], args['alamat_penerima'], args['metode_pembayaran'])
        db.session.add(detail_pemesanan)
        db.session.commit()
        marshal_detail_pemesanan = marshal(
            detail_pemesanan, DetailPemesanan.response_fields)
        # Bikin Properti untuk Riwayat Pemesanan
        # keranjang_id, barang_id, nama_barang, harga_barang, user_id, jumlah, ukuran,
        # id_pemesanan, total_harga, total_harga_int
        # Ambil semua data keranjang dengan checkout_status = True
        daftar_belanjaan = []
        list_keranjang = Keranjang.query.filter_by(user_id=user_id)
        total_belanja = 0
        for keranjang in list_keranjang:
            if keranjang.checkout_status == True:
                barang_id = keranjang.barang_id
                nama_barang = keranjang.nama_barang
                harga_barang = keranjang.harga_barang
                user_id = user_id
                jumlah = keranjang.jumlah
                ukuran = keranjang.ukuran
                id_pemesanan = detail_pemesanan.id
                total_harga = "Rp. {}".format(
                    keranjang.jumlah * keranjang.harga_barang_int)
                total_harga_int = keranjang.jumlah * keranjang.harga_barang_int
                pemesanan = RiwayatPemesanan(barang_id, nama_barang, harga_barang,
                                             user_id, jumlah, ukuran, id_pemesanan, total_harga, total_harga_int)
                # Menambah jumlah barang terjual di masing masing barang
                barang = Barang.query.get(barang_id)
                barang.terjual = barang.terjual + jumlah
                # Menambah popularitas senilai 5 di toko
                toko_id = barang.toko_id
                toko = Toko.query.get(toko_id)
                toko.popularitas = toko.popularitas + 5
                # Menambah keuntungan di toko
                untung = (keranjang.harga_barang_int -
                          harga_bahan[barang.bahan])*jumlah
                toko.keuntungan = toko.keuntungan + untung
                db.session.add(barang)
                db.session.add(toko)
                db.session.add(pemesanan)
                db.session.delete(keranjang)
                db.session.commit()
                total_belanja += total_harga_int
                pemesanan_marshal = marshal(
                    pemesanan, RiwayatPemesanan.response_fields)
                daftar_belanjaan.append(pemesanan_marshal)
                # Email si penjual / designer bahwa jualannya laku
                designer = User.query.get(toko.user_id)
                nama_designer = designer.full_name
                email_designer = designer.email
                signature = gmail.get_signature()
                message = bought_html.message.format(
                    nama_designer, nama_barang) + signature
                subject = "GREAT NEWS FROM TEESIGNR"
                gmail.send_email("*****@*****.**",
                                 email_designer, subject, message)
        # Email si pembeli detail pemesanan
        pesanan_id = detail_pemesanan.id
        user = User.query.get(user_id)
        full_name = user.full_name
        total_harga_belanja = "Rp. {}".format(total_belanja)
        metode_pembayaran = args['metode_pembayaran']
        nama_penerima = args['nama_penerima']
        nomor_telepon = args['no_telepon']
        alamat_penerima = args['alamat_penerima']
        email_user = user.email
        signature = gmail.get_signature()
        message = konfirmasi_html.PesananEmail(full_name, pesanan_id, total_harga_belanja, metode_pembayaran,
                                               nama_penerima, nomor_telepon, alamat_penerima, daftar_belanjaan) + signature
        subject = "ORDER INFORMATION (TEESIGNR)"
        gmail.send_email("*****@*****.**", email_user, subject, message)

        marshal_detail_pemesanan["total_belanja"] = "Rp. {}".format(
            total_belanja)
        marshal_detail_pemesanan["daftar_belanja"] = daftar_belanjaan
        return {"status": "checkout berhasil", "detail": marshal_detail_pemesanan}, 200, {'Content-type': 'application/json'}
            prediction = get_prediction(net, image)
            class_ids = list(prediction['class_ids'])
            class_ids.sort()
            print('class_ids:', class_ids)
            if len(prediction['indices']) > 0:
                if detectable_classes & set(class_ids):
                    draw_all_predictions(image, prediction)
                    str_class_ids = ','.join(map(str, class_ids))
                    str_date = datetime.datetime.now().strftime(
                        '%y-%m-%d_%H-%M-%S')
                    filename = '{}_{:05d}_[{}].jpg'.format(
                        str_date, count, str_class_ids)
                    save_image(filename, image)
                    if time.time() - timepoint >= min_interval_mail_sending:
                        print("!send a mail")
                        send_email()
                        timepoint = time.time()

                        #print("wait 120 sec")
                        #time.sleep(120)

        if prediction:
            draw_all_predictions(image, prediction)

        cv2.imshow('video', image)

        if count % 30 == 0:
            print_all_predictions(prediction)

    cv2.destroyAllWindows()
Exemple #21
0
 def save_user_and_send_email_confirmation(self, login, password, name,
                                           email, access):
     rnd_str = random_string()
     if send_email(email, rnd_str):
         self.users.save_user(login, hash(password), name, email, access,
                              rnd_str)
Exemple #22
0
    #
    # Generate current stats and write to file
    #

    current = [month,day,hour]
    num = 0
    for stat in jstats['indexSize']:
        currentSize = float(stat['currentSize'].replace('gb',''))
        hour_delta = currentSize - float(last_hour[num*3 + 3])
        day_delta = currentSize - float(day_start[num*3 + 3])
        current += [stat['currentSize'].replace('gb',''), hour_delta, day_delta]
        num += 1
    with open(filename, 'a') as file:
        for field in current[:-1]:
            file.write(f'{field},')
        file.write(f'{current[-1]}\n')

    #
    # Send email at the end of the day
    #

if hour == 0:
    filename = []
    for vmanage in vmanages:
        filename += [f'statsdb.{vmanage}.csv']
    message = create_email(from_user, recipient, alert_title, 'Home Depot daily StatsDB file', filename)
    if 'gmail.com' in from_user:
        send_gmail(from_user, from_password, recipient, message)
    else:
        send_email(from_user, recipient, message, mail_server, mail_port)
if __name__ == "__main__":
    test_data = False
    #test_data = True
    if test_data:
        raw_html = open('test.html', 'r').read()
    else:
        url = settings.URL
        raw_html = simple_get(url)
        open('test.html', 'w').write(raw_html)

    bikes_old = load_bikes()
    bikes_now = parseSearch(raw_html, settings.MAX_COUNT)

    new_arrivals = []
    for bike in bikes_now:
        if bike not in bikes_old:
            new_arrivals.append(bike)

    if new_arrivals:
        print(f'Got {len(new_arrivals)} bikes')
        send_email(new_arrivals)

        for bike in new_arrivals:
            send_whatsapp(str(bike))

    else:
        print('No new bikes')

    save_bikes(bikes_now)
Exemple #24
0
def send_email(address_to, subject, message, attachment):
    gmail.send_email(address_to, subject, message, attachment)
#--------------------------------------------------------------------------------------------
# Part 1

driver = webdriver.Chrome()
driver.get('https://docs.google.com/forms/d/e/1FAIpQLSek4lvyKCkjeKHJwRRSUdsNb4WCIohFNlog7YjeWVzmEr3DQQ/viewform')

time.sleep(2)

last_name = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input')
last_name.send_keys('Kattimani')

first_name = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input')
first_name.send_keys('Rishab')

RadioButtonPeriod = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[3]/div/div/div[2]/div[1]/div/span/div/div[2]/label/div/div[1]/div/div[3]/div')
RadioButtonPeriod.click()

Submit = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div/div/span')
Submit.click()

#-----------------------------------------------------------------------------------------------
# Part 2

driver.get('https://www.youtube.com/channel/UC6OrQk8WsnCOR1OezlUU9zQ')

get_confirmation_div_text = driver.find_element_by_xpath('//*[@id="subscriber-count"]')
print(get_confirmation_div_text.text)


gmail.send_email('YOUR_EMAIL', get_confirmation_div_text.text)
 def upload_summary(self, cid, lectures=None):
     #only sumbit the last summary
     max_lecture = self.get_max_lecture_num(cid)
     
     lectures_json = fio.LoadDictJson('../data/CourseMirror/lectures.json')
     
     if lectures:
         sheets = lectures
         
     if lectures==None:
         sheets = range(0, max_lecture)
         
     for i in sheets:
         lecture = i + 1
         
         path = "../data/" + str(cid) + '/mead/ClusterARank/' + str(lecture)+ '/'
         if not fio.IsExistPath(path): continue
         
         dict = {}
         for q in self.get_questions(cid):
             filename = path + q + '.summary'
             if not fio.IsExist(filename): continue
             
             lines = fio.ReadFile(filename)
             if len(lines) == 0: continue
             
             summary = []
             weight = []
             
             for line in lines:
                 summary.append(line.decode('latin-1').strip())
                 
             summarydict = {}
             summarydict['summaryText'] = summary
             
             sourcefile = path + q + '.summary.source'
             if not fio.IsExist(sourcefile):
                 for s in summary:
                     weight.append(1.0)
             else:
                 sources = [line.strip().split(",") for line in fio.ReadFile(sourcefile)]
                 
                 assert(len(sources) == len(summary))
                 summarydict['Sources'] = sources
                 
                 for source in sources:
                     weight.append(len(source))
                 
             summarydict['weight'] = weight
             
             dict[TypeMap[q]] = summarydict
         
         #get the object
         try:
             summary_Object = Summarization.Query.get(cid=cid, lecture_number = lecture, method='ClusterARank')
         except parse_rest.query.QueryResourceDoesNotExist:
             summary_Object = Summarization(cid=cid, lecture_number = lecture, method='ClusterARank')
         
         for key in dict:
             print key
             summary_Object.__dict__[key] = json.dumps(dict[key])
         
         #update the object
         summary_Object.save()
         
         if lecture != max_lecture: continue
         
         try:
             email_to = config.get('email', 'to')
             
             email_tos = [email_address.strip() for email_address in email_to.split(',')]
             
             lecture_date = self.getDate(lectures_json, cid, lecture)
             
             subject = 'Automatic Summary for Lecture ' + lecture_date
             
             content = []
             for key in dict:
                 content.append(TypeMapReverse[key])
                 for i, (text, weight) in enumerate(zip(dict[key]['summaryText'], dict[key]['weight'])):
                     summary = "%d) %s [%d]" % (i+1, text, weight)
                     content.append(summary)
                 content.append('\n')
             
             content = '\n'.join(content)
             print subject, self.email_from, email_tos, content
             
             gmail.send_email(subject, self.email_from, email_tos, content)
             
         except Exception as e:
             print e
             continue
Exemple #27
0
# Add net new issues to an e-mail message
#
currentissueset = set({})
issue_count = 0
mail_body = ' new global issue(s) detected on DNA Center\n\n'
outfile = open('issueset.txt', 'w')
for issue in jissues['response']:
    currentissueset.add(issue[key])
    if issue[key] not in oldissueset:
        issue_count += 1
        mail_body += json.dumps(issue, indent=4).replace('"', '') + '\n'
    outfile.write(f"{issue[key]}\n")
outfile.close()
mail_body = str(issue_count) + mail_body

#
# calculate net new issues and send e-mail if new issues exist
#
newissues = currentissueset - oldissueset

if newissues == set({}):
    print('No new issues')
else:
    print('New Issues: ', newissues)
    if 'gmail.com' in from_user:
        send_gmail(gmail_user, gmail_password, recipient, 'THD DNAC Alert',
                   mail_body)
    else:
        send_email(from_user, from_password, recipient, 'THD DNAC Alert',
                   mail_body, mail_server, mail_port)
Exemple #28
0
    def __init__(self):
        self.window = Tk()
        self.window.title("대중교통 경로 정보")

        Label(self.window, text='출발지').grid(row=0, column=0)
        Label(self.window, text='목적지').grid(row=1, column=0)

        # 출발지 목적지 좌표 정보
        self.departure = StringVar()
        self.destination = StringVar()
        self.start_x, self.start_y, self.end_x, self.end_y = [], [], [], []
        # 검색 리스트박스에서 선택한 장소의 인덱스 값을 가져오기 위한 변수
        self.selected_index = 0
        self.category = DEPARTURE

        # 출발지 및 목적지 검색 버튼
        self.departure_entry = Entry(self.window,
                                     textvariable=self.departure,
                                     width=30)
        self.departure_entry.grid(row=0, column=1)
        self.destination_entry = Entry(self.window,
                                       textvariable=self.destination,
                                       width=30)
        self.destination_entry.grid(row=1, column=1)
        self.departure_button = Button(
            self.window,
            text='검색',
            padx=12,
            command=lambda: self.search(DEPARTURE, self.departure_entry.get()))
        self.departure_button.grid(row=0, column=2)
        self.destination_button = Button(
            self.window,
            text='검색',
            padx=12,
            command=lambda: self.search(DESTINATION,
                                        self.destination_entry.get()))
        self.destination_button.grid(row=1, column=2)

        # 검색 결과 리스트박스와 스크롤바
        self.search_result_scroll = Scrollbar(self.window)
        self.search_result_scroll.grid(row=3, column=2, sticky='w' + 'n' + 's')
        self.search_result_list = Listbox(
            self.window,
            yscrollcommand=self.search_result_scroll.set,
            width=30,
            height=15)

        self.search_result_list.grid(row=3, column=1)
        self.search_result_scroll['command'] = self.search_result_list.yview
        Button(self.window,
               text='확인',
               command=lambda: self.set_location(
                   self.category, self.search_result_list)).grid(row=4,
                                                                 column=1,
                                                                 sticky='w',
                                                                 ipadx=30)

        Button(self.window,
               text='지도 보기',
               command=lambda: self.show_location_map(
                   self.category, self.search_result_list)).grid(row=4,
                                                                 column=1,
                                                                 sticky='e',
                                                                 ipadx=20)

        # 사이에 빈 공간 만들기
        Label(self.window).grid(row=2, padx=20)
        Label(self.window).grid(column=3, padx=20)
        Label(self.window).grid(row=7)

        # 환승 경로에 관한 변수
        self.fname, self.fx, self.fy, self.tname, self.tx, self.ty, self.route, self.minutes = [], [], [], [], [], [], [], []
        # 경로 선택 라디오 버튼
        self.selected_radio_button = IntVar()

        Radiobutton(self.window,
                    text='버스',
                    value=0,
                    variable=self.selected_radio_button).grid(row=0,
                                                              column=4,
                                                              sticky='w')
        Radiobutton(self.window,
                    text='지하철',
                    value=1,
                    variable=self.selected_radio_button).grid(row=1,
                                                              column=4,
                                                              sticky='w')
        Radiobutton(self.window,
                    text='버스+지하철',
                    value=2,
                    variable=self.selected_radio_button).grid(row=2,
                                                              column=4,
                                                              sticky='w')

        self.transfer_time = []
        self.is_sorted_by_transfer_time = False
        Button(self.window, text='경로 확인',
               command=self.select_path).grid(row=0, column=4, sticky='e')
        Button(self.window,
               text='시간 순 <-> 환승 횟수 순',
               command=self.sort_by_transfer_time).grid(row=2,
                                                        column=4,
                                                        sticky='e')

        # 경로 리스트박스와 스크롤바
        self.path_result_scroll = Scrollbar(self.window)
        self.path_result_scroll.grid(row=3, column=5, sticky='w' + 'n' + 's')
        self.path_result_list = Listbox(
            self.window,
            yscrollcommand=self.path_result_scroll.set,
            width=0,
            height=15)

        self.path_result_list.grid(row=3, column=4)
        self.path_result_scroll['command'] = self.path_result_list.yview

        Button(self.window,
               text='지도 보기',
               command=lambda: self.show_path_map(
                   self.path_result_list, self.fname, self.fx, self.fy, self.
                   tname, self.tx, self.ty)).grid(row=4,
                                                  column=4,
                                                  sticky='e',
                                                  ipadx=20)

        # 이메일 연동
        self.email_address = Entry(self.window, width=40)
        self.email_address.grid(row=6, column=4)
        Button(self.window,
               text='메일'
               ' 보내기',
               command=lambda: gmail.send_email(self.write_email_message(
               ), self.email_address.get())).grid(row=6,
                                                  column=4,
                                                  sticky='e',
                                                  ipadx=10)
        '''Label(self.window, text='텔레그램 봇').grid(row=3, column=4, padx=10, pady=5)
        Button(self.window, text='지하철 시간표 출력', command=telegram_bot.start).grid(row=3, column=5, stick='w', padx=10)'''

        self.window.mainloop()
def send_reminders(due_reminders, email, password):
    for reminder in due_reminders:
        send_email(email, password, reminder.address, reminder.message, "Your email reminder has arrived!")
import schedule
from docopt import docopt

from gmail import send_email

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Task Notifier 1.0')

    if arguments.get('start'):
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            print >> sys.stderr, 'Process fork failed %d - %s' % (e.errno, e.strerror)
            sys.exit(1)

        sender = ''
        recipient = ''
        subject = ''
        email_body = """
        Hello World!
        """

        schedule.every(1).minutes.do(
            lambda: send_email(sender, recipient, subject, email_body))

        while True:
            schedule.run_pending()
            time.sleep(1)