def login_handler(data): logger.debug("Login %s", data) data['type'] = 'login' sid = request.sid user = db.getUserByName(conn, data.get('doubleName').lower()) if user: logger.debug("User found %s", user[0]) update_sql = "UPDATE users SET sid=? WHERE double_name=?;" db.update_user(conn, update_sql, sid, user[0]) if data.get('firstTime') == False and data.get('mobile') == False: user = db.getUserByName(conn, data.get('doubleName').lower()) push_service.notify_single_device( registration_id=user[4], message_title='Finish login', message_body='Tap to finish login', data_message=data, click_action='FLUTTER_NOTIFICATION_CLICK', tag='testLogin', collapse_key='testLogin') insert_auth_sql = "INSERT INTO auth (double_name,state_hash,timestamp,scanned,data) VALUES (?,?,?,?,?);" db.insert_auth(conn, insert_auth_sql, data.get('doubleName').lower(), data.get('state'), datetime.now(), 0, json.dumps(data)) print('')
def change_password(): """ Api.change_password method arguments: [password] returns: empty body 200 -- password changed 400 -- wrong arguments 403 -- wrong authorization 500 -- internal error """ if not request.json or not 'password' in request.json or len( request.json['password']) == 0: abort(400) if not request.json['password'].isalnum(): abort(400) conn = conn_get() user = database.get_user(conn, AUTH.username()) user['password'] = generate_password_hash(request.json['password']) database.update_user(conn, user) conn.commit() return ""
def reset(): if logged_in(): return redirect(url_for('home')) message = None if request.method == 'POST': email = request.form['email'] username = request.form['username'] password1 = request.form['password1'] password2 = request.form['password2'] user = database.get_user(username) if not user: message = 'User does not exist.' elif password1 != password2: message = 'Passwords do not match' elif not user['email'] != email: app.logger.info(username + ' used invalid email at reset') message = 'Incorrect email' else: database.update_user( username, bcrypt.hashpw(password1.encode('utf-8'), bcrypt.gensalt()), email, user['description']) session['username'] = username app.logger.info(username + ' password reset successful') return redirect(url_for('home')) return render_template('reset.html', pagetitle='Reset', message=message)
def update_playlist(client: spotipy.Spotify, user: str): target_playlist = get_target_playlist(dt.now(tz=tz.utc), client, user) # in utc last_updated = get_newest_date_in_playlist(target_playlist, client) songs_to_be_added = get_unadded_songs(last_updated, client) database.update_user(client.me()['id'], "last_playlist", target_playlist) if len(songs_to_be_added) < 1: # print("No songs to be added for", client.me()['id']) pass else: timestamp = dt.now(tz=tz.utc).strftime('%Y-%m-%d %H:%M:%S') # print(timestamp + ": Adding " + str(len(songs_to_be_added)) + " songs for", client.me()['id']) database.update_user(client.me()['id'], "last_update", timestamp) database.increment_field(client.me()['id'], "update_count") # we can only add 100 songs at a time, place all the songs in a queue # and dequeue into a chunk 100 songs at a time chunk = [] while songs_to_be_added: chunk.append(songs_to_be_added.popleft()) if (len(chunk) == 100): client.user_playlist_add_tracks(client.me()['id'], target_playlist, chunk) chunk.clear() # if the chunk isn't completely filled then add the rest of the songs if (len(chunk) > 0): client.user_playlist_add_tracks(client.me()['id'], target_playlist, chunk)
def oauth(): global user url = request.url print(url) text = re.sub('.*\?', '', url) params = parser(text) user = OAuth1Session(CK, CS, params['oauth_token'], params['oauth_verifier']) res = user.post('https://api.twitter.com/oauth/access_token', params) params = parser(res.text) print(params) AK, AS = params['oauth_token'], params['oauth_token_secret'] id_ = params['user_id'] user = OAuth1Session(CK, CS, AK, AS) with open('datas.json', 'r') as f: obj = json.load(f) if is_exist(id_): print('update') update_user(id_, AK, AS) else: print('insert') insert_user(id_, AK, AS) return redirect(url_for('application'))
def update_user(user): """\ Updates the user entry in the database :param user: The <User> object that has to be updated in the database """ database.update_user(user)
def delete_menu(m_id): user = database.get_user(m_id) if not user: bot.send_message(m_id, 'Натисни /start, щоб почати.') return if int(user['menu_message']): bot.delete_message(m_id, int(user['menu_message'])) database.update_user(m_id, 'menu_message', '0')
def handle_unregistered_click(call): user = database.get_user(call.from_user.id) if user != None and call.data.startswith(Messages.GUILD): guild_name = call.data.split(':')[1] database.update_user(call.from_user.id, Database.FIELD_GUILD_NAME, guild_name) handle_user_status(user) else: bot.send_message(call.from_user.id, Locale.REGISTER_FIRST)
def send_menu_message(message): user = database.get_user(message.chat.id) delete_menu(message.chat.id) text = user['user_name'] + ', ви хочете знайти найближчий пункт переробки чи залишити заявку на вивіз сміття?' kb = types.InlineKeyboardMarkup() kb.row(types.InlineKeyboardButton(text='Найближчий пункт', callback_data='find_closest_init')) kb.row(types.InlineKeyboardButton(text='Заявка на вивіз', callback_data='leave_request_init')) m = bot.send_message(message.chat.id, text, reply_markup=kb) database.update_state(message.chat.id, 'menu') database.update_user(message.chat.id, 'menu_message', m.message_id)
def store_credentials(credentials): #use credentials to ask google who the credentials are for user_info = google_api.get_user_info(credentials) user_email = user_info['email'] #store currently authenticated user in session flask.session['authenticated_email'] = user_email #convert credentials object into dict and store in db credentials_dict = credentials_to_dict(credentials) database.update_user(email=user_email, credentials=credentials_dict) print('credentials obtained for %s' % user_email)
def send_email_gmail(sender_name, sender_email, recipient_email, service): #build message message = build_message(sender_name, sender_email, recipient_email) message = {'raw': base64.urlsafe_b64encode(message)} #try sending with service response = google_api.send_email(service, message) if response[0]: database.update_user(email=recipient_email, email_sent=True) return 'Message Id: %s sent from %s to %s' % (response[1], sender_email, recipient_email) else: return 'An error occurred: %s' % error
def update_user(): user = { "email": request.form["email"], "username": request.form["username"], "password_hash": generate_password_hash(request.form["password"]), "permissions": request.form["permissions"], "username-prev": request.form["username-prev"] } database.update_user(user) return redirect(url_for("admin_users"))
def main(): request_token = api.get_request_token() pin = input('Go to {} and enter the PIN here: ' .format(api.get_authorize_url(request_token['oauth_token']))) access_token = api.get_access_token(request_token['oauth_token'], pin) user = User(access_token['oauth_token'], access_token['oauth_token_secret']) user_data = api.get(user, 'account/verify_credentials') logging.info('adding user %s', user_data['screen_name']) with database.connect() as db, db.cursor() as cursor: twitter_id, = database.update_twitters(cursor, [user_data]) database.update_user(cursor, twitter_id, user.access_token, user.access_token_secret)
def user_profile(): """ Displays user profile data and handles two kinds of POST requests: 1) update to user profile itself (i.e. if user wishes to change their name or phone number) 2) application of these new settings to all user ads: user has a choice for specifying ad- specific contact phone and name. So they have to explicitly indicate if they want for their new defaults to be automatically applied to all of their ads. :return: """ user = flask_login.current_user apply_new_profile_settings_class = "style='display: none';" update_user_info_form = UpdateUserInfoForm(obj=user) apply_new_profile_settings_to_user_ads_form = FlaskForm() if request.method == 'POST': if not user_is_authorized_to_update_item(user.id): flash("You are not authorized to update this page") return redirect(url_for("index")) if request.form["action"] == "update_profile": if update_user_info_form.validate_on_submit(): user.name = update_user_info_form.name.data user.phone = update_user_info_form.phone.data database.update_user(user) flask_login.current_user.name = user.name flask_login.current_user.phone = user.phone apply_new_profile_settings_class = "" flash( "Your profile info has been updated. If you wish to apply your name and/" "or phone number to be applied" "to all your ads as contact info please click " "Apply new profile settings to all my ads button") elif request.form[ "action"] == "apply_new_profile_settings_to_user_ads": if apply_new_profile_settings_to_user_ads_form.validate_on_submit( ): database.update_ads_with_new_user_info(user) apply_new_profile_settings_class = "style='display: none';" # this post request is empty, so we need to force main form to show user name and phone update_user_info_form.name.data = user.name update_user_info_form.phone.data = user.phone flash("All ads have been updated with new user data.") return render_template( "user_profile.html", user=user, update_user_info_form=update_user_info_form, apply_new_profile_settings_to_user_ads_form= apply_new_profile_settings_to_user_ads_form, page_info=get_page_info(), apply_new_profile_settings_class=apply_new_profile_settings_class)
def get_user_info(credentials): people = googleapiclient.discovery.build('people', 'v1', credentials=credentials) user_profile = people.people().get( resourceName='people/me', personFields='names,emailAddresses').execute() info = { 'name': user_profile['names'][0]['displayName'], 'email': user_profile['emailAddresses'][0]['value'] } database.update_user(email=info['email'], name=info['name']) return info
def hack_form(): if request.method == 'POST': #extract post parameters sender_email = request.form.get('sender_email') sender_name = request.form.get('sender_name') recipient_email = request.form.get('recipient_email') #add recipient to db if they don't exist database.update_user(email=recipient_email) return sendemail.send_email_local(sender_name, sender_email, recipient_email) else: return render_template('hack_form.html')
def main(): request_token = api.get_request_token() pin = input('Go to {} and enter the PIN here: '.format( api.get_authorize_url(request_token['oauth_token']))) access_token = api.get_access_token(request_token['oauth_token'], pin) user = User(access_token['oauth_token'], access_token['oauth_token_secret']) user_data = api.get(user, 'account/verify_credentials') logging.info('adding user %s', user_data['screen_name']) with database.connect() as db, db.cursor() as cursor: twitter_id, = database.update_twitters(cursor, [user_data]) database.update_user(cursor, twitter_id, user.access_token, user.access_token_secret)
def send_email_local(sender_name, sender_email, recipient_email): #build message message = build_message(sender_name, sender_email, recipient_email) smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.ehlo() smtp.starttls() username = os.environ['GMAIL_USER'] password = os.environ['GMAIL_PASSWORD'] smtp.login(username, password) smtp.sendmail(sender_email, recipient_email, message) smtp.quit() database.update_user(email=recipient_email, email_sent=True) return 'Message sent from %s to %s' % (sender_email, recipient_email)
def notify_expiration(): users = database.get_users_with_expired_check() usr_count = len(users) if usr_count > 0: print(f'Found {usr_count} expired checkers') else: print('No users') for user in users: bot.send_message(user.telegram_id, Locale.BOSS_CHECK_EXPIRED) database.update_user(user.telegram_id, Database.FIELD_BOSS_MASK, 0)
def auth_signup(): post_data = request.get_json() from database import check_user user = check_user(post_data['username'], post_data['password']) print(user) if user is not None and (user['email'] is None or user['email'] == ''): from database import update_user if update_user(post_data['username'], post_data['email'], post_data['fullname']): token = jwt.encode({ 'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'username': post_data['username'] }, JWT_SECRET, algorithm=JWT_ALGORITHM).decode('utf-8') return { 'success': True, 'token': token } else: return { 'success': False, 'reason': 'creation_failed' } return { 'success': False, 'reason': 'no_account' if user is None else 'already_created' }
def authorize(): if 'oauth_token' not in flask.request.args: request_token = api.get_request_token(HOST + flask.url_for('authorize')) return flask.redirect(api.get_authorize_url(request_token['oauth_token'])) access_token = api.get_access_token(flask.request.args['oauth_token'], flask.request.args['oauth_verifier']) user = User(access_token['oauth_token'], access_token['oauth_token_secret']) user_data = api.get(user, 'account/verify_credentials') with db, db.cursor() as cursor: twitter_id, = database.update_twitters(cursor, [user_data]) database.update_user(cursor, twitter_id, user.access_token, user.access_token_secret) flask.session['screen_name'] = user_data['screen_name'] return flask.redirect(flask.url_for('user_mentors', screen_name=user_data['screen_name']))
def update_user(user_id): if not request.json or 'ID' not in request.json: abort(400) rows_affected = db.update_user(user_id, request.json) if rows_affected: return make_response(jsonify({'result': "ok"}), 200) else: return make_response(jsonify({'error': "couldn't update user"}),400)
def get_registration_code(user: User): code = random_digits() admins = database.get_all_admins() database.update_user(user.telegram_id, Database.FIELD_REG_CODE, code) bot.send_message(user.telegram_id, Locale.REGISTRATION_COMPLETE(code)) database.update_user(user.telegram_id, Database.FIELD_STATUS, Statuses.PENDING) keyboard = create_confirm_user_menu(user) question = Locale.REGISTRATION_COMPLETE_CONFIRM(user.character_name, code) # bot.send_message('463808631', text=question,reply_markup=keyboard) for admin in admins: if (admin.subscribed == Database.USER_SUBSCRIBED): bot.send_message(admin.telegram_id, text=question, reply_markup=keyboard)
def callback_worker(call): if call.data == Messages.MENU: send_menu(call) elif call.data == Messages.SUBSCRIBE: database.set_subscription(call.from_user.id, Database.USER_SUBSCRIBED) bot.send_message(call.from_user.id, Locale.CHARACTER_SUCCESSFUL_SUBCRIPTION) send_menu(call) elif call.data == Messages.UNSUBSCRIBE: database.set_subscription(call.from_user.id, Database.USER_UNSUBSCRIBED) bot.send_message(call.from_user.id, Locale.CHARACTER_SUCCESSFUL_UNSUBCRIPTION) send_menu(call) # elif call.data == Messages.WORLD_BOSSES: send_menu_bosses(call) # elif call.data in Bosses.getList(): notify_all(call.data, call.from_user.id) elif call.data == BossCheck.BEGIN_CHECKING: send_check_menu(call.from_user.id) elif call.data == BossCheck.CHECK_LIST: text = '' for boss_mask in BossMasks.boss_list(): text += f'{BossCheck.CHECK(boss_mask,database.get_users_by_mask(boss_mask))}\n\n' bot.send_message(call.from_user.id, text, parse_mode='markdown', reply_markup=botutils.create_menu( {Locale.GO_BACK: Messages.MENU})) elif call.data.startswith(Messages.CHECK): boss_mask = int(call.data.split(':')[1]) if (boss_mask in [BossMasks.ALL, BossMasks.NONE]): database.update_user(call.from_user.id, Database.FIELD_BOSS_MASK, boss_mask) else: database.toggle_user_mask(boss_mask, call.from_user.id) send_check_menu(call.from_user.id)
def location_handler(message): if not user_check_routine(message): return user = database.get_user(message.chat.id) if user['state'] == 'find_closest_init': database.update_state(message.chat.id, 'find_closest_type') print(message.location.longitude, message.location.latitude) database.update_user(message.chat.id, 'pos_lon', message.location.longitude) database.update_user(message.chat.id, 'pos_lat', message.location.latitude) types = recyclers.get_types() bot.send_message(message.chat.id, '\n'.join(types)) bot.send_message(message.chat.id, 'Вибери тип сміття зі списку вище. Можеш вибирати скільки завгодно, а потім просто повернутися в /menu.') if user['state'] == 'leave_request_location': database.update_state(message.chat.id, 'menu') print(message.location.longitude, message.location.latitude) database.update_request(message.chat.id, 'pos_lon', message.location.longitude) database.update_request(message.chat.id, 'pos_lat', message.location.latitude) bot.send_message(message.chat.id, 'Чудово! Оператор зв\'яжеться й домовиться з ваи про усе інше. Список ваших заявок можна побачити за допомогою /current_requests.') send_menu_message(message)
def oauth(): global user url = request.url text = re.sub('.*\?', '', url) params = parser(text) user = OAuth1Session(CK, CS, params['oauth_token'], params['oauth_verifier']) res = user.post('https://api.twitter.com/oauth/access_token', params) params = parser(res.text) AK, AS = params['oauth_token'], params['oauth_token_secret'] id_ = params['user_id'] user = OAuth1Session(CK, CS, AK, AS) if is_exist(id_): update_user(id_, AK, AS) else: insert_user(id_, AK, AS) return redirect(url_for('application'))
def login_handler(data): logger.debug("Login %s", data) double_name = data.get('doubleName').lower() state = data.get('state') data['type'] = 'login' sid = request.sid user = db.getUserByName(conn, double_name) if user: logger.debug("User found %s", user[0]) update_sql = "UPDATE users SET sid=? WHERE double_name=?;" db.update_user(conn, update_sql, sid, user[0]) user = db.getUserByName(conn, double_name) emitOrQueue('login', data, room=user[0]) insert_auth_sql = "INSERT INTO auth (double_name,state_hash,timestamp,scanned,data) VALUES (?,?,?,?,?);" db.insert_auth(conn, insert_auth_sql, double_name, state, datetime.now(), 0, json.dumps(data)) print('')
def callback_handler(call): if call.message.content_type == 'text': bot.edit_message_text(call.message.text, call.from_user.id, call.message.message_id) elif call.message.content_type == 'photo': bot.edit_message_caption(call.message.caption, call.from_user.id, call.message.message_id) data = call.data if data == "start game": ind, events = database.add_player(call.from_user.id, call.from_user.first_name) users[call.from_user.id] = [ind, events] send_mes(call.from_user.id, config.events[ind], ind) return elif data == "about": ab_markup = telebot.types.InlineKeyboardMarkup() ab_markup.add( telebot.types.InlineKeyboardButton("🎮 Начать игру", callback_data="start game")) bot.send_message(call.from_user.id, config.about, reply_markup=ab_markup) return else: if data in users[call.from_user.id][1]: data = 'not ' + data to_send = config.events[data] users[call.from_user.id][0] = data if 'command' in to_send: command = to_send['command'].split(' ') if 'add' in command: users[call.from_user.id][1] += command[1] + ' ' database.update_user(call.from_user.id, users[call.from_user.id][0], users[call.from_user.id][1]) send_mes(call.from_user.id, to_send, data) print(users[call.from_user.id])
def update_clients(): """ Refreshes the access tokens and updates the playlists for all clients in the cache """ for user in db.get_users(): if db.get_field(user, "active") != "false": print("updating", user) oauth = spotipy.oauth2.SpotifyOAuth( scope=constant.SCOPE, cache_handler=DatabaseCacheHandler(user), client_id=config.client_id, client_secret=config.client_secret, redirect_uri=config.redirect_uri) try: client = spotipy.Spotify(auth_manager=oauth) playlist.update_playlist(client, user) # reset the users error count if an update was successful db.update_user(user, "error_count", 0) except SpotifyException as e: # we hit a rate limit wait 60 seconds and retry if e.code == 429: time.sleep(60) try: playlist.update_playlist(client) except Exception as e: log_error_to_database(user, e) else: log_error_to_database(user, e) except Exception as e: log_error_to_database(user, e) # if a user passes a certain error threshold, mark them as # inactive, they probably revoked our access if db.get_field(user, "error_count") > constant.ERROR_THRESHOLD: try: db.update_user(user, "active", "false") except Exception: print("Could not set user to inactive")
def account_update(): user = auth.current_user() post_data = request.get_json() from database import update_user if update_user(user['username'], post_data['email'], post_data['fullname']): return { 'success': True } else: return { 'success': False }
def authorize(): if 'oauth_token' not in flask.request.args: request_token = api.get_request_token(HOST + flask.url_for('authorize')) return flask.redirect( api.get_authorize_url(request_token['oauth_token'])) access_token = api.get_access_token(flask.request.args['oauth_token'], flask.request.args['oauth_verifier']) user = User(access_token['oauth_token'], access_token['oauth_token_secret']) user_data = api.get(user, 'account/verify_credentials') with db, db.cursor() as cursor: twitter_id, = database.update_twitters(cursor, [user_data]) database.update_user(cursor, twitter_id, user.access_token, user.access_token_secret) flask.session['screen_name'] = user_data['screen_name'] return flask.redirect( flask.url_for('user_mentors', screen_name=user_data['screen_name']))
def log_in(): if request.method == 'POST': userid = request.form['username'] passw = request.form['password'] print(userid) print(passw) print("login!!!") try: sql = text("select * from User where username = '******' and password = '******'") data = db.engine.execute(sql) db.session.commit() print("test here") x = [] for row in data: x.append(row) print(len(x)) if len(x) != 0: print("log in success") session['logged_in'] = True print("log in 2222") user = load_user(x[0].id) user.id = x[0].id login_user(user, remember=True) database.update_user(user.id, "state", "0") print(current_user.id) return redirect(url_for('home')) else: return 'Not a registered user' return redirect(url_for('log_in')) except Exception as err: print("enter except") print(err) return "Not a registered user" return redirect(url_for('log_in')) return render_template('log_in.html')
def settings(): if not logged_in(): return redirect(url_for('login')) user = get_user() message = None if request.method == 'POST': username = user['username'] if not bcrypt.checkpw(request.form['password'].encode('utf-8'), user['password'].encode('utf-8')): message = "Incorrect password." else: app.logger.info(username + ' changed their settings') database.update_user(username, user['password'], request.form['email'], request.form['description']) message = "Changes saved successfully." if 'image' not in request.files: message = 'File not found.' else: file = request.files['image'] if file.filename == '': message = 'Invalid file name.' else: extension = os.path.splitext(file.filename)[1] if extension not in ['.png', '.jpg', '.jpeg']: message = 'Invalid file type.' else: file.save(app.config['upload_folder'] + username + '/' + username + '.png') user = get_user() else: request.form.email = user['email'] request.form.description = user['description'] return render_template('settings.html', pagetitle='Settings', user=user, message=message)
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 )