def get_all_users(): results = database.get_all_users() processed = [] for result in results: n = (result.name, str(result.id), result.score) processed.append(n) return dumps(processed)
def commit_create_user(self, instance): username = self.username_input.text.strip() password = self.password_input.text.strip() all_users_created = database.get_all_users() if username == '' or password == '': self.remove_errors() self.layout.add_widget(self.error_label) return elif username in all_users_created: self.remove_errors() self.layout.add_widget(self.already_created) return if self.preset_attributes: for label in self.preset_attributes: try: attr_fields = database.split_attributes(label.text) attr = Attribute(attr_fields[0], attr_fields[1], attr_fields[2], label.category) self.attributes.append(attr) except: self.remove_errors() self.layout.add_widget(self.improperly_filled) self.attributes = [] return new_user = database.add_user(username, password) for attr in self.attributes: database.modify_user_attr(username, attr) self.attributes = [] self.dismiss() manager.menu.show_users()
def in_database(user_id): is_exist = False for i in database.get_all_users(): if user_id in i: is_exist = True break return is_exist
def probe_users(self): all_users = get_all_users() for user in all_users: try: jid = user[0] except (KeyError, ValueError, IndexError) as e: logger.error('%s while sending probes' % e) continue self.send(Probe(TRANSPORT_ID, jid))
def add_user_dropdown(self, instance): all_users = database.get_all_users() current_group = database.get_group_members(manager.CURRENT_GROUP) members = [] for member in current_group: members.append(member[0]) for user in all_users: if user not in members: self.num_not_in_group += 1 user_tog = UserToggle(user) self.dropdown.add_widget(user_tog)
def ask_user_id(): # get lists from cursor users = database.get_all_users() # decompose list to get id and name of each element and then print them for _id, name in users: print(f"{_id}) {name}") # check that the input is not letters and it is within the numbers of users message_select_user = "******" return check_id(message_select_user, users)
def select_user(): # get lists from cursor users = database.get_all_users() # in case no user has been created, go to first menu while not users: print("No existing user! Add one user before proceeding!") return # if table users has entries return ask_user_id()
def calculate_total_score(): users = database.get_all_users() for user in users: score_result = database.average_tweet_score(user["id"]) average_tweet_score = score_result["AverageTweetScore"] total_score = (user["score"] + average_tweet_score) / 2 database.update_user_total_score(user["id"], total_score)
def validate_startup(override_first_time_check=False): users = database.get_all_users() if users and not override_first_time_check: return if not users: print("No users found on the system. This is likely the first time the application has been started.") print("Enter new user details below.") username = input("Input username: "******"Input password: ") util.create_user(username, password)
def log_in(): nick_name = input("Enter your nickname: ") password = input("Enter your password: "******"Login was successfull") return user_id else: print("Login failed") return user_id
def love(request): number_of_task = int(request.GET.get('cron')) all_users = database.get_all_users() all_users = sorted(all_users, key=lambda x: x[0]) slice_number = len(all_users) / 5 if number_of_task != 4: users = all_users[number_of_task * slice_number:(number_of_task + 1) * slice_number] elif number_of_task == 4: users = all_users[number_of_task * slice_number:len(all_users)] for user in users: loved_songs = scrobble.xiami_loved(user) if loved_songs: scrobble.lastfm_loved(loved_songs, user) return HttpResponse('Loved!')
def choose_user(): users = database.get_all_users() print("Select a user") print("-------------") for index, user in enumerate(users): print("{} - {}".format(index + 1, user.username)) user_choice = input("Option: ") if not user_choice or not user_choice.isdigit() or ( user_choice.isdigit() and (int(user_choice) < 1 or int(user_choice) > len(users))): print("") print("***************") print("Invalid choice!") print("***************") print("") return else: return users[int(user_choice) - 1]
def upload_file(self, instance, x, y): #try: print("Loading users...") users_from_file = fileIO.load_users(instance.selection[0]) print("Users Loaded") for user in users_from_file: already_exists = False if user.name in database.get_all_users(): already_exists = True if already_exists: continue has_been_added = False for key, value in user.attributes.items(): if key[0] == 'Cleartext-Password': database.add_user(user.name, value) has_been_added = True elif key[0] == 'Crypt-Password' in user.attributes: database.add_user(user.name, value, True) has_been_added = True if not has_been_added: #add prompt to add password database.add_user(user.name, '*None*') for key, value in user.attributes.items(): if key[0] != 'Crypt-Password' and key[0] != 'Cleartext-Password': user_att = database.Attribute(key[0], key[1], value, key[2]) database.add_user_attr(user.name, user_att) #except SyntaxError: ''' for child in self.layout.children: if type(child) == Label and child.text == "Improperly formatted user file": self.layout.remove_widget(child) self.layout.add_widget(Label(text="Improperly formatted user file", color=(1,0,0,1), pos_hint={'center_x':.5, 'top':1.68})) return ''' self.dismiss() manager.menu.show_users()
def calculate_user_score(): users = database.get_all_users() for user in users: user_score = 100 #friends less than followers if user["friends"] < user["followers"]: user_score -= 10 #Account less than 50 days old dt = user["accountcreated"] parsed = datetime.strptime(dt, "%Y-%m-%d %H:%M:%S") now = datetime.today() diff = now - parsed #age of account if diff.days < 50: user_score -= 14 #based on the findings of research #average user tweets per day avg_result = database.average_tweets_per_day(user["id"]) tweets_per_day = avg_result["AvgTweetsPerDay"] if tweets_per_day > 20: user_score -= 30 #verified status if user["verified"] == 1: user_score += 50 #if user_score exceeeds 100, set score to 100 if user_score > 100: user_score = 100 database.update_user_score(user["id"], user_score) return user_score
def results(): if "logged_in" in session and session['logged_in']: if request.method == 'POST': a = None user_search = None results = [] if request.form['search_type'] == "users": number_of_photos = [] least_p = [] most_p = [] has_photos = [] all_users = database.get_all_users() for i in range(len(all_users)): found = search(request.form['search'].lower(), all_users[i].username.lower()) if found == True: if all_users[i] not in results: results.append(all_users[i]) number_of_photos.append( len( database.get_photos_by_user_id( all_users[i].id))) prices = [] if number_of_photos[-1] == 0: has_photos.append(False) else: has_photos.append(True) for j in database.get_photos_by_user_id( all_users[i].id): converted_p = converter.convert( j.price, j.currency, 'USD') prices.append(converted_p) least_p.append(min(prices)) most_p.append(max(prices)) # results = database.get_users(request.form['search']) user_search = True if results == []: a = True return render_template("searchpage.html", results=results, a=a, user_search=user_search, search=True, number_of_photos=number_of_photos, least_p=least_p, most_p=most_p, has_photos=has_photos) if request.form['search_type'] == "images": # path = database.get_photo_id_by_keywords(request.form['search']) # print(path) # for i in path: # results.append(database.get_photo_by_id(i.pic_id)) all_keywords = database.get_all_keywords() for i in range(len(all_keywords)): found = search(request.form['search'].lower(), all_keywords[i].keyword.lower()) if found == True: photo = database.get_photo_by_id( all_keywords[i].pic_id) if photo not in results: results.append(photo) user_search = False if results == []: a = True return render_template("searchpage.html", results=results, a=a, user_search=user_search, search=True) else: return redirect(url_for("home_page")) else: return render_template("searchpage.html") else: return redirect(url_for("home_page"))
def scoreboard(): return render_template('scoreboard.html', title='Scoreboard', all_users=sorted(get_all_users(), key=lambda x: len(x['eggs']), reverse=True))
def text_content_handler(message): cid = message.chat.id uid = message.from_user.id # Обработка первой регистрации пользователя в боте if uid in READY_TO_REGISTER: if 'name' not in READY_TO_REGISTER[uid]: READY_TO_REGISTER[uid]['name'] = message.text # Попытка получения аватара пользователя user_avatars = bot.get_user_profile_photos(uid) if len(user_avatars.photos) > 0: avatar = user_avatars.photos[0][-1] file_info = bot.get_file(avatar.file_id) downloaded_file = bot.download_file(file_info.file_path) photo_path = '{!s}{!s}.jpg'.format(config.AVARATRS_PATH, uid) with open(photo_path, 'wb') as new_file: new_file.write(downloaded_file) READY_TO_REGISTER[uid]['avatar'] = photo_path markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) cm = database.get_communities() communities = [x['name'] for x in cm] for x in communities: markup.add(x) markup.add('Другое') return bot.send_message(cid, texts.register_travel_type, reply_markup=markup) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True, row_width=1) markup.row('Не сейчас') return bot.send_message(cid, texts.add_avatar_text, reply_markup=markup) elif 'avatar' not in READY_TO_REGISTER[uid]: if message.text == 'Не сейчас': READY_TO_REGISTER[uid]['avatar'] = 'default.jpg' markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) cm = database.get_communities() communities = [x['name'] for x in cm] for x in communities: markup.add(x) markup.add('Другое') return bot.send_message(cid, texts.register_travel_type, reply_markup=markup) return bot.send_message(cid, texts.error_avatar_text) elif 'community' not in READY_TO_REGISTER[uid]: if message.text == 'Другое': keyboard = types.InlineKeyboardMarkup() keyboard.add( types.InlineKeyboardButton('Узнать, кто такие сансерферы', url='https://sunsurfers.ru')) keyboard.add( types.InlineKeyboardButton('Узнать, кто такие сменщики', url='https://smenastation.com')) return bot.send_message(cid, texts.community_more_info_text, reply_markup=keyboard) cm = database.get_communities() communities = [x['name'] for x in cm] if message.text not in communities: return bot.send_message(cid, texts.error_button_text) READY_TO_REGISTER[uid]['community'] = message.text text = 'Вы выбрали сообщество {!s}'.format( READY_TO_REGISTER[uid]['community']) markup = types.ReplyKeyboardRemove() bot.send_message(cid, text, reply_markup=markup) for x in cm: if message.text == x['name']: READY_TO_REGISTER[uid]['community_id'] = x['id'] # Проверка на присутсивие в white листе airtables if message.from_user.username: if database.is_user_in_whitelist('@{!s}'.format( message.from_user.username)): user = database.add_user( None, READY_TO_REGISTER[uid]['name'], READY_TO_REGISTER[uid]['avatar'], 1, None, uid, None, READY_TO_REGISTER[uid]['community_id']) del READY_TO_REGISTER[uid] return bot.send_message(uid, texts.success_confirm_anket_text) # На данный момент нет пероприятияй для Смены, поэтому опускаем этот шаг if READY_TO_REGISTER[uid]['community'] == 'Смена': READY_TO_REGISTER[uid]['events'] = '' READY_TO_REGISTER[uid]['confirm_people'] = '' user = database.add_user( None, READY_TO_REGISTER[uid]['name'], READY_TO_REGISTER[uid]['avatar'], 0, None, uid, None, READY_TO_REGISTER[uid]['community_id']) # Отправить анкету в канал админов channel_text = 'Новая заявка №{!s}\n\n<a href="tg://user?id={!s}">Ссылка</a>\n\nИмя: {!s}\nСообщество: {!s}\nМероприятия: {!s}\nДоверенные люди: {!s}'.format( user['id'], uid, READY_TO_REGISTER[uid]['name'], READY_TO_REGISTER[uid]['community'], READY_TO_REGISTER[uid]['events'], READY_TO_REGISTER[uid]['confirm_people']) keyboard = types.InlineKeyboardMarkup() keyboard.add( types.InlineKeyboardButton( '✅ Подтвердить', callback_data='confirmanket_{!s}_{!s}'.format( user['id'], user['telegram']))) keyboard.add( types.InlineKeyboardButton( '❌ Отклонить', callback_data='refuseanket_{!s}_{!s}'.format( user['id'], user['telegram']))) bot.send_photo(config.admin_channel_id, open(READY_TO_REGISTER[uid]['avatar'], 'rb'), caption=channel_text, reply_markup=keyboard, parse_mode='HTML') logging.info('User {!s} anket sended to channel'.format(cid)) del READY_TO_REGISTER[uid] markup = types.ReplyKeyboardRemove() return bot.send_message(cid, texts.register_complete, reply_markup=markup) READY_TO_REGISTER[uid]['event_ids'] = [] READY_TO_REGISTER[uid]['events_text'] = '' typeofevents = database.get_all_typeofevents() keyboard = types.InlineKeyboardMarkup() for x in typeofevents: keyboard.add( types.InlineKeyboardButton( text=x['name'], callback_data='selecttypeofevent_{!s}'.format( x['id']))) return bot.send_message(cid, texts.register_type_events_question_text, reply_markup=keyboard) elif 'events' not in READY_TO_REGISTER[uid]: if len(READY_TO_REGISTER[uid]['event_ids']) == 0: text = 'Выберите хотя бы одно мероприятие' return bot.send_message(cid, text) READY_TO_REGISTER[uid]['events'] = message.text return bot.send_message(cid, texts.register_confirm_people_text) elif 'confirm_people' not in READY_TO_REGISTER[uid]: READY_TO_REGISTER[uid]['confirm_people'] = message.text user = database.add_user(None, READY_TO_REGISTER[uid]['name'], READY_TO_REGISTER[uid]['avatar'], 0, None, uid, None, READY_TO_REGISTER[uid]['community_id']) for x in READY_TO_REGISTER[uid]['event_ids']: database.add_user_event(user['id'], x) # Отправить анкету в канал админов channel_text = 'Новая заявка №{!s}\n\n<a href="tg://user?id={!s}">Ссылка</a>\n\nИмя: {!s}\nСообщество: {!s}\nМероприятия: {!s}\nДоверенные люди: {!s}'.format( user['id'], uid, READY_TO_REGISTER[uid]['name'], READY_TO_REGISTER[uid]['community'], READY_TO_REGISTER[uid]['events_text'], READY_TO_REGISTER[uid]['confirm_people']) keyboard = types.InlineKeyboardMarkup() keyboard.add( types.InlineKeyboardButton( '✅ Подтвердить', callback_data='confirmanket_{!s}_{!s}'.format( user['id'], user['telegram']))) keyboard.add( types.InlineKeyboardButton( '❌ Отклонить', callback_data='refuseanket_{!s}_{!s}'.format( user['id'], user['telegram']))) bot.send_photo(config.admin_channel_id, open(READY_TO_REGISTER[uid]['avatar'], 'rb'), caption=channel_text, reply_markup=keyboard, parse_mode='HTML') logging.info('User {!s} anket sended to channel'.format(cid)) del READY_TO_REGISTER[uid] markup = types.ReplyKeyboardRemove() return bot.send_message(cid, texts.register_complete, reply_markup=markup) # Проверка на регистрацию прользователя user = database.get_user(uid) if not user: markup = types.ReplyKeyboardRemove() return bot.send_message(cid, texts.register_invite_text, reply_markup=markup) # Обработка отмены действий пользователя if message.text == '❌ Отменить': if uid in READY_TO_ADD_ABOUT: del READY_TO_ADD_ABOUT[uid] bot.send_message(cid, texts.cancel_text) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.main_markup: markup.row(x) return bot.send_message(cid, texts.main_text, reply_markup=markup) # Обработка отмены действий админа if message.text == '❌ Отмена': if uid in config.ADMINS: if uid in READY_TO_ADMIN_EMAIL: del READY_TO_ADMIN_EMAIL[uid] bot.send_message(cid, texts.cancel_text) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.admin_markup: markup.add(x) return bot.send_message(cid, texts.admin_panel_greet_text, reply_markup=markup) # Обработка действий админа if uid in READY_TO_ADMIN_EMAIL: if 'text' not in READY_TO_ADMIN_EMAIL[uid]: READY_TO_ADMIN_EMAIL[uid]['text'] = message.text logging.info('Admin message email') users = database.get_all_users() for x in users: try: bot.send_message(x['telegram'], READY_TO_ADMIN_EMAIL[uid]['text']) except Exception as e: print(e) continue del READY_TO_ADMIN_EMAIL[uid] bot.send_message(cid, texts.success_send_email_admin_text) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.admin_markup: markup.add(x) return bot.send_message(cid, texts.admin_panel_greet_text, reply_markup=markup) # Обработка добавления about if uid in READY_TO_ADD_ABOUT: if 'text' not in READY_TO_ADD_ABOUT[uid]: READY_TO_ADD_ABOUT[uid]['text'] = message.text # Обвновить данные о пользователе в базе user = database.get_user(uid) database.update_user(user['id'], user['email'], user['name'], user['photo'], user['is_host'], READY_TO_ADD_ABOUT[uid]['text'], user['telegram'], user['insta'], user['community']) del READY_TO_ADD_ABOUT[uid] bot.send_message(cid, texts.about_updated) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.setting_markup: markup.row(x) markup.row('↪️ В главное меню') return bot.send_message(cid, texts.settings_text, reply_markup=markup) # Обработка добавления insta if uid in READY_TO_ADD_INSTA: if 'text' not in READY_TO_ADD_INSTA[uid]: READY_TO_ADD_INSTA[uid]['text'] = message.text # Обвновить данные о пользователе в базе user = database.get_user(uid) database.update_user(user['id'], user['email'], user['name'], user['photo'], user['is_host'], user['about'], user['telegram'], READY_TO_ADD_INSTA[uid]['text'], user['community']) del READY_TO_ADD_INSTA[uid] bot.send_message(cid, texts.insta_updated) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.setting_markup: markup.row(x) markup.row('↪️ В главное меню') return bot.send_message(cid, texts.settings_text, reply_markup=markup) # Обработка админ-панели if uid in config.ADMINS: if message.text == '📩 Создать рассылку': READY_TO_ADMIN_EMAIL[uid] = {} markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) markup.add('❌ Отмена') return bot.send_message(cid, texts.ready_send_email_admin_text, reply_markup=markup) # Обработка основной клавиатуры пользователя if message.text == '📍 Поделиться геолокацией': return bot.send_message(cid, 'В разработке...') elif message.text == '🗺 Посмотреть геолокации пользователей': return bot.send_message(cid, 'В разработке...') elif message.text == '⚙️ Настройки': markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.setting_markup: markup.row(x) markup.row('↪️ В главное меню') return bot.send_message(cid, texts.settings_text, reply_markup=markup) # Возврат в главное меню if message.text == '↪️ В главное меню': markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) for x in config.main_markup: markup.row(x) return bot.send_message(cid, texts.main_text, reply_markup=markup) # Обработка меню настроек if message.text == 'ℹ️ Рассказать о себе и своих интересах': READY_TO_ADD_ABOUT[uid] = {} markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) markup.row('❌ Отменить') about_text = '' user = database.get_user(uid) if user['about']: about_text = user['about'] text = '{!s}\n\nВаши интересы на данный момент: {!s}'.format( texts.add_about, about_text) return bot.send_message(cid, text, reply_markup=markup) elif message.text == '🎇 Дополнить мероприятия': typeofevents = database.get_all_typeofevents() keyboard = types.InlineKeyboardMarkup() for x in typeofevents: keyboard.add( types.InlineKeyboardButton( text=x['name'], callback_data='addselecttypeofevent_{!s}'.format(x['id']))) return bot.send_message(cid, texts.register_type_events_question_text, reply_markup=keyboard) elif message.text == '📱 Добавить ссылку на инстаграм': READY_TO_ADD_INSTA[uid] = {} markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1) markup.row('❌ Отменить') insta_text = '' user = database.get_user(uid) if user['insta']: insta_text = user['insta'] text = '{!s}\n\nВаш инстаграм на данный момент: {!s}'.format( texts.add_about, insta_text) return bot.send_message(cid, text, reply_markup=markup)
def get_all_users(self): return db.get_all_users(self.db_cursor)
def userspos(): if request.method == "POST": json = util.getJson(request) return JSON.dumps(database.get_other_users_pos(json["token"])) else: return JSON.dumps(database.get_all_users())
def add_group_dropdown(self): all_users = database.get_all_users() for user in all_users: user_tog = UserToggle(user) self.dropdown.add_widget(user_tog)
def view_all_users(): user_doc = database.get_all_users() return user_doc
line = line.strip("\n") line = line.split(",") print("%s\t|%s\t|%s\t|%s\t|%s" % (line[0].center(30), line[1].center(30), line[2].center(30), line[3].center(30), line[4].center(30))) time.sleep(UPDATE_TIME) btc_price = btc.get_price() eth_price = eth.get_price() last_prices = log.get_last_line() last_prices = last_prices.split(",") btc_last_price = float(last_prices[1]) eth_last_price = float(last_prices[2]) btc_delta = (btc_last_price - btc_price) / btc_last_price * 100 eth_delta = (eth_last_price - eth_price) / eth_last_price * 100 log.log([btc_price, eth_price], [btc_delta, eth_delta]) for user in get_all_users(): telegram_id = user[0] th_sup_btc = float(user[4]) ack_btc = int(user[1]) ack_eth = int(user[2]) th_inf_btc = float(user[5]) th_sup_eth = float(user[6]) th_inf_eth = float(user[7]) if (btc_last_price > th_sup_btc and ack_btc == 0 and th_sup_btc > 0): update_queue( telegram_id, "Se ha superado el limite superior para BTC!!!\nCotizacion actual: " + str(btc_last_price) + "\nLimite superior = " + str(th_sup_btc) + "\nEscriba btc_ok para eliminar la alarma") elif (btc_last_price < th_inf_btc and ack_btc == 0 and th_inf_btc > 0): update_queue(