def get_users_tasks(db): username = request.query['username'] user_id = database.get_user_data(db, username)['userID'] task_list = database.position_list(db, user_id) registerd_tasks = tasks_registered_by_user(db) ret_val = [] for x in task_list: is_registered = False for registered_task in registerd_tasks: if (registered_task['jobID'] == x[0]): is_registered = True status = status_dict[str(x[8])] ret_val.append({ 'id': x[0], 'time': x[1], 'owner': x[3], 'title': x[4], 'location': x[5], 'description': x[6], 'selectedUserID': x[7], 'category': x[10], 'ownerName': database.get_user_data(db, x[3])['name'], 'cost': x[9], 'isRegistered': is_registered, 'status': status, 'selectedUsername': database.get_username(db, x[7]), }) return {'result': ret_val}
def task(db): all_tasks = database.position_list(db, None) registerd_tasks = tasks_registered_by_user(db) ret_val = [] for task in all_tasks: is_registered = False for registered_task in registerd_tasks: if (registered_task['jobID'] == task[0]): is_registered = True status = status_dict[str(task[8])] ret_val.append({ 'id': task[0], 'time': task[1], 'owner': task[3], 'name': database.get_user_data(db, task[3])['name'], 'title': task[4], 'location': task[5], 'description': task[6], 'selectedUserID': task[7], 'cost': task[9], 'category': task[10], 'status': status, 'isRegistered': is_registered }) return {'result': ret_val}
def standup_send(token, channel_id, message): """ Add a message to standup queue """ # If token is valid, take u_id which is used to look through users u_id = database.get_current_user(token) # Check if user is member of channel that message is within # if not then raise an AccessError channel_data = database.get_channel_data(channel_id) if u_id not in channel_data['member_ids']: raise error.AccessError( description="You are not a member of this channel") # Check if message if more than 1000 characters long and raise InputError if that is the case if len(message) > 1000: raise error.InputError( description="The message entered is more than 1000 characters long" ) # Check if standup is currently active in channel, raise InputError if not if standup_active(token, channel_id)['is_active'] is False: raise error.InputError( description="There are no standups active in this channel") # Format message to "handle_str: message" handle_str = database.get_user_data(u_id)['handle_str'] string = handle_str + ": " + message # Now add string to the appropriate list in queues QUEUES[str(channel_id)].append(string) return {}
def main(record): e = None q_data = None if record is None: return redirect(url_for('index')) if request.method == 'POST': app.logger.info("main POST request: %s", request) if request.form['title']: t = request.form['title'] else: t = None if request.form['year']: y = request.form['year'] else: y = None if request.form['artist']: a = request.form['artist'] else: a = None q_data = database.query_music(t, y, a) user_data = database.get_user_data(record, None) sub = [] if user_data is not None: sub = database.get_sub_music(user_data.get('slist')) data = { 'e': e, 'user_data': user_data, 'uid': record, 'q_data': q_data, 'sub': sub } return render_template('main.html', data=data)
def get_user_data_json(db): username = request.query['username'] print(username) user_data = database.get_user_data(db, username) # need to use split_string and acces items as you would in an array for skills field return {'result': user_data}
def get_user_tasks(db): user_id = get_user_id(db) task_list = database.position_list(db, user_id) ret_val = [] for x in task_list: status = status_dict[str(x[8])] ret_val.append({ 'id': x[0], 'time': x[1], 'owner': x[3], 'title': x[4], 'location': x[5], 'description': x[6], 'selectedUserID': x[7], 'category': x[10], 'ownerName': database.get_user_data(db, x[3])['name'], 'cost': x[9], 'status': status, 'selectedUsername': database.get_username(db, x[7]), }) return {'result': ret_val}
def send_user_score(event, vk_api): user_id = get_user_id(event) score = get_user_data(user_id)['score'] keyboard = get_message_keyboard(['Новый вопрос']) vk_api.messages.send(user_id=event.user_id, keyboard=keyboard.get_keyboard(), message=f'Текущий счет: {score}', random_id=random.randint(1, 1000))
def start_game(event, vk_api): user_id = get_user_id(event) user_score_delta = get_user_data(user_id)['score'] * -1 update_user_score(user_id, user_score_delta) keyboard = get_message_keyboard(['Начать викторину']) vk_api.messages.send(user_id=event.user_id, keyboard=keyboard.get_keyboard(), message='Привет! Я бот для викторин', random_id=random.randint(1, 1000))
def is_admin_logged(): user = get_user() if user == None: return False user_data = database.get_user_data(user) if (user_data[5] < variables.admin_privilige): return False return True
def user_profile(token, u_id): """ Given a token and u_id return a dictionary containing the user's data """ # pylint: disable=unused-argument # NB: Supressed this warning because token is in fact used in # the decorator, however pylint doesn't check for this. user = database.get_user_data(u_id) return {"user": user}
def send_right_answer(event, vk_api): user_id = get_user_id(event) question_id = get_user_data(user_id)['last_asked_question'] answer = get_right_answer(quiz_content, question_id) keyboard = get_message_keyboard(['Новый вопрос', 'Мой счет']) vk_api.messages.send(user_id=event.user_id, keyboard=keyboard.get_keyboard(), message=f'Правильный ответ {answer}', random_id=random.randint(1, 1000))
def channel_details(token, channel_id): """ This function is given a valid token and channel_id. It then returns the name, owners and members of the channel """ # Check if token is valid and raise AccessError if not curr_id = database.get_current_user(token) # check if user is a member of channel with channel_ID and return AccessError if not if is_user_channel_member(channel_id, curr_id) is False: raise error.AccessError(description="""You must be a member of the channel to view its details.""") # now we return the name, owners and members of the channel details = {"name": "", "owner_members": [], "all_members": []} # for owner/all_members we need a list of dictionaries containing u_id, first name and last name # {"u_id": [], "name_first": "", "name_last": ""} channel = database.get_channel(channel_id) members = database.get_channel_data(channel_id) details["name"] = channel["name"] for user_id in members["owner_ids"]: owner_id = user_id user_data = database.get_user_data(owner_id) name_first = user_data["name_first"] name_last = user_data["name_last"] profile_img_url = user_data['profile_img_url'] details["owner_members"].append({"u_id": owner_id, "name_first": name_first, "name_last": name_last, "profile_img_url": profile_img_url}) for user_id in members["member_ids"]: member_id = user_id user_data = database.get_user_data(member_id) name_first = user_data["name_first"] name_last = user_data["name_last"] profile_img_url = user_data['profile_img_url'] details["all_members"].append({"u_id": member_id, "name_first": name_first, "name_last": name_last, "profile_img_url": profile_img_url}) return details
def handle_data(): speed = request.form['speed'] user_id = session[DISCORD_ID] user_data = database.get_user_data(user_id) if user_data: min_speed = user_data.min_speed if not min_speed: database.store_settings_data(user_id, min_speed=0) if speed < min_speed: bot.client.punish(user_data)
def handle_pair(): pair_id = request.form[PAIR_ID] user_id = database.get_user_id_from_pair_id(pair_id) if user_id is not None: database.delete_pair_id(pair_id) user_data = database.get_user_data(user_id) session[DISCORD_ID] = user_id session[DISCORD_NAME] = user_data.user_name else: abort(401, description="Invalid or expired pair code")
def show_user(username): try: user_data = [[d[2], d[3], str(d[4])] for d in database.get_user_data(username)] return render_template("user.html", username=username, data=json.dumps(user_data)) except Exception as e: print(e) return "An unexpected error has occurred, please try again later", 500
def start_session(bot, update): user_id = get_user_id(update) user_score_delta = get_user_data(user_id)['score'] * -1 update_user_score(user_id, user_score_delta) custom_keyboard = [['Начать викторину']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.send_message(chat_id=update.message.chat_id, text="Привет! Я бот для викторин", reply_markup=reply_markup) return WAIT_FOR_CHOISE
def send_right_answer(bot, update): user_id = get_user_id(update) question_id = get_user_data(user_id)['last_asked_question'] answer = get_right_answer(quiz_content, question_id) custom_keyboard = [['Новый вопрос', 'Мой счет']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.send_message(chat_id=update.message.chat_id, text=f'Правильный ответ: {answer}', reply_markup=reply_markup) return WAIT_FOR_CHOISE
def send_user_score(bot, update): user_id = get_user_id(update) score = get_user_data(user_id)['score'] custom_keyboard = [['Новый вопрос']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.send_message(chat_id=update.message.chat_id, text=f'Текущий счет: {score}', reply_markup=reply_markup) return WAIT_FOR_CHOISE
def user_profile_setemail(token, email): """ Given input for email sets user's email if valid and not taken """ users = database.get_users() for user in users: if user['email'] is email: raise error.InputError(description="This email is already taken") u_id = database.get_current_user(token) user = database.get_user_data(u_id) user['email'] = email database.set_user_data(user)
def call_bot(channel_id): """ Bot is registered if not a user. Bot is logged in if not logged in. Bot joins the channel if not a member of the channel. """ if database.get_user_data(-1) is None: register_bot() elif database.get_token_from_user(-1) is None: login_bot() channel_data = database.get_channel_data(channel_id) if -1 not in channel_data['member_ids']: channel.channel_join(BOT_TOKEN, channel_id) return {"bot_id": -1}
def user_profile_sethandle(token, handle_str): """ given input for a handle name set user's handle """ if (len(handle_str) > 20 or len(handle_str) < 2): raise error.InputError( description="Handle is not within 2-20 characters") users = database.get_users() for user in users: if user['handle_str'] is handle_str: raise error.InputError(description="Handle is already taken") u_id = database.get_current_user(token) user = database.get_user_data(u_id) user['handle_str'] = handle_str database.set_user_data(user)
def user_profile_uploadphoto(token, img_url, x_start, y_start, x_end, y_end): """ given url of image on the internet, crops it within bounds. """ # pylint: disable=too-many-arguments # This pylint warning is supressed because the function requires 6 arguments # Get the image from img_url and check if HTTP status of 200 returned try: req = urllib.request.Request(img_url, headers={'User-Agent': 'Mozilla/5.0'}) response = urllib.request.urlopen(req) except: raise error.InputError( description="The image could not be opened from the given url") # Open the image, check if x and y are within dimensions of the image img = Image.open(response) width, height = img.size if x_start < 0 or y_start < 0 or x_end > width or y_end > height: raise error.InputError( description="Bounds given exceed the dimensions of the image") # Check if image type if a JPG if img.format != "JPEG": raise error.InputError(description="Image given is not of JPG type") # Crop the image to the correct dimensions img = img.crop((x_start, y_start, x_end, y_end)) # Get u_id from token u_id = database.get_current_user(token) img_path = os.path.join(os.path.dirname(__file__), f"static/{u_id}.jpg") # Save the image in the static directory # image saved as {u_id}.jpg img.save(img_path) # serve image from file profile_img_url = url_for('static', filename=f"{u_id}.jpg", _external=True) # Add profile_img_url to database user = database.get_user_data(u_id) user['profile_img_url'] = profile_img_url database.set_user_data(user) return {}
def reg(): e = None if request.method == 'POST': app.logger.info("login POST request: %s", request) app.logger.info("login POST request: %s %s", request.form['email'], request.form['password']) user_data = database.get_user_data(None, request.form['email']) if user_data: e = 'Email already exists' else: if database.put_user_data(request.form['email'], request.form['username'], request.form['password']): return redirect(url_for('index')) data = {'e': e} return render_template('reg.html', data=data)
def check_answer(event, vk_api): user_id = get_user_id(event) question_id = get_user_data(user_id)['last_asked_question'] if is_answer_correct(quiz_content, question_id, event.text): reply_text = 'Правильно! Поздравляю! Для следующего вопроса нажми «Новый вопрос»' update_user_score(user_id, 1) keyboard = get_message_keyboard(['Новый вопрос', 'Мой счет']) else: reply_text = 'Неправильно... Попробуешь ещё раз?' keyboard = get_message_keyboard(['Сдаться']) vk_api.messages.send(user_id=event.user_id, keyboard=keyboard.get_keyboard(), message=reply_text, random_id=random.randint(1, 1000))
def user_profile_setname(token, name_first, name_last): """ Given input for first and last name sets user's firtname and lastname if within character limit """ if (len(name_first) > 50 or name_first == ""): raise error.InputError( description="First name is not within 1-50 characters") if (len(name_last) > 50 or name_last == ""): raise error.InputError( description="Last name is not within 1-50 characters") u_id = database.get_current_user(token) user = database.get_user_data(u_id) user['name_first'] = name_first user['name_last'] = name_last database.set_user_data(user)
def wrapper_func(*args, **kwargs): """ Wrapper function """ try: uid_arg_index = argspec.args.index("u_id") target_user = database.get_user_data(args[uid_arg_index]) # Check the u_id is valid. if target_user is None: # u_id is invalid raise error.InputError( description="u_id does not refer to a valid user") else: return func(*args, **kwargs) except ValueError: print("\033[93m" + "WARNING: u_id arg not found - running function " + f"{func.__name__} without u_id check." + "\033[0m") return func(*args, **kwargs)
def check_answer(bot, update): user_id = get_user_id(update) question_id = get_user_data(user_id)['last_asked_question'] if is_answer_correct(quiz_content, question_id, update.message.text): reply_text = 'Правильно! Поздравляю! Для следующего вопроса нажми «Новый вопрос»' update_user_score(user_id, 1) custom_keyboard = [['Новый вопрос', 'Мой счет']] next_state = WAIT_FOR_CHOISE else: reply_text = 'Неправильно... Попробуешь ещё раз?' custom_keyboard = [['Сдаться']] next_state = WAIT_FOR_ANSWER reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.send_message(chat_id=update.message.chat_id, text=reply_text, reply_markup=reply_markup) return next_state
def get_user_data(identifier): user_data = db.get_user_data(identifier) if user_data != "Invalid": user_name = user_data[0] e_mail = user_data[1] country = user_data[2] city = user_data[3] followers = user_data[4] location = user_data[5] avatar_image = user_data[6] return jsonify({"response": ["Success"], "user_name": [user_name], "e_mail": [e_mail], "country": [country], "city": [city], "followers": [followers], "location": [location], "avatar_image": [avatar_image]}) else: return jsonify({"response": ["Failure"]})
def newpost(): if not is_admin_logged(): return redirect('/') if request.method == 'GET': return render_page("newpost.html") else: title = request.form['title'] content = request.form['content'] user_data = database.get_user_data(get_user()) if (title == '' or content == ''): return render_page("newpost.html", error="Need both title and content", title=title, content=content) database.create_post(title, content, user_data[3]) return redirect('/')
def render_page(file, lang="en/", **args): """Renders the given page. Performs functionality every page needs, checks whether an user is logged in and if the user is an admin """ user = get_user() admin = False if user != None: user_data = database.get_user_data(user) args['login'] = user if (user_data[5] >= variables.admin_privilige): args['admin'] = True admin = True resp = make_response(render_template(lang + file, **args)) if user == None: resp.set_cookie('user', '', expires=0) resp.set_cookie('password_hash', '', expires=0) return resp
def get_user_data(identifier): user_data = db.get_user_data(identifier) if user_data != "Invalid": user_name = user_data[0] e_mail = user_data[1] country = user_data[2] city = user_data[3] followers = user_data[4] location = user_data[5] avatar_image = user_data[6] return {"response": "Success", "user_name": user_name, "e_mail": e_mail, "country": country, "city": city, "followers": followers, "location": location, "avatar_image": avatar_image} else: return {"response": "Failure"}
def get_user_data(identifier): user_data = db.get_user_data(identifier) if user_data != "Invalid": user_name = user_data[0] e_mail = user_data[1] country = user_data[2] city = user_data[3] followers = user_data[4] location = user_data[5] avatar_image = user_data[6] return jsonify( { "response": ["Success"], "user_name": [user_name], "e_mail": [e_mail], "country": [country], "city": [city], "followers": [followers], "location": [location], "avatar_image": [avatar_image], } ) else: return jsonify({"response": ["Failure"]})