Example #1
0
def run(config):
    # TODO: 减少对 config.json 的调用次数,导入一次就够了
    functions.schedule_run(config)
    token, login_response = functions.get_token(config)

    if token:
        userinfo = functions.get_user_info(token)
        index = 0
        date = functions.get_date("today")
        seats = functions.search_seats(token, config["room"], date)

        while seats is not False and index < len(seats):
            response = functions.post_data(seats, config, token, index)
            status = response[u"status"]
            index = index + 1
            time.sleep(random.uniform(0.1, 0.5))

            if status == u"fail":
                print "\n--------------Oops! failed!---------------\n"
                print "\n------------" + response[u'message'] + "-------------"
                break

            elif status == u"success":
                print "\n-------------Yeah! it's done!-------------\n"
                break

            # TODO: 将所有除了success和该座位已被预约以外的status设置为返回status并break

        # TODO: 调整send_mail参数
        functions.send_mail(config, response[u'message'])

    else:
        response = None

    return userinfo, response
Example #2
0
def waiting_from_you(u, m=None, c=None):
    if m is not None:
        u.why_fat_again = m.text
        u.save()
    bot.send_message(u.user_id, s.waiting_from_you)

    # устанавливаем отправку сообщения на 21.00
    dt = datetime.now()
    dt = dt.replace(hour=21, minute=0)
    schedule(dt, "thanks_for_efforts", user_id=u.user_id)

    keyboard = types.InlineKeyboardMarkup()
    agree_btn = types.InlineKeyboardButton(text=s.looked_btn,
                                           callback_data=s.agree)
    keyboard.add(agree_btn)
    send_message_delay(u.user_id,
                       s.measurements_link,
                       delay=10,
                       state=s.measurements,
                       reply_markup=keyboard)
    send_mail(u.email, "Замеры тела", s.measurements_link)

    dt = datetime.now()
    dt = dt.replace(hour=10, minute=0)
    delta = timedelta(days=1)
    schedule(dt + delta, "day_2", user_id=u.user_id)
Example #3
0
def email():
    my_email = "*****@*****.**"                                        
    my_password = "******"
    if request.method == 'POST':
        receiver = request.form.get("email")
        send_mail(receiver)
    return redirect(url_for('click'))
Example #4
0
    def post(self, request):
        email_id = request.POST["email_id"].strip()

        # check if email already exists
        if CustomUser.objects.filter(email=email_id).count():
            # the user exists
            messages.info(
                request,
                'This email is already in use, login <a href="'
                + reverse("login")
                + '">here</a>.',
            )
            return render(request, self.template)

        pass_phrase = config("SIGNUP_EMAIL_ENCODING_SECRET")
        encoded_email = encode_data(pass_phrase, email_id)
        encoded_email = encoded_email.replace("/", "slash")
        encrypted_hash = encrypt_data(config("SIGNUP_EMAIL_PHRASE"))
        encrypted_hash = encrypted_hash.replace("/", "slash")

        base_url = request.scheme + "://" + request.get_host() + "/accounts/signup/"
        link = base_url + encoded_email + "/" + encrypted_hash + "/"

        message_body = render_to_string(self.email, {"signup_link": link})

        # sending email
        functions.send_mail(
            to_emails=[email_id], content=message_body, subject="Newspapers Invite"
        )

        messages.info(request, "Check your mail for signup link.")
        return redirect("signup")
Example #5
0
def remind_1(u, c):
    u.state = s.stop
    u.save()
    bot.send_message(u.user_id, s.waiting_from_you)

    files = [
        'files/Анализы.pdf', 'files/Анкета.docx',
        'files/Анкета физактивность.docx'
    ]
    send_mail(u.email, s.your_documents, s.your_documents, files=files)

    img = open("images/system/img2.jpeg", "rb")
    send_photo_delay(cid(c), img, delay=3, state=s.stop)
    img = open("images/system/img1.jpeg", "rb")
    send_photo_delay(cid(c), img, delay=6, state=s.stop)

    keyboard = types.InlineKeyboardMarkup()
    continue_btn = types.InlineKeyboardButton(text=s.continue_btn,
                                              callback_data=s.agree)
    keyboard.add(continue_btn)
    send_message_delay(cid(c),
                       s.we_sent_mail,
                       delay=9,
                       state=s.remind_1,
                       reply_markup=keyboard)
Example #6
0
def review(request):
    saved = False
    review = ''
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            user_sender = User.objects.get(pk=request.POST['id_sender'])
            user_receiver = User.objects.get(pk=request.POST['id_receiver'])
            content = request.POST['content']
            sent = True
            re = Review()
            re.id_sender = user_sender
            re.id_receiver = user_receiver
            re.content = content
            re.save()
            mail_data = {}
            mail_data['subject'] = 'You have a new review.'
            mail_data['message'] = '''
                %s %s, <br> %s %s wrote a review about you. Here are the details<br>
                            <h3>Details: </h3><br>
                            %s
                                   ''' % (user_receiver.first_name, user_receiver.last_name, user_sender.first_name, user_sender.last_name, content)
            mail_data['from'] = '*****@*****.**'
            mail_data['sender'] = user_sender.email
            mail_data['receiver'] = user_receiver.email
            sent = utils.send_mail(mail_data)
            saved = True
            return HttpResponseRedirect('/trainer/%d' % (user_receiver.id))
        else:
            return HttpResponseRedirect('/')
Example #7
0
    def post(self, request):
        email = request.POST["email_id"].strip()

        # check if user exists
        if not CustomUser.objects.filter(email=email).count():
            messages.error(
                request,
                'User with this email does not exists, signup <a href="'
                + reverse("signup")
                + '">here</a>.',
            )
            return render(request, self.template)

        # get username using email
        user = CustomUser.objects.get(email=email)
        username = user.username

        # create password reset link
        encoded_link = (
            request.scheme
            + "://"
            + request.get_host()
            + "/accounts/password_reset/"
            + encode_data(config("PASSWORD_RESET_PHRASE"), email)
            + "/"
        )

        # send password reset email
        message = render_to_string(
            "accounts/password_reset_email.html",
            {"username": username, "reset_link": encoded_link},
        )
        functions.send_mail(
            to_emails=[email], content=message, subject="Reset Password"
        )

        messages.success(request, "Check your mail for password reset link.")
        return render(request, self.template)
Example #8
0
def respond(request):
    saved = False
    people =  0
    sessions = 0
    message = ''
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            user_sender = User.objects.get(pk=request.POST['id_sender'])
            user_receiver = User.objects.get(pk=request.POST['id_receiver'])
            sent = True
            people = form.cleaned_data['people']
            sessions = form.cleaned_data['sessions']
            message = form.cleaned_data['message']
            bm = Message()
            bm.id_sender = user_sender
            bm.id_receiver = user_receiver
            bm.message = message
            bm.people = people
            bm.sessions = sessions
            bm.save()
            mail_data = {}
            mail_data['subject'] = ' %s %s is Interested in you.' % (user_sender.first_name, user_sender.last_name)
            mail_data['message'] = '''
                %s %s, <br> %s %s is Interested in talking to you. To answer check your inbox.<br>
                            <h3>People: %s</h3>
                            <br>
                            <h3>Sessions: %s</h3>
                            <br>
                            <h3>Details: </h3><br>
                            %s
                                   ''' % (user_receiver.first_name, user_receiver.last_name, user_sender.first_name, user_sender.last_name, people, sessions, message)
            mail_data['from'] = '*****@*****.**'
            mail_data['sender'] = user_sender.email
            mail_data['receiver'] = user_receiver.email
            sent = utils.send_mail(mail_data)
            saved = True
            return HttpResponseRedirect('/search/')
        else:
            return HttpResponseRedirect('/')
Example #9
0
                                            params={"filter": "2fa_disabled"})
users = []

for user in json_list:
    user_dict = functions.do_github_api_request(user['url'])
    user_dict['first_alert'], user_dict['alert_count'] = functions.insert_user_row_in_db(conn, curs, user_dict,
                                                                                         dont_update_counter)
    users.append(user_dict)

conn.close()
email = functions.construct_email(users)
if skip_sending_email:
    print email
else:
    # lets send an overview email
    functions.send_mail(config.FromAddress, config.Receivers, "Github Two Factor authentication audit", email,
                        type="plain")
    if config.SEND_EMAIL_TO_USERS:
        ldap_conn = functions.connect_and_bind_to_ldap(config.LDAP_HOST.lower(), config.LDAP_USER, config.LDAP_PASS)
        email_users = functions.get_email_address_for_users(ldap_conn, base_dn, users)
        ldap_conn.unbind()
        # check if we have a custom email template
        if os.path.isfile(cur_path+"/templates/custom/email_instructions.html"):
            file_name = cur_path+"/templates/custom/email_instructions.html"
        else:
            file_name = cur_path+"/templates/email_instructions.html"

        with open (file_name, "r") as my_file:
            message=my_file.read().replace('\n', '')

        for email in email_users:
            functions.send_mail(config.FromAddress, email, "Please enable 2-factor authentication in Github", message,
Example #10
0
#!/usr/bin/env python
# -*- coding: utf8 -*-
from datetime import *
import sys
path='./include'
sys.path.insert(0,path)
import functions as func

send_mail_to_list = func.get_option('send_mail_to_list')
mailto_list=send_mail_to_list.split(';')

result = func.send_mail(mailto_list," I hope you can learn","Beautiful Day")
print result
if result:
    send_mail_status = "success"
else:
    send_mail_status = "fail"
print "send_mail_status:"+send_mail_status
Example #11
0
ldap_github_users = []

for user in result_set:
    user_details = user[0][1]
    github_user_name = user_details[config.LDAP_SCHEMA_FIELD][0]
    ldap_github_users.append(github_user_name.lower())

github_members = functions.do_github_api_request('https://api.github.com/orgs/' + config.Organisation + '/members')

github_users = []
for member in github_members:
    login = member['login'].lower()
    if not login in (name.lower() for name in config.LDAP_IGNORE_GITHUB_USERS):
        github_users.append(login)

not_in_list = list(set(github_users) - set(ldap_github_users))
count = len(not_in_list)
if count > 0:
    message = "The following Github users are not set in the LDAP server:\n\n"
    for username in not_in_list:
        username = username.encode('utf-8')
        message = message + username + " (https://github.com/" + username  + ")\n"
    message = message + "\nPlease edit the " + config.LDAP_SCHEMA_FIELD + " property and add the Github user name.\n"
    if skip_sending_email:
        print message
    else:
        functions.send_mail(config.FromAddress, config.Receivers, "Github users that are not registered in LDAP",
                            message, type="plain")

conn.unbind()
Example #12
0
# If connected to internet
if (is_connected()):
    try:
        log('Internet connection available')

        # Check for relevant roles
        relevant_roles = check_relevant_roles()

        # If relevant roles found
        if (relevant_roles):
            log(f'{len(relevant_roles)} relevant roles(s) found')

            # Send mail
            log('Sending mail...')
            send_mail(relevant_roles, 'success')

        # If no relevant roles found
        else:
            log('No relevant roles found')

    except Exception as e:
        log(f'Error: {str(e)}.')

        try:
            # Send error mail
            send_mail([], str(e))

        # If error mail cant be sent
        except Exception as e:
            log(f'Mail could not be sent. Error: {str(e)}.')
Example #13
0
				self.object_code = int_code
			except Exception as e:
				print(e)
				msg = "Ошибка. Некорректно указан файл с номером объекта или файл имеет некорректное содержимое"
				print(msg)
				log(msg)
				exit()





if __name__ == "__main__":
	args = Args()

	while True:
		if check_changes():
			try:
				good_names = get_pretty_names(args)
				raw_data = get_raw_data(args)
				generate_file(good_names, raw_data)

				msg = 'Файл создан'
				log(msg)
				send_mail(args.email, msg, msg)
			except:
				msg = 'Ошибка при создании файла'
				log(msg)
				send_mail(args.email, msg, msg)
		exit()
		sleep(60*60)
Example #14
0
def main():

	args = get_args()  # receive args

	str_date = datetime.today().strftime("%H:%M:%S %d/%m/%Y")
	if not args.nohup:
		print('\n'+str_date)
		d = '--- Spawn Execute and Notify (SEN) tool'
		d += ' for FLUKA 4 input files ---\n'
		d += '\t\t(cli edition)\n'
		print(d)

	inp_name = args.input[:-4]
	exe = args.exe

	if exe != "flukadpm":
		if not args.nohup:
			print(f'Custom executable {PATH_TO_CUSTOM}/{exe} will be used...')
		cmd_exe = f"-e {PATH_TO_CUSTOM}/{exe}"
		command = f"{PATH_TO_CUSTOM}/{exe}"
	# elif EXE == "":  # TODO simple fluka exe
	# 	cmd_EXE = ""
	# 	command = f"{os.environ['FLUKA']}/bin/fluka"
	else:
		if not args.nohup:
			print(f'Default executable "flukadpm" will be used...')
		cmd_exe = "-d"
		command = f"{os.environ['FLUKA']}/bin/flukadpm"

	copy_n = args.copyn
	skip_n = args.skipn
	if not args.nohup:
		print(f'Number of input files to spawn = {copy_n}')
		print(f'Number of input files to skip = {skip_n}')

	save_seed = open("Random.seed", "+w")
	save_seed.write(
		f"------ Start of Run {str_date} {inp_name}.inp" +
		f" number of copies: {copy_n} ------\n\n")

	save_total_seed = open("RandomTotal.seed", "+a")
	save_total_seed.write(
		f"------ Start of Run {str_date} {inp_name}.inp" +
		f" number of copies: {copy_n} ------\n\n")

	executive = []

	print()
	i = 1 + skip_n
	while i <= (copy_n + skip_n):

		cur_name = f"{inp_name}_{i:02d}.inp"

		shutil.copy(f"{inp_name}.inp", cur_name)

		# TODO maybe better algo for seed generation
		# Seed = "".join(['0'*(10-len(str(i))), str(i)])  № ???
		# Seed = "".join([str(i), '0'*(10-len(str(i)))])  # Seems ok
		seed = f'{1234567890+i}'

		with open(cur_name) as file_in:
			text = file_in.read()

		# search for string with random seed
		random_lst = functions.search_string_in_file(
			f'{inp_name}.inp',
			'RANDOMIZ')

		for rndm in random_lst:
			initial_str = rndm[1]

			text = text.replace(
				initial_str,
				f"RANDOMIZ          1.{seed}")

		with open(cur_name, "w") as file_out:
			file_out.write(text)

		if not args.nohup:
			print(f"Seed for: {cur_name} is {seed}")
		save_seed.write(f"Seed for: {cur_name} is {seed}\n")
		save_total_seed.write(f"{seed}\n")

		executive.append(
			f"/usr/bin/nohup $FLUKA/bin/rfluka -M 1 {cmd_exe} {cur_name} &")

		i += 1

	for file in [save_seed, save_total_seed]:
		file.write(
			f"\n------ End of Run {str_date} {inp_name}.inp" +
			f" number of copies: {copy_n} ------\n\n\n")
		file.close()

	# !!!Run files!!!
	for x in range(len(executive)):
		subprocess.call(executive[x], shell=True)
	# !!!Run files!!!

	time.sleep(3)  # Need delay to get PID of processes

	size_pids, pids, max_pid = functions.get_pids(command)

	if size_pids == 1:
		if pids[0] == 0:
			exit("Something went wrong! Check your input file correctness!")
		else:
			pass

	if not args.nohup:
		print(f"Number of processes in run is: {size_pids}\n")
		for i in pids:
			print(i)

	functions.create_bomb()  # create script to stop all jobs

	if args.notifybot:
		start_time = datetime.now()
		functions.telegram_bot(
			args.token, f"{inp_name}.inp", start_time, notify=not args.nohup)

	if args.notifymail:

		functions.send_mail(pids, size_pids, f'{inp_name}.inp', args.password)

		while not functions.check_pids_state(pids, size_pids):  # while False
			time.sleep(600)

		functions.send_mail(
			pids, size_pids, f'{inp_name}.inp', args.password, m_type='finish')

		subprocess.call('rm bomb.sh', shell=True)

	exit('\n--- Made by GN ---\n---- Goodbye! ----\n')
Example #15
0
from baro import bastemp
from spi_sensor import read_sensor

   
last_upt_wd = time.time()
text_formatting("Uygulama çalıştırıldı", 0, 'info')
values = []
interval_wd = 5
interval_rg = 0.1
wd = [0,0,0,0,0,0,0,0]
ws = 0
rg = 0
hk = 0
light = 0
offline = False
send_mail(get_interface_ip('eth0'))
ykilit = False
while True:
    if time.time() >= last_upt_wd + interval_wd:
       last_upt_wd = time.time()
       if read_sensor(0) >= 0.61 and read_sensor(0) <= 0.63:
           wd[0] = int(wd[0]) + 1
       elif read_sensor(0) >= 0.68 and read_sensor(0) <= 0.72:
           wd[1] = int(wd[1]) + 1
       elif read_sensor(0) >= 0.73 and read_sensor(0) <= 0.77:
           wd[2] = int(wd[2]) + 1
       elif read_sensor(0) >= 0.48 and read_sensor(0) <= 0.53:
           wd[3] = int(wd[3]) + 1
       elif read_sensor(0) >= 0.21 and read_sensor(0) <= 0.25:
           wd[4] = int(wd[4]) + 1
       elif read_sensor(0) >= 0.13 and read_sensor(0) <= 0.17:
Example #16
0
from baro import bastemp
from spi_sensor import read_sensor


last_upt_wd = time.time()
text_formatting("Uygulama çalıştırıldı", 0, "info")
values = []
interval_wd = 5
interval_rg = 0.1
wd = [0, 0, 0, 0, 0, 0, 0, 0]
ws = 0
rg = 0
hk = 0
light = 0
offline = False
send_mail(get_interface_ip("eth0"))
ykilit = False
while True:
    if time.time() >= last_upt_wd + interval_wd:
        last_upt_wd = time.time()
        if read_sensor(0) >= 0.61 and read_sensor(0) <= 0.63:
            wd[0] = int(wd[0]) + 1
        elif read_sensor(0) >= 0.68 and read_sensor(0) <= 0.72:
            wd[1] = int(wd[1]) + 1
        elif read_sensor(0) >= 0.73 and read_sensor(0) <= 0.77:
            wd[2] = int(wd[2]) + 1
        elif read_sensor(0) >= 0.48 and read_sensor(0) <= 0.53:
            wd[3] = int(wd[3]) + 1
        elif read_sensor(0) >= 0.21 and read_sensor(0) <= 0.25:
            wd[4] = int(wd[4]) + 1
        elif read_sensor(0) >= 0.13 and read_sensor(0) <= 0.17:
Example #17
0
import time
# Importing functions
from functions import check_price, send_mail
# Importing Class
from config import checkPrice

check_price()

# Send email if current price is lower or equal to entered value (see config)
if (check_price.convert_price <= checkPrice.targetPrice):
    send_mail()

# Loop time in seconds (every hour)
while (True):
    check_price()
    print('Going to sleep for an hour')
    time.sleep(3600)
Example #18
0
#!/usr/bin/env python
# -*- coding: utf8 -*-
from datetime import *
import sys
path = './include'
sys.path.insert(0, path)
import functions as func

send_mail_to_list = func.get_option('send_mail_to_list')
mailto_list = send_mail_to_list.split(';')

result = func.send_mail(mailto_list, " I hope you can learn", "Beautiful Day")
print result
if result:
    send_mail_status = "success"
else:
    send_mail_status = "fail"
print "send_mail_status:" + send_mail_status
Example #19
0
    # first get all the repositories for your organization
    repos = functions.do_github_api_request('https://api.github.com/orgs/' + config.Organisation + '/repos', params)

    message = ""
    for repo in repos:
        name = repo['name']
        repo_priv = repo['private']
        repo_url = repo['html_url']
        # public repository detected
        if repo_priv == False:
            message = message + "The repository " + name + " (" + repo_url + ") is defined as a public repository.\n"
        else:
            message = message + "The repository " + name + " (" + repo_url + ") is defined as a private repository.\n"
            forks = functions.do_github_api_request('https://api.github.com/repos/' + config.Organisation + '/' + name + '/forks')
            for fork in forks:
                owner_url = fork['html_url']
                message = message + "\t\tFork: " + owner_url + "\n"

    return message

# first get all the repositories for your organization
message = "Public repositories:\n\n"
message = message + get_repos_and_forks(True) + "\n\n"
message = message + "Private repositories:\n\n"
message = message + get_repos_and_forks(False) + "\n\n"

if skip_sending_email:
    print message
else:
    functions.send_mail(config.FromAddress, config.Receivers, "Repository information for organization " + config.Organisation,
                        message, type="plain")