def is_admin(ctx): # Don't execute commands in private messages if ctx.guild is None: raise commands.NoPrivateMessage() if "Admin" not in [role.name for role in ctx.author.roles]: raise commands.MissingRole("Admin") return True
async def templates(self, ctx: utils.Context, guild_id: int = None): """ Lists the templates that have been created for this server. """ # See if they're allowed to get from another guild ID if guild_id is not None and guild_id != ctx.guild.id and self.bot.config.get( 'bot_support_role_id') not in ctx.author._roles: raise commands.MissingRole("Bot Support Team") # Grab the templates async with self.bot.database() as db: templates = await db( """SELECT template.template_id, template.name, COUNT(created_profile.*) FROM template LEFT JOIN created_profile ON template.template_id=created_profile.template_id WHERE guild_id=$1 GROUP BY template.template_id""", guild_id or ctx.guild.id) if not templates: return await ctx.send( "There are no created templates for this guild.") return await ctx.send('\n'.join([ f"**{row['name']}** (`{row['template_id']}`, `{row['count']}` created profiles)" for row in templates ]))
async def predicate(ctx): mod_role = discord.utils.get(ctx.author.roles, name="Mod") if await ctx.bot.is_owner(ctx.author) or mod_role is not None: return True raise commands.MissingRole("Mod")
async def predicate(ctx): # Check if command is being used in a DM # if ctx.channel.type is ChannelType.private: raise commands.NoPrivateMessage # Check if guild is setup # strGuildID = str(ctx.guild.id) dbcursor.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'monopolyrun' AND TABLE_NAME = ?", (f'tbl_{strGuildID}', )) lisGuildTable = dbcursor.fetchall() if not lisGuildTable: raise MonopolyRunError.DatabaseTableNotFound # Check if the user has a team role # lismyRoles = [r.name for r in ctx.author.roles] lismyRoles.reverse() r = re.compile("team.*") if not list(filter(r.match, lismyRoles)): raise commands.MissingRole("team?") # Check if user is using the command in their team channel # if re.search('team', ctx.channel.name) is None: raise commands.ChannelNotFound("team?") x = str(ctx.channel.name) y = str(next(filter(r.match, lismyRoles))) if x != y: raise MonopolyRunError.NotInTeamChannel(next(filter(r.match, lismyRoles)), ctx.channel.name) return True
async def predicate(ctx): if ctx.guild.get_role(config.can_modify_economy ).position <= ctx.author.top_role.position: return True else: raise commands.MissingRole( ctx.guild.get_role(config.can_modify_economy).name)
async def on_member_join(self, member): now = datetime.now(timezone(timedelta(hours=3))) try: dbhandle.connect(reuse_if_open=True) User.insert(discord_id=member.id) \ .on_conflict_ignore() \ .execute() role = member.guild.get_role(config.get('ROLES_ID', 'user')) if not role: raise commands.MissingRole("Помошник машиниста") await member.add_roles(role) except discord.HTTPException as error: raise commands.CommandError(error) except Exception as error: raise commands.CommandError(error) finally: dbhandle.close() embed = discord.Embed( colour=discord.Colour.dark_green(), title="Новый пользователь", description=f"На сервер зашел {member.name}#{member.discriminator}" ) embed.set_image(url=member.avatar_url) embed.set_footer(text=f"Дата входа: {now.strftime('%d.%m.%Y %H:%M')}") channel = discord.utils.get(self.client.get_all_channels(), name=config.get("CHANNELS", "logging")) await channel.send(embed=embed)
def funTeamRole(ctx): lisUserRoles = [r.name for r in ctx.author.roles] lisUserRoles.reverse() r = re.compile("team.*") if not list(filter(r.match, lisUserRoles)): raise commands.MissingRole("team?") return utils.get(ctx.author.roles, name=next(filter(r.match, lisUserRoles)))
async def cog_check(self, ctx): required_role = discord.utils.get(ctx.guild.roles, name=self.bot.config['trusted_role']) print(f"Checking role {required_role} against user's roles.") if required_role in ctx.author.roles: return True else: raise commands.MissingRole(required_role) return False
def mod_role_check(context): if context.author.id in context.bot.owner_ids: return True mod_role = context.bot.get_mod_role(context.guild) if mod_role is None: return False else: if mod_role in context.author.roles: return True raise commands.MissingRole(mod_role)
async def predicate(context): if context.author.id in context.bot.owner_ids: return True admin_role = context.bot.get_admin_role(context.guild) cmd_role = context.bot.get_cmd_role(context.guild) if admin_role is None and cmd_role is None: return False else: if admin_role in context.author.roles or cmd_role in context.author.roles: return True raise commands.MissingRole(cmd_role)
async def predicate(ctx): if ctx.guild is None: raise commands.NoPrivateMessage if await ctx.bot.is_owner(ctx.author): return True if ctx.author.guild_permissions.administrator: return True role = discord.utils.get(ctx.author.roles, id=763274450107367425) if role is not None: return True raise commands.MissingRole('Professor')
async def cog_check(self, ctx): if await ctx.bot.is_owner(ctx.author): return True elif isinstance(ctx.channel, discord.abc.GuildChannel): if self.is_mod(ctx.author.guild_permissions): return True else: for guild in ctx.author.mutual_guilds: perms = guild.get_member(ctx.author.id).guild_permissions if self.is_mod(perms): return True raise commands.MissingRole("admin")
def predicate(ctx): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise commands.NoPrivateMessage() if config.DEMOCRACIV_GUILD_ID != ctx.guild.id: raise exceptions.NotDemocracivGuildError() found = discord.utils.get(ctx.author.roles, id=role.value) if found is None: raise commands.MissingRole(role.printable_name) return True
def predicate(ctx): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise commands.NoPrivateMessage() if isinstance(item, int): role = discord.utils.get(ctx.guild.roles, id=item) else: role = discord.utils.get(ctx.guild.roles, name=item) if role is None: raise commands.MissingRole(item) return role <= ctx.author.top_role
async def colour(self, ctx, new_colour: convert_colour): guild_doc = await self.colour_guilds.find_one({"_id": ctx.guild.id}) if guild_doc is None: await ctx.reply(embed=self.bot.create_error_embed("This guild does not have colour roles enabled! " "Get a staff member to do !enable_colour_change " "to enable it!")) return minimum_role_id = guild_doc.get("minimum_role_id", None) if minimum_role_id is not None: minimum_role = ctx.guild.get_role(minimum_role_id) if minimum_role is None: await ctx.reply(embed=self.bot.create_error_embed("This guild's minimum_role appears to have been " "deleted. Get a staff member to run " "!enable_colour_change")) return if ctx.author.top_role < minimum_role: raise commands.MissingRole(minimum_role) user_doc = await self.colour_roles.find_one({"_id": {"user_id": ctx.author.id, "guild_id": ctx.guild.id}}) changing_role = None if user_doc is not None: changing_role = ctx.guild.get_role(user_doc.get("role_id")) else: user_doc = {"_id": {"user_id": ctx.author.id, "guild_id": ctx.guild.id}} done = False if changing_role is None: for role in ctx.guild.roles: if role.name == str(ctx.author.id): changing_role = role if changing_role is None: ideal_position = 0 for role in ctx.author.roles: if role.colour != discord.Colour.default(): ideal_position = role.position + 1 if ideal_position >= ctx.guild.me.top_role.position: await ctx.reply("My role isn't high enough to make this role your top coloured role, " "so it may not instantly re-colour your name!") changing_role = await ctx.guild.create_role(name=ctx.author.id, colour=new_colour, reason=f"Custom colour role for {ctx.author.name}") done = True if not done: try: await changing_role.edit(colour=new_colour) except discord.errors.Forbidden: await ctx.reply(embed=self.bot.create_error_embed("My role isn't high enough to edit your " "colour role.")) return await ctx.author.add_roles(changing_role, reason="Added custom colour role.") user_doc["role_id"] = changing_role.id await self.bot.mongo.force_insert(self.colour_roles, user_doc) await ctx.reply(embed=self.bot.create_completed_embed("Added role!", "Added your colour role!"))
async def update_score(self, ctx, score: int, member: discord.Member = None): if member: if "games master" not in map(lambda x: x.name, ctx.author.roles): raise commands.MissingRole("games master") target = member else: target = ctx.author self.scores[target] += score await ctx.send(f"```\n {self.scores[target]:3}" + f" | {target.display_name} \n```") return
async def role(self, ctx, user: discord.Member, action, role: discord.Role): if not permChecks.check_full_access(ctx.author): if role.id not in self.rc(): raise commands.CheckFailure( message=Lang.lang(self, 'role_user_not_configured')) need_mod_role_id = self.rc()[role.id]['modrole'] if need_mod_role_id is None or need_mod_role_id == 0: raise commands.CheckFailure( message=Lang.lang(self, 'role_user_no_modrole', role.name)) if need_mod_role_id not in [r.id for r in ctx.author.roles]: raise commands.MissingRole(need_mod_role_id) if action.lower() == "add": if role in user.roles: await ctx.send( Lang.lang(self, 'role_user_already', utils.get_best_username(user), role)) return await add_user_role(user, role) await ctx.send( Lang.lang(self, 'role_user_added', role, utils.get_best_username(user))) elif action.lower() == "del": if role not in user.roles: await ctx.send( Lang.lang(self, 'role_user_doesnt_have', utils.get_best_username(user), role)) return await remove_user_role(user, role) await ctx.send( Lang.lang(self, 'role_user_removed', role, utils.get_best_username(user))) else: raise commands.BadArgument(Lang.lang(self, 'role_user_bad_arg')) await utils.log_to_admin_channel(ctx)
async def predicate(ctx: commands.Context) -> bool: if not if_manitou(ctx): raise commands.MissingRole(get_manitou_role()) return True
async def cog_check(self, ctx): if ctx.author in get_admin_role().members or await self.bot.is_owner( ctx.author): return True raise commands.MissingRole(get_admin_role())
def cog_check(self, ctx): role = discord.utils.get(ctx.author.roles, id=Config().BOTMASTER_ROLE_ID) if role is None: raise commands.MissingRole(Config().BOTMASTER_ROLE_ID) return True
async def predicate(ctx: commands.Context) -> bool: owner = await ctx.bot.is_owner(ctx.author) if not if_qualified_manitou(ctx) and not owner: raise commands.MissingRole(get_qualified_manitou_role()) return True
async def wrapper(self, ctx, *args, **kwargs): if not czy_manitou(ctx): raise commands.MissingRole(get_manitou_role()) await func(self, ctx, *args, **kwargs)
async def test__on_command_error(self): """Unit tests for bot._on_command_error function.""" # async def _on_command_error(bot, ctx, exc) _on_command_error = bot._on_command_error # mauvais serveur ctx = mock.NonCallableMock(commands.Context, guild=10) await _on_command_error(config.bot, ctx, None) ctx.send.assert_not_called() # STOP ctx = mock_discord.get_ctx() exc = commands.CommandInvokeError(blocs.tools.CommandExit()) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("Mission aborted") # STOP custom message ctx = mock_discord.get_ctx() exc = commands.CommandInvokeError(blocs.tools.CommandExit("cust0m")) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("cust0m") # BDD error - MJ ctx = mock_discord.get_ctx() ctx.author.top_role = mock.MagicMock(discord.Role, __ge__=lambda s, o: True) # >= MJ exc = commands.CommandInvokeError(bdd.SQLAlchemyError("bzzt")) try: raise exc.original # creating traceback except bdd.SQLAlchemyError: pass await _on_command_error(config.bot, ctx, exc) mock_discord.assert_sent(config.Channel.logs, "Rollback session") config.Channel.logs.send.reset_mock() config.session.rollback.assert_called_once() config.session.rollback.reset_mock() ctx.assert_sent(["Un problème est survenu", "Traceback", "SQLAlchemyError", "bzzt"]) # BDD error - not MJ ctx = mock_discord.get_ctx() ctx.author.top_role = mock.MagicMock(discord.Role, __ge__=lambda s, o: False) # < MJ exc = commands.CommandInvokeError(bdd.DriverOperationalError("bzoozt")) try: raise exc.original # creating traceback except bdd.DriverOperationalError: pass await _on_command_error(config.bot, ctx, exc) mock_discord.assert_sent(config.Channel.logs, "Rollback session") config.Channel.logs.send.reset_mock() config.session.rollback.assert_called_once() config.session.rollback.reset_mock() ctx.assert_sent(["Un problème est survenu", bdd.DriverOperationalError.__name__, "bzoozt"]) ctx.assert_not_sent("Traceback") # BDD error - session not ready : on vérifie juste que pas d'erreur ctx = mock_discord.get_ctx() _session = config.session del config.session ctx.author.top_role = mock.MagicMock(discord.Role, __ge__=lambda s, o: True) # >= MJ exc = commands.CommandInvokeError(bdd.SQLAlchemyError("bzzt")) await _on_command_error(config.bot, ctx, exc) mock_discord.assert_sent(config.Channel.logs) # nothing config.Channel.logs.send.reset_mock() ctx.assert_sent(["Un problème est survenu", "SQLAlchemyError", "bzzt"]) config.session = _session # CommandNotFound ctx = mock_discord.get_ctx() await _on_command_error(config.bot, ctx, commands.CommandNotFound()) ctx.assert_sent("je ne connais pas cette commande") # DisabledCommand ctx = mock_discord.get_ctx() await _on_command_error(config.bot, ctx, commands.DisabledCommand()) ctx.assert_sent("Cette commande est désactivée") # ConversionError command = mock.Mock() ctx = mock_discord.get_ctx(command) exc = commands.ConversionError("bkrkr", "kak") await _on_command_error(config.bot, ctx, exc) ctx.assert_sent(["ce n'est pas comme ça qu'on utilise cette commande", "ConversionError", "bkrkr", "kak"]) config.bot.get_context.assert_called_with(ctx.message) self.assertEqual(ctx.message.content, f"!help {command.name}") config.bot.get_context.return_value.reinvoke.assert_called() # UserInputError command = mock.Mock() ctx = mock_discord.get_ctx(command) exc = commands.UserInputError("bakaka") await _on_command_error(config.bot, ctx, exc) ctx.assert_sent(["ce n'est pas comme ça qu'on utilise cette commande", "UserInputError", "bakaka"]) config.bot.get_context.assert_called_with(ctx.message) self.assertEqual(ctx.message.content, f"!help {command.name}") config.bot.get_context.return_value.reinvoke.assert_called() # UserInputError derivate command = mock.Mock() ctx = mock_discord.get_ctx(command) exc = commands.BadArgument("bakaka") await _on_command_error(config.bot, ctx, exc) ctx.assert_sent(["ce n'est pas comme ça qu'on utilise cette commande", "BadArgument", "bakaka"]) config.bot.get_context.assert_called_with(ctx.message) self.assertEqual(ctx.message.content, f"!help {command.name}") config.bot.get_context.return_value.reinvoke.assert_called() # CheckAnyFailure ctx = mock_discord.get_ctx() exc = commands.CheckAnyFailure(mock.ANY, mock.ANY) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("cette commande est réservée aux MJs") # MissingAnyRole ctx = mock_discord.get_ctx() exc = commands.MissingAnyRole([mock.ANY]) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("Cette commande est réservée aux joueurs") # MissingRole ctx = mock_discord.get_ctx() exc = commands.MissingRole(mock.ANY) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("cette commande est réservée aux joueurs en vie") # one_command.AlreadyInCommand, not addIA/modifIA command = mock.Mock() command.configure_mock(name="blabla") ctx = mock_discord.get_ctx(command) exc = blocs.one_command.AlreadyInCommand() await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("Impossible d'utiliser une commande pendant") # one_command.AlreadyInCommand, addIA command = mock.Mock() command.configure_mock(name="addIA") ctx = mock_discord.get_ctx(command) exc = blocs.one_command.AlreadyInCommand() await _on_command_error(config.bot, ctx, exc) ctx.assert_sent() # one_command.AlreadyInCommand, modifIA command = mock.Mock() command.configure_mock(name="modifIA") ctx = mock_discord.get_ctx(command) exc = blocs.one_command.AlreadyInCommand() await _on_command_error(config.bot, ctx, exc) ctx.assert_sent() # CheckFailure (autre check erreur) ctx = mock_discord.get_ctx() exc = commands.CheckFailure("jojo") with mock.patch("lgrez.blocs.tools.mention_MJ") as mmj_patch: await _on_command_error(config.bot, ctx, exc) mmj_patch.assert_called_once_with(ctx) ctx.assert_sent(["cette commande ne puisse pas être exécutée", "CheckFailure", "jojo"]) # other exception ctx = mock_discord.get_ctx() exc = AttributeError("oh") with mock.patch("lgrez.blocs.tools.mention_MJ") as mmj_patch: await _on_command_error(config.bot, ctx, exc) mmj_patch.assert_called_once_with(ctx) ctx.assert_sent(["Une erreur inattendue est survenue", "AttributeError", "oh"]) # other exception ctx = mock_discord.get_ctx() class SomeException(Exception): pass exc = SomeException("p!wet") with mock.patch("lgrez.blocs.tools.mention_MJ") as mmj_patch: await _on_command_error(config.bot, ctx, exc) mmj_patch.assert_called_once_with(ctx) ctx.assert_sent(["Une erreur inattendue est survenue", "SomeException", "p!wet"])