def authorized(): if "error" in request.args: # User cancelled the auth flow - discard auth (most likely there won't be any) session.pop("twitch_token", None) return redirect(url_for("mainpage")) twitch = OAuth2Session(config.CLIENT_ID, config.CLIENT_SECRET, state=session["login_state"]) resp = twitch.fetch_access_token( "https://id.twitch.tv/oauth2/token", code=request.args["code"], # For some bizarre reason, we need to pass this information along. client_id=config.CLIENT_ID, client_secret=config.CLIENT_SECRET, redirect_uri=url_for("authorized", _external=True)) if "access_token" not in resp: # Something went wrong with the retrieval. No idea what or why, # so I'm doing a cop-out and just dumping to console. print("Unable to log in") pprint(resp) print("Returning generic failure.") raise Exception session["twitch_token"] = resp["access_token"] session["twitch_refresh_token"] = resp["refresh_token"] session["twitch_auth_scopes"] = " ".join(sorted(resp["scope"])) user = query("helix/users", token="bearer")["data"][0] user["_id"] = user[ "id"] # For now, everything looks for _id. Existing logins don't have user["id"]. database.create_user(user["_id"]) session["twitch_user"] = user return redirect(url_for("mainpage"))
def create_new_user(): username = input("Username: "******"Password: "******"First Name:") surname = input("Surname: ") salt, bcrypt_password = create_password_salt(password) database.create_user(username, bcrypt_password, salt, first_name, surname)
def signup(): if "logged_in" in session and session['logged_in']: return redirect(url_for("home_page")) else: if request.method == 'POST': username = request.form['username'] email = request.form['email'] password = request.form['password'] file = request.files['file'] failed = None if file and allowed_file(file.filename): a = database.get_last_user_id() b = file.filename if a == None: f = str(1) + "." + b.rsplit('.', 1)[1].lower() else: f = str( (int(a.id) + 1)) + "." + b.rsplit('.', 1)[1].lower() target = os.path.join(app.config['UPLOAD_FOLDER_2'], f) file.save(target) database.create_user(username, email, password, f, 0, 0) # ###########################IMPORTANT Q: how to create a new name for session['pics(1/2/3/4/5/6/7/....)'] everytime it goes through the for loop return redirect(url_for('home_page')) if file and not allowed_file(file.filename): failed = True return render_template("signup.html", failed=failed) else: return render_template("signup.html")
def signup(): if request.method == "POST": email = request.form["email"] session["email"] = email password = request.form["password"] password2 = request.form["password-two"] access = request.form["access"] name = request.form["name"] location = request.form["location"] # Change this to create a user if authentic email if password != password2: return render_template("home.html", correct={"signup":True}, bad_signup=True, error="Passwords must match.") if database.user_exists(email): return render_template("home.html", correct={"signup":True}, bad_signup=True, error="User already exists.") if security.check_email(email): database.create_user(email, password, name, access, location) token = security.generate_confirmation_token(email) confirm_url = url_for("confirm", token=token, _external=True) html = render_template("activate.html", confirm_url=confirm_url) subject = "Please confirm your email" send_email(email, subject, html) flash("A confirmation email has been sent via email.", "success") return render_template("home.html", correct={"login":True}, bad_login=True, error="An authentication link has been sent to your email.", resend_auth=True) else: return render_template("home.html", correct={"signup":True}, bad_signup=True, error="Invalid email.") else: return render_template("home.html", correct={"signup":True}, bad_signup=False)
def user_render(access): if not database.valid_access(access): return render_template("error.html", error="Page not found.") elif not database.is_admin(session["access"]): return redirect(url_for("unauthorized")) else: users = database.get_users() if request.method == "POST": email = request.form["email"] password = request.form["password"] password2 = request.form["password-two"] new_access = request.form["access"] name = request.form["name"] location = request.form["location"] # Change this to create a user if authentic email if password != password2: return render_template("users.html", users=users, access=access, error="Passwords for " + email + " do not match.") if database.user_exists(email): return render_template("users.html", users=users, access=access, error="User: "******" already exists.") database.create_user(email, password, name, new_access, location) token = security.generate_confirmation_token(email) confirm_url = url_for("confirm", token=token, _external=True) html = render_template("account.html", confirm_url=confirm_url, access = new_access, password=password) subject = "Please confirm your email" send_email(email, subject, html) print("CONFIRM: ", confirm_url) print("EMAIL: ", email) return render_template("users.html", users=users, access=access, error="An authentication email has been send to: " + email) else: return render_template("users.html", users=users, access=access)
def post(self): try: info = loads(request.data.decode()) db.create_user(**info) except decoder.JSONDecodeError as e: return f'Error decoding json ({str(e)})', 500 else: return None, 204
def create_new_user(group_id=1): username = input("Username: "******"Password: "******"First Name:") surname = input("Surname: ") email = input("Email: ") salt, bcrypt_password = create_password_salt(password) database.create_user(username, bcrypt_password, salt, first_name, surname, email, group_id)
def start(bot, update): m = update.message if not is_message_for_bot(m): return m.reply_text(messages.START_MESSAGE) if not is_registered(m.from_user): create_user({ 'telegram_id': m.from_user.id, 'first_name': m.from_user.first_name })
def mainpage(channelid=None): # NOTE: If we've *reduced* the required scopes, this will still force a re-login. # However, it'll be an easy login, as Twitch will recognize the existing auth. if "twitch_token" not in session or session.get( "twitch_auth_scopes") != REQUIRED_SCOPES: return render_template("login.html") user = session["twitch_user"] if channelid is None: channelid = user["_id"] try: channelid = str(int(channelid)) except ValueError: # If you go to /editor/somename, redirect to /editor/equivalent-id # Bookmarking the version with the ID will be slightly faster, but # streamers will usually want to share the version with the name. users = query("helix/users", token="app", params={"login": channelid})["data"] # users is either an empty list (bad login) or a list of one. if not users: return redirect("/") return redirect("/editor/" + users[0]["id"]) if not may_edit_channel(user["_id"], channelid): return redirect(url_for("mainpage")) database.create_user( channelid ) # Just in case, make sure the database has the basic structure channel = get_channel_setup(channelid) sched_tz, schedule, sched_tweet = database.get_schedule(channelid) if "twitter_oauth" in session: auth = session["twitter_oauth"] username = auth["screen_name"] twitter = "Twitter connected: " + username tweets = list_scheduled_tweets(auth["oauth_token"], auth["oauth_token_secret"], sched_tz) else: twitter = Markup( """<div id="login-twitter"><a href="/login-twitter"><img src="/static/Twitter_Social_Icon_Square_Color.svg" alt="Twitter logo"><div>Connect with Twitter</div></a></div>""" ) tweets = [] error = session.get("last_error_message", "") session["last_error_message"] = "" return render_template( "index.html", twitter=twitter, username=user["display_name"], channel=channel, channelid=channelid, error=error, setups=database.list_setups(channelid), sched_tz=sched_tz, schedule=schedule, sched_tweet=sched_tweet, checklist=database.get_checklist(channelid), timers=database.list_timers(channelid), tweets=tweets, )
def handle_start (message): if not user_exist(message.from_user.id): create_user(message.from_user.id, message.chat.id, message.from_user.first_name, carteira="") #BOTÕES DO BOT user_markup = telebot.types.ReplyKeyboardMarkup(True, True) user_markup.row(' NST {:.8f} '.format(Salcon)) user_markup.row('Iniciar', 'Deposito') user_markup.row('Wallet NST', 'Saque', 'Suporte') user_markup.row('Ajuda') bot.send_message(message.from_user.id, 'Seu cadastro foi criado com sucesso! \n' ' Seja, Bem vindo {} ! ao melhor Bot de investimento.'.format(message.from_user.first_name), reply_markup=user_markup)
def sign_up(connection): firstname = input("Enter your first name ") lastname = input("Enter your last name ") password = input("Enter your password ") status = input("Enter your access code") date = datetime.datetime.now() if status == '256': status = 'admin' else: status = 'customer' database.create_user(connection, firstname, lastname, password, status, date)
def start(bot, update): chat_id = update.message.chat_id try: send_message(bot, chat_id, START_TEXT) username = get_username(update.message.chat) db.create_user(chat_id, username) except Exception as e: print('Error with chat_id: {}'.format(chat_id)) print(traceback.format_exc()) send_message(bot, chat_id, 'There was a server error')
def create_user(bot, update): chat_id = update.message.chat_id try: send_message(bot, chat_id, 'Creating your user, wait for a confirmation message') db.create_user(chat_id) send_message(bot, chat_id, 'User successfully created!') except Exception as e: print('Error with chat_id: {}'.format(chat_id)) print(traceback.format_exc()) send_message(bot, chat_id, 'There was an error while creating your user')
def signUp(): if request.method == "GET": return render_template("signIn.html") else: firstname = request.form["firstname"] lastname = request.form["lastname"] password = request.form["password"] email = request.form["email"] db.create_user(email, password, first_name=firstname, last_name=lastname) return redirect(url_for("home"))
def register(): form = forms.RegisterUserForm(request.form) if request.method == 'POST' and form.validate(): if form.access_code.data == access_code and not database.get_user_details_from_username( form.username.data): salt, bcrypt_password = logins.create_password_salt( form.password.data) database.create_user(form.username.data, bcrypt_password, salt, form.first_name.data, form.surname.data, form.email.data) return 'New user account created! <meta http-equiv="refresh" content="3;url=/login" />' return "Error, unable to create user account. User may already exist or access code may be incorrect" return (render_template("register.html", form=form))
def signup(): if request.method == 'POST': first_name = request.form['first_name'] last_name = request.form['last_name'] session['email'] = request.form['email'] email = request.form['email'] phoneNumber = request.form['phoneNumber'] password = request.form['password'] database.create_user(first_name, last_name, email, phoneNumber, password, '0') return render_template("survey.html") else: return render_template("signup.html")
def post_sign_up(): next_url = request.args['next'] email = request.form['email'] password = request.form['password'] confirmation = request.form['confirmation'] # Check if the fields were filled. email_valid = email is not None and email != '' email_feedback = 'Please enter your email address' password_valid = password is not None and password != '' password_feedback = 'Please enter your password' confirmation_valid = confirmation is not None and confirmation != '' confirmation_feedback = 'Please enter your password again' # Check if the fields match our simple regex. if email_valid: email_valid = re.match(r'[^@]+@[^@]+\.[^@]+', email) email_feedback = 'The value you’ve entered is not a valid email address' if password_valid: password_valid = len(password) >= 6 password_feedback = 'The password you’ve entered is too short to be valid' if confirmation_valid: confirmation_valid = password == confirmation confirmation_feedback = 'The passwords you’ve entered don’t match' # Check if the user does not already exist in the DB. if email_valid: email_valid = not database.user_exists(email) email_feedback = 'The email you’ve entered is already in use by another account' if email_valid and password_valid and confirmation_valid: # Hash the password. salt = os.urandom(SALT_LENGTH) password_hash = scrypt.hash(password, salt) # Create the user and their password in the database. user_id = database.create_user(email) database.create_password(user_id, salt, password_hash) # Set the login cookie. session['user_id'] = user_id session['email'] = email return redirect(next_url) else: return render_template('sign_up.html', next=next_url, email=email, email_valid=email_valid, email_feedback=email_feedback, password=password, password_valid=password_valid, password_feedback=password_feedback, confirmation=confirmation, confirmation_valid=confirmation_valid, confirmation_feedback=confirmation_feedback)
def test_create_user(session): user = create_user(session, name="Bob", password="******") session.commit() assert user.name == "Bob", "Bob's name should not be changed" assert user.password != "1234", "User password should be protected by a hash!" assert user.id == 1, "Bob should have an id!"
def register_user(message): """ Handle creating a new user in the database. """ LOGGER.debug(f"Attempting to create user from {message}") try: user_name = message["user_name"] email = message["email"] password = message["password"] except KeyError as error: raise UnauthorizedError( "A username, email, and password must be provided to register" ) from error user = create_user(database_session, user_name, email, password) database_session.commit() LOGGER.info(f"New user registered: {user.email} as {user.name}") emit( "registration_success", { "user_id": user.id, "user_name": user.name, "email": user.email }, )
def create_user(data): try: firstname = data["name"] name = data["name"] username = data["username"] password = data["password"] confirm_password = data["confirm_password"] except KeyError: emit("Error", { "message": "Fields are missing in create_user", "show": "false" }) return if (password != confirm_password): emit("Error", {"message": "Passwords do not match", "show": "true"}) return password = hashlib.md5(bytes(password, 'utf-8')) password = password.hexdigest() new_user = db.create_user(username, firstname, name, password) if (new_user): emit('new_user', 'success') return else: emit('new_user', 'failure') emit( 'Error', { "message": "Username already exists, try another username", "show": "true" }) return emit("new_user", "success")
async def profile(ctx, user=None): dec = database.read("users.json") if user is None: u_disc = ctx.message.author else: if isinstance(user, str): if user.startswith("<@!") and user.endswith(">"): user = user[3:][:-1] try: user = int(user) except ValueError: for u, d in dec.items(): if d['name'] == user: user = int(u) break else: await ctx.send(f":x: Aucun participant du nom de `{user}` n'a été trouvé !") return if isinstance(user, int): u_disc = client.get_user(user) if u_disc is None: await ctx.send(f":x: Aucun participant avec l'id `{user}` n'a pas été trouvé !") return try: user = dec[str(u_disc.id)] except KeyError: username = client.get_guild(688355824934060032).get_member(u_disc.id).nick if username is None: username = client.get_user(u_disc.id).display_name user = database.create_user(dec, username, u_disc.id) await ctx.send(embed=show_user(u_disc, user))
def setUp(self): prepare_db_for_tests() self.app = FlaskClient(app, response_wrapper=FormWrapper) self.app.application.config["CSRF_ENABLED"] = False self.depute = Depute(test_depute).save() self.user = create_user("test", "test") self.ctx = app.test_request_context() self.ctx.push()
def create_user(username, password, type_): db = current_app.config["db"] if db.create_user(username, password, type_): user_id = db.get_user(username, type_) user = User(user_id, username, password) return user else: return None
def create_account(): """ Render register page and process register requests. """ if request.method == "POST": form = request.form user_name = form["user_name"] password = form["password"] # Register and Login the user. create_user(g.session, user_name, password) g.session.commit() login(user_name, password) return redirect(url_for("main_page")) return render_template("register.html")
def login(): username = request.form.get("username") # check that username is not empty if not username: return "Username is empty" # check that username is free if username in logged_in_users: return "Username is busy" db.create_user(username) db.check_online(username) # create session for new user session["username"] = username logged_in_users.append(username) return redirect(url_for("chat"))
def signup(): form = request.form new_user = NewUser(form) uuid = create_user(new_user) if uuid is None: return redirect('/') session['uuid'] = uuid return redirect('/home')
def fitbit_user(): """ POST /user?access_token=<aaa>&user_id=<fitbit_user_id> """ access_token = request.args.get('access_token', '') logger.debug('Creating user with token %s', access_token) #get lifetimfe stats https://api.fitbit.com/1/user/4KRQ6L/activities.json # Get users fitbit email and points balance. # eg: https://api.fitbit.com/1/user/4KRQ6L/activities.json fitbit_id = request.args.get('user_id', '') user = database.get_user_by_fitbit(fitbit_id) if user is None: if len(access_token) > 0: fitbit_api = fitbit.Fitbit('227QRF', 'aacdb90aaaa175c50e0556e1a50f35ab',access_token=access_token) name = fitbit_api.user_profile_get(fitbit_id)['user']['fullName'] database.create_user(name=name, email='*****@*****.**', loyalty_program_user_id='GlobalRewards123', access_token=access_token, refresh_token='some refresh token', token_expiry='2016-10-01 12:12:12.777', fitbit_id=fitbit_id, points=20146) else: raise StandardError("no user found, or access token sent") user = database.get_user_by_fitbit(fitbit_id) if len(access_token) > 0: database.update_user_token(user.get('userIdentifier'), access_token) #points_balance = lcp_query.get_balance(user_id) #points_balance = 549 userJSON = { 'access_token': access_token, 'userId': user.get('userIdentifier'), 'points_balance': user.get('points'), 'name': user.get('name'), 'fitbitId':user.get('fitbit_id') } return Response(json.dumps(userJSON), status=httplib.CREATED, mimetype='application/json')
def register(): username = bleach.clean(request.form['username']) key = uuid.uuid4().hex if not db.user_exists(username, key) and studip.is_valid(username): points = studip.get_points(username) rank = studip.get_rank(username) try: db.create_user(username, key, points, rank) except db.IntegrityError: return get_error('Could not create user.') # return jsonify({'username': username, 'key': key, 'points': points, 'rank': rank}) return redirect( url_for('show_user', username=username) + '?uuid=' + str(key)) else: return get_error( 'Username not available in Stud.IP or already registered in this service.' )
def register(conn): conn.send(b'Enter username: '******'Enter password: '******'You have been successfully registered\n') else: conn.send(b'Opps error... Try again\n')
def register(self): if not self.type_selected: tkMessageBox.showwarning("Registration Failure", "Must select if creating a " "student or teacher account.") return if (self.tpw_entry != None) and (self.tpw_entry.get() != "engineering"): tkMessageBox.showwarning( "Registration Failure", "Must enter correct password " "to create teacher account." ) return name = self.name_entry.get() username = self.username_entry.get() password = self.password_entry.get() password_conf = self.confpw_entry.get() for x in [name, username, password, password_conf]: if x == "": tkMessageBox.showwarning("Registration Failure", "Please complete all fields.") return if password != password_conf: # Pop up window saying that passwords do not match tkMessageBox.showwarning( "Registration Failure", "The passwords you have entered do not match. " "Ensure that your passwords are matching and try again.", ) return if self.type_selected == "student": account_type = "student" else: account_type = "teacher" if database.username_exists(username): tkMessageBox.showwarning( "Registration Failure", "The username that you have selected already exists. " "Please choose a different username.", ) return else: database.create_user(name, username, account_type, hasher.create_hash(password)) self.destroy() login = LoginScreen(master=self.master) login.pack()
def addrec(): '''runs the SQL to make a new user, then renders a page based upon whether it was successful or not''' if request.method == 'POST': try: conn = mysql.connect() nm = request.form['nm'] unm = request.form['unm'] pswd = request.form['pswd'] dob = request.form['dob'] email = request.form['email'] salt = generate_salt() password = bcrypt.generate_password_hash(pswd + salt).decode('utf-8') database.create_user(conn, unm, nm, dob, password, email, salt) msg = " success!" except pymysql.err.IntegrityError: msg = "Sorry that username is already taken! Please try again." finally: conn.close() return render_template("result.html",msg=msg, links=check_for_cookie()[0])
def access_db(): """Renders 'user.html' page and checks for passed username inside the database. Gets user's data tuple only when flash messages are not displayed.""" form = LoginForm() global session_user if form.validate_on_submit(): if not signing_up: # As signing in... if database.check_user(form.username.data) is not None: flash('Username taken!') return redirect(url_for('access_db')) else: database.create_user(form.username.data, form.userkey.data) session_user = database.check_user(form.username.data) return redirect(url_for('user_choice')) else: if database.check_user(form.username.data) is None: flash('Cannot find username in database!') else: session_user = database.check_user(form.username.data) return redirect(url_for('user_choice')) return render_template('user.html', form=form)
def create_user(conn): conn.send(b'Enter username: '******'Enter password: '******'0. newbie\n1. soldier\n2. sergeant\n3. ensign\n4. lieutenant\n5. captain\n6. major\n7. colonel\n8. brigadier\n9. general\n10. marshal\nChoose rank: ') rank = int(get_input(conn)) success = database.create_user(username, password, rank) if success == True: conn.send(b'User successfully created\n') else: conn.send(b'Opps error... Try again\n')
def user_sign_up(): if request.method=="GET": return render_template('signup.html', incorrect=False, user=True, action_name="usersignup") elif request.method=="POST": username = request.form["username"] password = request.form["password"] confirm_pass = request.form["confirm"] first_name = request.form["first_name"] last_name = request.form["last_name"] if password != confirm_pass or not database.create_user(first_name, last_name, username, password): return render_template('signup.html', incorrect=True, user=True, action_name="usersignup") else: session["user"] = username return redirect(url_for("user_dashboard"))
def create_user(): """Creates a new user.""" if 'username' in session: return jsonify(ok=0, msg='First logout before creating a new user') user = request.form['user'] passw = request.form['pass'] if database.user_exists(user): return jsonify(ok=0, msg='User already exists') if database.create_user(user, passw): session['username'] = user session['userid'] = database.get_userid(user) session['password'] = passw return jsonify(ok=1, msg='User created!') return jsonify(ok=0, msg='User could not be created')
def register(): form = RegisterForm() if form.validate_on_submit(): if User.collection.find_one({"username": form.username.data}): form.username.errors.append(u"Ce pseudonyme est déjà pris.") return render_template("register.haml", form=form) if form.password.data != form.confirm_password.data: form.confirm_password.errors.append(u"Les mots de passe ne correspondent pas.") return render_template("register.haml", form=form) user = create_user(form.username.data, form.password.data) login_user(user) flash(u"Votre compte a correctement été créé.", "success") return redirect(url_for("home")) return render_template("register.haml", form=form)
def authenticate_client(self): request = conn.recv(1024) request = json.loads(request.decode("utf-8")) if request["action"] == "CREATE": print("Creating User") if request["username"] in database.users: response = {"action":"RESP", "good":"False", "reqnum":request["reqnum"], "message":"User already exists"} conn.send(json.dumps(response).encode("utf-8")) return False if len(request["username"]) == 0: response = {"action":"RESP", "good":"False", "reqnum":request["reqnum"], "message":"username cannot be empty"} conn.send(json.dumps(response).encode("utf-8")) return False if len(request["password"]) == 0: response = {"action":"RESP", "good":"False", "reqnum":request["reqnum"], "message":"password cannot be empty"} conn.send(json.dumps(response).encode("utf-8")) return False if len(request["email"]) == 0: response = {"action":"RESP", "good":"False", "reqnum":request["reqnum"], "message":"email cannot be empty"} conn.send(json.dumps(response).encode("utf-8")) return False if database.create_user(request): self.username=request["username"] response = {"action":"RESP", "good":"True", "reqnum":request["reqnum"]} conn.send(json.dumps(response).encode("utf-8")) return True if not request["action"] == "AUTH": response = {"action":"RESP", "good":"False", "reqnum":request["reqnum"]} conn.send(json.dumps(response).encode("utf-8")) return False if not database.authenticate(request["username"], request["password"]): response = {"action":"RESP", "good":"False", "reqnum":request["reqnum"]} conn.send(json.dumps(response).encode("utf-8")) return False self.username = request["username"] response = {"action":"RESP", "good":"True", "reqnum":request["reqnum"]} conn.send(json.dumps(response).encode("utf-8")) return True
def test_create_user(self): self.assertTrue(isinstance(create_user("foo", "bar"), User))
def test_create_user_save(self): create_user("foo", "bar") self.assertEqual(User.collection.find().count(), 1)
def test_user_as_login(self): user = create_user(username="******", password="******") self.assertEqual(user.username, "foo")
def test_dont_store_password_in_clear(self): user = create_user(username="******", password="******") self.assertNotEqual(user.password, "bar")
def test_password_is_correct(self): user = create_user(username="******", password="******") self.assertTrue(user.test_password("bar"))
def test_password_is_not_correct(self): user = create_user(username="******", password="******") self.assertFalse(user.test_password("bad password"))
def test_duplicated_users(self): create_user(username="******", password="******") self.assertRaises(DuplicatedUser, create_user, username="******", password="******")
def setUp(self): prepare_db_for_tests() self.user = create_user("pouet", "pouet") self.depute = Depute(test_depute).save()
def weixin(): # parse xml to dict obj xml = eT.fromstring(request.data) msg = dict() for ele in list(xml): msg[ele.tag] = ele.text # subscribe or unsubscribe if 'Event' in msg.keys(): return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=WELCOME_TEXT ) # normal command ask = msg['Content'] if ask == 'user': # prompt user to set their sno and password return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=LOGIN_TEXT ) elif ask == 'login': # prompt user to login check = check_user_status(msg) if check['status'] != 'success': return check['response'] else: jwxt = check['instance'] db.set_session_id(msg['FromUserName'], jwxt.cookies['JSESSIONID']) return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'已尝试登陆' ) elif re.match(r'^\d+#.+$', ask): # set sno and password sno, password = ask[:ask.find('#')], ask[ask.find('#') + 1:] user_info = db.get_user_info(msg['FromUserName']) if user_info: db.update_user(msg['FromUserName'], sno, password) else: db.create_user(msg['FromUserName'], sno, password) return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'创建成功' if not user_info else u'修改成功' ) elif ask in [str(i) for i in range(10)]: # query course from day 0-7, 0 stand for all, 1-7 stand for Monday to Sunday check = check_user_session(msg) if check['status'] != 'success': return check['response'] else: jwxt = check['instance'] try: # get today or tomorrow course (ask = 8, ask = 9) if ask == '8': ask = str(date.today().weekday() + 1) elif ask == '9': ask = str(date.today().weekday() + 2) course_list = jwxt.get_course_list(CURRENT_XND, CURRENT_XQ) course_list.sort(key=lambda x: int(x['day']) * 100 + int(x['start_time'])) output_list = [] for course in [course for course in course_list if ask == '0' or course['day'] == int(ask)]: course['start_time'] = COURSE_START_TIME[int(course['start_time']) - 1] course['end_time'] = COURSE_END_TIME[int(course['end_time']) - 1] course['date'] = WEEK_TIME[int(course['day']) - 1] output = u'{course_name}\n{date} {start_time}-{end_time}\n{location}{duration}'.format(**course) output_list.append(output) if not output_list: output_list.append(u'此期间没有课程') return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=('\n' + '-' * 20 + '\n').join(output_list) ) except: return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'会话过期, 请重新输入 login 命令登陆' ) elif re.match(r'^(cj#)(\d+#\d+)$', ask): # query score by xnd(year-year+1) and xq[0(all), 1, 2, 3] check = check_user_session(msg) if check['status'] != 'success': return check['response'] else: jwxt = check['instance'] try: tmp = ask.split('#') xnd, xq = u'{}-{}'.format(int(tmp[1]), int(tmp[1]) + 1), tmp[2] if xq in ['0', '1', '2', '3']: if xq == '0': score_list = reduce(lambda x, y: x + y, [jwxt.get_score_list(xnd, str(i)) for i in range(1, 4)]) else: score_list = jwxt.get_score_list(xnd, xq) output_list = [] for score in score_list: if len(score.get('jxbpm', '')) > 1: output = u'{kcmc}\n成绩: {zpcj}\n排名: {jxbpm}'.format(**score) else: output = u'{kcmc}\n成绩: {zpcj}'.format(**score) output_list.append(output) if not output_list: output_list.append(u'此期间没有成绩') return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=('\n' + '-' * 20 + '\n').join(output_list) ) else: return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'请输入正确的查询格式' ) except: return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'会话过期, 请重新输入 login 命令登陆' ) elif re.match(r'^gpa(#\d+#\d+)?$', ask): # query gpa by xnd(year-year+1) and xq[0(all), 1, 2, 3] or all gpa check = check_user_session(msg) if check['status'] != 'success': return check['response'] else: jwxt = check['instance'] try: output_list = [] tmp = ask.split('#') if len(tmp) == 1: gpa_list = jwxt.get_all_gpa() else: xnd, xq = '{}-{}'.format(int(tmp[1]), int(tmp[1]) + 1), tmp[2] if xq not in ['1', '2', '3']: return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'请输入正确的查询格式' ) gpa_list = jwxt.get_gpa(xnd, xq) for gpa in gpa_list: output = u'{oneColumn}: {twoColumn}'.format(**gpa) output_list.append(output) if not output_list: output_list.append(u'此期间没有绩点') return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content='\n'.join(output_list) ) except: return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'会话过期, 请重新输入 login 命令登陆' ) elif ask == 'credit': check = check_user_session(msg) if check['status'] != 'success': return check['response'] else: jwxt = check['instance'] count = 3 while not jwxt.tno and count >= 0: count -= 1 jwxt.get_info() try: output_list = [u'已获得的学分:'] for credit in jwxt.get_credit(): output = u'{oneColumn}: {twoColumn}'.format(**credit) output_list.append(output) output_list.append(u'-' * 20) output_list.append(u'毕业所需学分:') for credit in jwxt.get_total_credit(): output = u'{oneColumn}: {twoColumn}'.format(**credit) output_list.append(output) return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content='\n'.join(output_list) ) except: return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=u'会话过期, 请重新输入 login 命令登陆' ) else: # prompt user help information return weixin_response( from_user_name=msg['ToUserName'], to_user_name=msg['FromUserName'], content=HELP_TEXT )