예제 #1
0
파일: ms.py 프로젝트: Mause/haven
def main():
    sess = requests.Session()
    import betamax

    bm = betamax.Betamax(sess)

    match_requests_on = [
        # 'digest-auth',
        'path',
        'method',
        'body',
        'host',
        'uri',
        # 'headers',
        'query'
    ]

    with bm.use_cassette('ms', match_requests_on=match_requests_on):
        from main import login
        with open('auth.json') as fh:
            login(sess, *json.load(fh))

        units = list(get_units('2016 Semester 1', sess))

        from pprint import pprint
        pprint(units)

        write_out(units)
예제 #2
0
파일: ms.py 프로젝트: Mause/haven
def main():
    sess = requests.Session()
    import betamax

    bm = betamax.Betamax(sess)

    match_requests_on = [
        # 'digest-auth',
        'path',
        'method',
        'body',
        'host',
        'uri',
        # 'headers',
        'query'
    ]

    with bm.use_cassette('ms', match_requests_on=match_requests_on):
        from main import login
        with open('auth.json') as fh:
            login(sess, *json.load(fh))

        units = list(get_units('2016 Semester 1', sess))

        from pprint import pprint
        pprint(units)

        write_out(units)
예제 #3
0
 def move_MainMenu(self, password):
     main.login(ref, password)
     if ref.token != None:
         self.container.show_frame(MainMenu)
     if ref.token == None:
         self.label = tk.Label(self.status_frame, text="incorrect password")
         self.label.pack()
예제 #4
0
def get_novedades(current_pag=1, user=None, psw=None, logged_in=False):

    if not logged_in:
        login(user, psw, driver)
    else:
        pass

    file = open("C:\\Users\Martin\Documents\test\\Novedades " + hoy + ".txt",
                'w+')
    driver.find_elements_by_tag_name("select")[2].click()
    driver.find_element_by_xpath('//option[@value="FECHA"]').click()
    driver.find_element_by_xpath('//a[text()="Ordenar"]').click()
    autos = driver.find_elements_by_xpath(
        "//i[@class='fa fa-eye fa-lg']/preceding::td[3]")
    fechas = driver.find_elements_by_xpath(
        "//i[@class='fa fa-eye fa-lg']/preceding::td[1]")
    for i in range(0, 15):
        if hoy in fechas[i].text:
            expte = autos[i].text
            file.write(expte + "\n")
        else:
            break


# TODO: Me falta poner el avanzar pag. y arreglar problemas con el IO
예제 #5
0
def test_login_throws_if_no_username_provided():
    """
    When a request is sent without a username field in the Json body, an error
    should be returned.
    """
    request = Mock(json={})
    with pytest.raises(werkzeug.exceptions.BadRequest):
        main.login(request)
예제 #6
0
def test_login_success():
    with unittest.mock.patch('builtins.input', return_value="machine"):
        assert login() == True
    with unittest.mock.patch('builtins.input', return_value="agent"):
        assert login() == True
    with unittest.mock.patch('builtins.input', return_value="Machine"):
        assert login() == True
    with unittest.mock.patch('builtins.input', return_value="Agent"):
        assert login() == True
예제 #7
0
def get_n_combined_user():
    username = request.headers.get('username')
    password = request.headers.get('password')
    request_n = request.args.get('n', default='10', type=int)
    request_user = request.args.get('user', default='', type=str)
    n = int(request_n)
    main.login(username, password)
    messages = main.get_n_combined_user(n, request_user)
    main.logout()
    return jsonify(messages)
예제 #8
0
def test_login_throws_if_multiple_users_exists():
    """
    When logging in with a name that exists twice, and error should be thrown.
    """
    (main.db.collection.return_value.where.return_value.stream.return_value
     ) = [MagicMock(), MagicMock()]

    request = Mock(json={'username': '******'})
    with pytest.raises(RuntimeError):
        main.login(request)
예제 #9
0
파일: fixup.py 프로젝트: KevZho/redditbot
	def get(self):
		s = Session()
		login(s)
		players = db.GqlQuery("SELECT * FROM Player").fetch(None)
		for player in players:
			if player.baleeted is None:
				player.baleeted = False
			if player.userName.isdigit():
				logging.debug("fixing userID %s" % player.userName)
				player.userName = UserProfileRequest(s, player.userName).doRequest()['userName']
			player.put()
예제 #10
0
def get_new_since():
    username = request.headers.get('username')
    password = request.headers.get('password')
    request_date = request.args.get(
        'date',
        default=(datetime.datetime.now() -
                 datetime.timedelta(days=3)).strftime('%Y-%m-%d-%H-%M-%S'),
        type=str)
    date = datetime.datetime.strptime(request_date, '%Y-%m-%d-%H-%M-%S')
    main.login(username, password)
    messages = main.get_new_since(date)
    main.logout()
    return jsonify(messages)
예제 #11
0
	def get(self):
		s = Session()
		login(s)
		g = GetPendingApplicationsRequest(s)
		pending = g.doRequest()
		for userId in pending["players"]:
			logging.debug("adding %s" % userId)
			if userId not in Data.clanBlacklist:
				a = AddPlayerToClanRequest(s, userId)
				logging.debug("adding %s is a %s" % (userId, a.doRequest()))
				msg = SendMessageRequest(s, {'userId': userId, 'text': "You have been accepted into Reddit United.\n\nPlease read clan rules in the clan forums, under the subforum \"Clan Rules.\" We're telling you this because as a Normal Member (your current rank), you have 0 (ZERO) privileges (Yes, NO stash, NO dungeon), and the only way to be promoted is reading the rules C-A-R-E-F-U-L-L-Y! If you don't read them, we'll know. Oh, yes we'll know, all right.\n\nMake sure to join us in clan chat as well! Type in \"/listen clan\" (or) \"/chat clan\" into the chat box.\n\nPlease do not reply to this message. This is an automated response."})
				msg.doRequest()
			else:
				logging.debug("player %s is on blacklist" % userId)
예제 #12
0
def main(github_token, repo_name):
    u = login(github_token)
    repo = u.get_repo(repo_name)
    bookmark_issue = repo.get_issue(BOOKMARK_ISSUE_NUMBER)
    comments = bookmark_issue.get_comments()

    bookmark_str = BOOKMARK_STAT_HEAD
    for c in comments:
        has_file = False
        comment_str_list = c.body.splitlines()
        # drop the empty line
        comment_str_list = [c for c in comment_str_list if c]
        if len(comment_str_list) < 2:
            continue
        name, link = comment_str_list[0], comment_str_list[1]
        if link.find(f"{repo_name}/files") != -1:
            has_file = True
        bookmark_str += make_bookmark_str(
            f"[{name}]({link})",
            c.html_url,
            str(c.created_at)[:10],
            str(c.updated_at)[:10],
            has_file,
        )
    with open(BOOKMARK_FILE_NAME, "w+") as f:
        f.write(BOOKMARK_FILE_HEAD)
        f.write(bookmark_str)
예제 #13
0
def join(xpath):
    print("Start join zoom")
    driver = main.login(False)
    joinButton = driver.find_element_by_xpath(xpath)
    joinButton.click()

    print("Parent window title: " + driver.title)

    #get current window handle
    p = driver.current_window_handle

    #get first child window
    chwd = driver.window_handles

    for w in chwd:
        #switch focus to child window
        if (w != p):
            driver.switch_to.window(w)
            break
    time.sleep(5)
    pyg.click(722, 219)
    time.sleep(5)
    pyg.click(698, 429)
    time.sleep(5)
    pyg.click(750, 362)
    time.sleep(5)
    pyg.click(840, 279)
    driver.quit()
    print("DONE")
예제 #14
0
파일: Main.py 프로젝트: jaimodha/MMOG
    def menu(self, task):
        # Accept raw_input choice
        self.login = login()
        if self.login.getStatus() == "Authorized":
            print "going to character Select Menu"
            return task.done

        return task.again
예제 #15
0
파일: Main.py 프로젝트: jaimodha/MMOG
 def menu(self, task):
     # Accept raw_input choice
     self.login = login()
     if self.login.getStatus() == "Authorized":
         print "going to character Select Menu"
         return task.done
     
     return task.again
예제 #16
0
 def get(self):
     if ("username" in request.headers and "password" in request.headers):
         if (main.login(request.headers["username"],
                        request.headers["password"]) == False):
             return "E2"  # incorrect login
         return main.getDay(request.headers["username"],
                            request.headers["password"])
     else:
         return "E1"  # no/missing header data
예제 #17
0
def login_btn(controller):
    global username
    username = SP_username.get()
    user_name['text'] = username
    if main.login(username, SP_password.get()):
        controller.show_frame(PageOne)
        label['text'] = f'Welcome {main.USERS_DATA[username]["firstname"]}'

    else:
        SP_error_label['fg'] = 'red'
예제 #18
0
 def WBlogin(self):
     try:
         login(self.nickForm.text(), self.passwordForm.text())
         self.loggedIn = True
         for i in [
                 self.nickLabel, self.nickForm, self.passwordLabel,
                 self.passwordForm, self.loginButton
         ]:
             i.setVisible(False)
         for i in [
                 self.chooseClassLabel, self.chooseClassBox,
                 self.chooseButton
         ]:
             i.setVisible(True)
     except:
         pass
     time.sleep(1)
     self.classes = loadClasses()
     self.chooseClassBox.addItems([i.text for i in self.classes])
예제 #19
0
 def get(self, mp):
     if ("username" in request.headers and "password" in request.headers):
         if (main.login(request.headers["username"],
                        request.headers["password"]) == False):
             return "E2"  # incorrect login
         return jsonify(
             main.getSched(request.headers["username"],
                           request.headers["password"], mp))
     else:
         return "E1"  # no/missing header data
예제 #20
0
 def get(self):
     if ("username" in request.headers and "password" in request.headers):
         if (main.login(request.headers["username"],
                        request.headers["password"]) == False):
             return "400"  # incorrect login
         return jsonify(
             main.getClasses(request.headers["username"],
                             request.headers["password"]))
     else:
         return "500"  # no/missing header data
예제 #21
0
파일: Main.py 프로젝트: jaimodha/MMOG
    def __init__(self):

        # Network Setup
        self.cManager = ConnectionManager()
        self.startConnection()
        print "Ran Main2"
        #taskMgr.add(self.menu, "Menu")
        self.login = login()
        self.login.createLogo()
        self.login.createLoginWindow()
        print "Finished"
예제 #22
0
파일: Main.py 프로젝트: jaimodha/MMOG
    def __init__(self):
        
	    # Network Setup
        self.cManager = ConnectionManager()
        self.startConnection()
        print "Ran Main2"
        #taskMgr.add(self.menu, "Menu")
        self.login = login()
        self.login.createLogo()
        self.login.createLoginWindow()
        print "Finished"
예제 #23
0
파일: get_up.py 프로젝트: mq0707/2021
def main(github_token, repo_name):
    u = login(github_token)
    repo = u.get_repo(repo_name)
    issue = get_get_up_issue(repo)
    is_toady = get_today_get_up_status(issue)
    if is_toady:
        print("Today I have recorded the wake up time")
        return
    body, is_get_up_early = make_get_up_message()
    if is_get_up_early:
        issue.create_comment(body)
    else:
        print("You wake up late")
예제 #24
0
def main_command_controller(maincom, secondcom):
    if maincom != "run":
        raise errors.CliArgumentsError(
            "Debes iniciar el programa con 'python3 cli.py run login o python3 cli.py run create'"
        )
    if secondcom == "create":
        main.create_user_db()
    if secondcom == "login":
        login_status, pw, name = main.login()
        if login_status:
            main.logged_in_menu(pw, name)
        else:
            print("Error de password.")
            return
예제 #25
0
def test_login_gets_user_if_user_exists():
    """
    When logging in with an existing name, that user should be retrieved from
    the database.
    """
    user = MagicMock()
    user.id = 'test'
    (main.db.collection.return_value.where.return_value.stream.return_value
     ) = [user]

    request = Mock(json={'username': '******'})
    response = main.login(request)
    assert main.db.collection.return_value.document.called
    assert main.db.collection.return_value.document.call_args[0][0] == 'test'
    assert 'token' in json.loads(response)
예제 #26
0
def record_schedule():
    container=[]
    driver = main.login(True)
    # mengambil table data di web
    table = WebDriverWait(driver, 8).until(lambda driver: driver.find_elements_by_css_selector("#studentViconList tr td"))
    for tr in table:
        if(tr.text!=''):
            container.append(tr.text)
    rows = len(driver.find_elements_by_xpath('//*[@id="studentViconList"]/tbody/tr'))
    header = driver.find_element_by_xpath('//*[@id="studentViconList"]/thead/tr')
    matrix = np.array(container).reshape((rows-2),12)
    for i in range(0,(rows-2)):
        matrix[i][11] = '//*[@id="studentViconList"]/tbody/tr['+ str((i+3)) +']/td[12]/div/a'
    df = pd.DataFrame(data=matrix,columns=['DATE','TIME','CLASS','ROOM','CAMPUS','DELIVERY MODE','COURSE','WEEK','SESSION','MEETING ID','MEETING PASSWORD','VICON'])
    df.to_csv(r'C:\Users\Asus\Desktop\auto-login\schedule_record.csv')
    print("record has done")
예제 #27
0
def dejar_nota(current_pag=1):

    # Llega a los expedientes en despacho
    driver.find_elements_by_class_name("btn-filter")[1].click()
    while driver.find_element_by_xpath(
            "//*[text()='Consulta en proceso']").is_displayed():
        sleep(0.1)

    driver.find_element_by_xpath('//span[text()=' + current_pag + ']').click()

    for i in range(0, 16):

        # referencia en cada loop los botones de dejar nota y los nombres de los autos, ya que la sesion
        # se vence.
        lapices = driver.find_elements_by_xpath(
            "//i[@class='fa fa-pencil fa-lg']")
        autos = driver.find_elements_by_xpath(
            "//i[@class='fa pencil fa-lg']/preceding::td[3]")

        while driver.find_element_by_xpath(
                "//*[text()='Consulta en proceso']").is_displayed():
            sleep(0.1)

        lapices[i].click()

        driver.find_element_by_xpath('//input[@value="Dejar Nota"]').click()

        while driver.find_element_by_xpath(
                "//*[text()='Consulta en proceso']").is_displayed():
            sleep(0.1)

        if "Ya se ha dejado nota con el usuario" or "Se ha dejado nota en el expediente de forma correcta" in driver.page_source:
            print("Nota correcta en autos " + autos[i].text)

        else:
            print("Error dejando nota, ultima nota en " + autos[i].text +
                  " en pagina: " + str(current_pag))
            print("Intentando reinicio")
            driver.quit()
            if login():
                dejar_nota(current_pag)
            break  # Aca va error handling - raise exception

    avanzar_pag(current_pag)
예제 #28
0
def main(github_token, repo_name, weather_message, tele_token, tele_chat_id):
    u = login(github_token)
    repo = u.get_repo(repo_name)
    issue = repo.get_issue(GET_UP_ISSUE_NUMBER)
    is_toady = get_today_get_up_status(issue)
    if is_toady:
        print("Today I have recorded the wake up time")
        return
    weather_message = f"现在的天气是:{weather_message}\n"
    early_message, is_get_up_early = make_get_up_message()
    body = weather_message + early_message
    if is_get_up_early:
        issue.create_comment(body)
        # send to telegram
        requests.post(
            url="https://api.telegram.org/bot{0}/{1}".format(
                tele_token, "sendMessage"),
            data={
                "chat_id": tele_chat_id,
                "text": body,
            },
        )
    else:
        print("You wake up late")
예제 #29
0
 def test_login_inconsistent_data(self, mock_input):
     # Вводим только один параметр, хотя нужна пара - логин и пароль
     mock_input.side_effect = [random_word(8)]
     with unittest.mock.patch('builtins.input', mock_input):
         main.login()
예제 #30
0
 def test_lottery_login(self):
     assert login() == True, "Testing Login"
예제 #31
0
 def test_CorrectLogin(self):
     user = self.users.get_user_by_id(self.user1id)
     data = main.login(user['email_address'], user['password'])
     self.assertEqual(data['success'], True, "Login was unsuccessful")
     self.assertEqual(data['error'], None)
예제 #32
0
# contacts = get_dynamic_list(url)

# hubspot login info
credentials = ['ACCOUNT EMAIL', 'ACCOUNT PASSWORD']

# # sequence_info = [start_date, start_time, am/pm, days_until_followup, time_follow_up, am/pm]
sequence_info = ['02/23/2018', '3:30', 'pm', '5', '8:00', 'am']
#
# #emails to sequence
# test_contacts = [['jake', 'maldo', 'text company', 'https://app.hubspot.com/contacts/12345/contact/12345/?interaction=note']]

#template for the sequences

driver = get_driver(True)
print('******** Driver created ********')
login(credentials, driver)
print('******** Login completed ********')

#
# with open('Sasha_Sequence_proper.csv', 'r') as f:
#     reader = csv.reader(f)
#     contact_list = list(reader)
#
# get_emails(contact_list, template, sequence_info, driver)
# for contact in contact_list:
#     contact_id = contact[0]
#     contact_json = json.loads(requests.get(
#         'https://api.hubapi.com/contacts/v1/contact/vid/' + contact_id + '/profile?hapikey=' + api_key).text)
#     print('https://api.hubapi.com/contacts/v1/contact/vid/' + contact_id + '/profile?hapikey=' + api_key)
#     last_emailed = int(contact_json['properties']['hs_email_last_send_date']['value'].strip())
#     last_emailed_datetime = datetime.datetime.fromtimestamp(int(last_emailed) / 1e3)
예제 #33
0
import time
import csv
import schedule
from main import login
okay = login()


def server():
    #okay.sendmail()
    f = open('log.csv', 'w')
    h = csv.writer(f, quoting=csv.QUOTE_ALL)

    h.writerow([str(time.time())])
    h.writerow([str(okay.last_reply()[-1])])
    f.close()
    with open('log.csv', newline='') as outf:
        reader = csv.reader(outf)
        list_f = list(reader)
    #print(list_f)

    diff = int(float(list_f[-1][0])) - int(float(list_f[-2][0]))
    if abs(diff) > 180:
        okay.sendpdf()
    #elif abs(diff) > 60:
    #   okay.sendmail()


schedule.every(1).hour.do(okay.sendmail)
time.sleep(3600)
schedule.every(2).hours.do(server)
while True:
예제 #34
0
파일: daily.py 프로젝트: yoavz/snapcat
    folders = os.walk(config.PIC_DIRECTORY).next()[1]
    folders_int = dict()
    for f in folders:
        try:
            folders_int[f] = int(f)
        except:
            pass

    max_pic_folder = max(folders_int.items(), key=operator.itemgetter(1))[0]
    pic_path = os.path.join(config.PIC_DIRECTORY, max_pic_folder)
    pic_names = os.walk(pic_path).next()[2]
    return [os.path.join(config.PIC_DIRECTORY, max_pic_folder, n) for n in pic_names]

if __name__ == '__main__':

    user = main.login()
    username = user.get('username')
    auth_token = user.get('auth_token')

    if not username or not auth_token:
        print 'ERROR while logging in'
    
    recipients = get_all_recipients()
    images = get_images()

    if recipients and images:
        chosen_image = random.choice(images)
        print 'Using image: ' + chosen_image
        main.send_image(username, auth_token, recipients, chosen_image, sleep_time=config.SLEEPTIME)
    else:
        print 'Users and/or images not found'
예제 #35
0
def dejar_nota(current_pag=1, user=None, psw=None, logged_in=False):
    pagina = str(current_pag)
    driver = webdriver.Firefox()
    if not logged_in:
        login(user, psw, driver)
    else:
        pass

    # Llega a los expedientes en despacho
    try:
        if "Quitar filtro dejar nota" in driver.page_source:
            pass
        else:
            driver.find_elements_by_class_name("btn-filter")[1].click()
    except NoSuchElementException as e:
        print(e)
        driver.find_elements_by_class_name("btn-filter")[1].click()

    while driver.find_element_by_xpath(
            "//*[text()='Consulta en proceso']").is_displayed():
        sleep(0.3)

    if current_pag > 1:
        driver.find_element_by_xpath('//span[text()=' + pagina + ']').click()
    while driver.find_element_by_xpath(
            "//*[text()='Consulta en proceso']").is_displayed():
        sleep(0.3)

    try:

        for i in range(0, 15):

            driver.execute_script("window.scrollBy(0, 120);")
            # referencia en cada loop los botones de dejar nota y los nombres de los autos, ya que la sesion
            # se vence.
            lapices = driver.find_elements_by_xpath(
                "//a[@class='btn btn-info btn-sm']")

            try:
                while driver.find_element_by_xpath(
                        "//*[text()='Consulta en proceso']").is_displayed():
                    sleep(0.3)
            except NoSuchElementException as e:
                pass

            lapices[i].click()

            try:
                while driver.find_element_by_xpath(
                        "//*[text()='Consulta en proceso']").is_displayed():
                    sleep(0.3)
            except NoSuchElementException as e:
                pass

            driver.find_element_by_xpath(
                '//input[@value="Dejar Nota"]').click()

            try:
                while driver.find_element_by_xpath(
                        "//*[text()='Consulta en proceso']").is_displayed():
                    sleep(0.3)
            except NoSuchElementException as e:
                pass

            if "Ya se ha dejado nota con el usuario" or "Se ha dejado nota en el expediente de forma correcta" in driver.page_source:

                sleep(2)
                autos = driver.find_elements_by_xpath(
                    "//a[@class='btn btn-info btn-sm']/preceding::td[5]")
                try:
                    import intercara
                    msj = str("Nota correcta en autos " + autos[i].text)
                    agValor = intercara.Ui_MainWindow
                    agValor.agregar_valor(msj=msj)
                except Exception as e:
                    print(e)

            else:
                print("Error dejando nota, ultima nota en " + autos[i].text +
                      " en pagina: " + pagina)
                print("Intentando reinicio")
                driver.quit()
                if login():
                    dejar_nota(current_pag, logged_in=False)
                break  # Aca va error handling - raise exception
    except IndexError as indice:
        print(indice)
        print("Se ha llegado al final de la lista. Nota terminada")
        driver.quit()

    avanzar_pag(current_pag, driver)
예제 #36
0
파일: gui.py 프로젝트: colddreams/web_plug
 def on_click(self):
     main.login()
예제 #37
0
파일: score.py 프로젝트: mrzhangboss/test
def get_score(username, passwd):
	session = main.login(username, passwd)
	url = 'http://218.64.56.18/xszqcjglAction.do?method=queryxscj'
	res = session.post(url, data={'kksj':'2015-2016-1'})
	return res.content