def test_create_role(self): """Create a role for users.""" create_role('tester') t = Role.select().where(Role.role_name == 'tester') d = Role.delete().where(Role.role_name == 'tester') d.execute() self.assertEqual(str(t), ("<class 'models.Role'> SELECT `t1`.`id`," " `t1`.`role_name` FROM `role` AS t1 " "WHERE (`t1`.`role_name` = %s) ['tester']"))
def switch_role(): """ Switch role view and logic Switch role based on assigned roles and add to session """ u = User.from_object(session['user']) roles = u.assigned_roles def redirect_after_switch(role_, roles_): # check if user has selected role for r in roles_: if role_ == r.role: session['active_role'] = model_to_dict(role_) # ADMIN if role_.role == AuthRoleType.ADMIN.value: flash( 'U bent nu actief als: %s' % AuthRoleType.ADMIN.value.upper(), AlertType.WARNING.value) return redirect(url_for('admin.index')) # CLIENT elif role_.role == AuthRoleType.CLIENT.value: flash( 'U bent nu actief als: %s' % AuthRoleType.CLIENT.value.upper(), AlertType.WARNING.value) return redirect('/client/') else: return None if request.method == 'POST': role_value = request.form['role'] if not role_value: flash('Kiez een rol', AlertType.WARNING.value) return redirect(url_for('auth.switch_role')) role = Role.select().where(Role.id == role_value) if not role.exists(): flash('Rol bestaat niet', AlertType.WARNING.value) return redirect(url_for('auth.switch_role')) role = role.get() response = redirect_after_switch(role, roles) if response is None: flash('U heeft de gekozen rol niet', AlertType.WARNING.value) return redirect(url_for('auth.switch_role')) return response if len(roles) is 0: flash('U heeft geen rollen', AlertType.WARNING.value) return redirect(url_for('auth.logout')) elif len(roles) is 1: return redirect_after_switch(roles[0].role, roles) return render_template('pages/switch_role.html', roles=roles)
def get_name_of_role(self, ctx) -> str: try: dbhandle.connect(reuse_if_open=True) role = Role.select().where(Role.role_id == ctx.author.top_role.id)[0] except IndexError: raise commands.CommandError("Профиль пользователя не был создан в БД") except Exception as error: raise commands.CommandError(error) if role: return role.name
def register_user(message): user = User.get_or_none(User.id == message.chat.id) if user is not None: game = Game.get_or_none(Game.user == user) if game is None: send_message(message.chat.id, f"Hi again <b>{user.name}</b>!", reply_markup=keyboards.main) else: text = f"Hi again <b>{user.name}</b>!\n\n" text += ":game_die: Note that you're in the middle of a game." send_message( message.chat.id, text, ) return False send_message(message.chat.id, f"Hi <b>{message.chat.first_name}</b>!", reply_markup=keyboards.main) # tracker and user information Tracker.replace(id=message.chat.id).on_conflict_replace().execute() User.replace( id=message.chat.id, name=message.chat.first_name, username=message.chat.username, ).on_conflict_replace().execute() # default game settings for each user user = User.get(User.id == message.chat.id) GameSettings.insert(user=user).execute() # insert selected roles tracker roles = Role.select().where(Role.is_default == True) data = [] for r in roles: data.append((r, user, False)) RoleSelectionTracker.insert_many(data, fields=[ RoleSelectionTracker.role, RoleSelectionTracker.user, RoleSelectionTracker.checked ]).execute() return True
async def on_message(message): lmsg = None smsg = None if not message.author.bot: if message.content.startswith('cb.'): fields = message.content.split() cmd = fields[0].split('.')[1] await bot.call(cmd, message) return async with lock: if not message.author.bot: server, created = Server.get_or_create(sid=message.server.id) user, created = User.get_or_create(uid=message.author.id) local, created = LocalLevel.get_or_create(user=user, server=server) level, exp = await levelup(server.level, server.experience) try: if level > server.level: # Yay, the server leveled up if server.announce_channel: channel = client.get_channel( f'{server.announce_channel}') smsg = await client.send_message( channel, f"{party} {message.server.name} is now level" f" {level}! {party}") except Exception as e: pass server.level = level server.experience = exp server.save() level, exp = await levelup(user.level, user.experience) user.level = level user.experience = exp user.save() level, exp = await levelup(local.level, local.experience) try: if level > local.level: # User leveled up on the server leaders = LocalLevel.select().where( LocalLevel.server == server).order_by( LocalLevel.level.desc(), LocalLevel.experience.desc()).limit(1) if f"{leaders[0].user.uid}" == message.author.id: leaderboard_roles = Role.select().where( (Role.server == server) & (Role.leaderboard == True)).order_by( Role.awardlevel.desc()) leader_role = discord.utils.get( message.server.roles, id=f'{leaderboard_roles[0].rid}') for member in message.server.members: item = next((i for i in member.roles if i.id == f"{leader_role.id}"), None) if item: await client.remove_roles(member, leader_role) await client.add_roles(message.author, leader_role) try: try: role = Role.get((Role.server == server) & (Role.awardlevel == level)) except Role.DoesNotExist as e: role = None if role: r = discord.utils.get(message.server.roles, id=f'{role.rid}') try: logger.info(f"Adding role {r.name} to " f"{message.author.name}") await client.add_roles(message.author, r) except AttributeError as e: logger.exception("Could not add role") except Role.DoesNotExist as e: logger.exception("Count not find level up reward") except Exception as e: logger.exception("Could not process level up") local.level = level local.experience = exp local.save() await asyncio.sleep(10) if lmsg: await client.delete_message(lmsg) if smsg: await client.delete_message(smsg)
def get_roles(): roles_list = [('', '')] roles = Role.select() for r in roles: roles_list.append((r, r)) return roles_list