async def ensure_voice(self, ctx): embed = utils.baseEmbed() player = self.zt.lavalink.players.create(ctx.guild.id, endpoint=ctx.guild.region.value) should_connect = ctx.command.name in ('play', 'connect') if ctx.guild.id == 498011182620475412 and not 529365459397509130 in [role.id for role in ctx.author.roles]: raise commands.CheckFailure() if not ctx.author.voice or not ctx.author.voice.channel: embed.description = f'<{self.zt.emoji("Error")}> **| Você precisa estar em um canal de voz.**' await ctx.send(embed=embed) raise commands.CheckFailure() if not player.is_connected: if not should_connect: embed.description = f'<{self.zt.emoji("Error")}> **| Não estou conectada.**' await ctx.send(embed=embed) raise commands.CheckFailure() player.store('channel', ctx.channel.id) await self.connect_to(ctx.guild.id, str(ctx.author.voice.channel.id)) else: if int(player.channel_id) != ctx.author.voice.channel.id: embed.description = f'<{self.zt.emoji("Error")}> **| Você precisa estar no meu canal de voz.**' await ctx.send(embed=embed) raise commands.CheckFailure()
async def _connect(self, ctx, *, channel: discord.VoiceChannel = None): if not channel: try: channel = ctx.author.voice.channel except AttributeError: raise commands.CheckFailure('<:ausente:589239789002162176>│Nenhum canal para participar. ' 'Por favor, especifique um canal válido ou entre em um!``') vc = ctx.voice_client if vc: if vc.channel.id == channel.id: return try: await vc.move_to(channel) except asyncio.TimeoutError: raise commands.CheckFailure(f'<:ausente:589239789002162176>│Mover para o canal: ' f'<{channel}> tempo esgotado.') else: try: await channel.connect() except asyncio.TimeoutError: raise commands.CheckFailure(f'<:ausente:589239789002162176>│Conectando ao canal: ' f'<{channel}> tempo esgotado.') await ctx.send(f'<:on_status:519896814799945728>│Conectado a: **{channel}**', delete_after=20)
def predicate(ctx): if ctx.message.webhook_id is not None: return True guild = ctx.bot.get_guild(ctx.bot.config['config']['default_guild']) if ctx.author.id not in [m.id for m in guild.members]: msg = "<:alert:739251822920728708>│`Voce precisa está dentro do meu servidor de suporte, para poder me " \ "usar.`\n**Obs:** Para entrar no servidor de suporte use o comando **ash invite** para receber o" \ " convite do servidor!" if ctx.command.name in ["invite", "register", "register guild"]: pass else: raise commands.CheckFailure(msg) if isinstance(ctx.message.channel, (discord.DMChannel, discord.GroupChannel)): if ctx.command.name == "help" or ctx.command.name == "ajuda": pass else: if kwargs.get('no_pm', False): pass else: raise commands.NoPrivateMessage( '<:alert:739251822920728708>│`Você não pode mandar comandos em ' 'mensagens privadas!`') if not (isinstance( ctx.channel, (discord.DMChannel, discord.GroupChannel))) and kwargs.get( 'is_nsfw', False): if ctx.channel.is_nsfw() is False: raise commands.CheckFailure( "<:alert:739251822920728708>│`Esse comando apenas pode ser usado" " em um canal` **nsfw!!**") if ctx.author.id == data['config']['owner_id'] and kwargs.get( 'is_owner', False): pass elif ctx.author.id in ctx.bot.staff and kwargs.get('is_owner', False): pass elif ctx.author.id != data['config']['owner_id'] and kwargs.get( 'is_owner', False): raise commands.CheckFailure( "<:alert:739251822920728708>│`Apenas meu criador pode usar esse comando!`" ) if kwargs.get("check_role", False): role = discord.utils.find( lambda r: r.name in kwargs.get("roles", []), ctx.author.roles) if role is None: raise commands.CheckFailure( "<:alert:739251822920728708>│`Você precisa de um cargo " "específico para usar esse comando!`") perms = dict() for perm_ in kwargs.keys(): if perm_ in permissions: perms[perm_] = kwargs[perm_] return check_permissions(ctx, perms)
def verificationCheck(self, ctx): self.c.execute('SELECT Verified FROM main where Discord_UID = (:uid)', {'uid': ctx.author.id}) tuple = self.c.fetchone() if not tuple: raise commands.CheckFailure('AccountNotLinked') if tuple[0] == 'False': raise commands.CheckFailure('EmailNotVerified') return True
async def vc_check(ctx: commands.Context): """Check for whether VC is available in this bot.""" if not discord.voice_client.has_nacl: raise commands.CheckFailure('You cannot use voice because PyNaCl is not loaded.') if not discord.opus.is_loaded(): raise commands.CheckFailure('You cannot use voice because libopus is not loaded.') return True
def predicate(ctx): if not len( ctx.bot.spel.players ) >= MIN_PLAYERS: # not enough players joined yet to start playing raise commands.CheckFailure(message="not enough players") elif str( ctx.author ) != ctx.bot.spel.beurt.fullname: # it is not this players turn raise commands.CheckFailure(message="not your turn") return True
async def pred(ctx): verified = await ctx.bot.conn.fetch( 'SELECT verified FROM student WHERE discord_uid = $1', ctx.author.id ) if not verified: raise commands.CheckFailure('AccountNotLinked') if not verified[0]['verified']: raise commands.CheckFailure('UserNotVerified') return True
async def user_has_voice(ctx): """ Returns true if the user is connected to a voice channel reachable by the bot """ if type(ctx.author) is discord.Member: if ctx.author.voice is not None: return True else: raise commands.CheckFailure( "You are not connected to a voice channel of your guild") else: raise commands.CheckFailure("This command cannot work through DM")
async def predicate(ctx): member = await ctx.bot.mongo.Member.find_one({"id": ctx.author.id}) if member is None: raise commands.CheckFailure( f"Please first start by running `>start`!") if not member.event_activated: raise commands.CheckFailure( "You need to join the event with `>event join`") return True
async def predicate(ctx): member = await ctx.bot.mongo.Member.find_one({"id": ctx.author.id}, {"suspended": 1}) if member is None: raise commands.CheckFailure( f"Please first start by running `>start`!") if member.suspended: raise commands.CheckFailure("Your account has been suspended.") return True
async def predicate(ctx): member = await ctx.bot.mongo.Member.find_one({"id": ctx.author.id}, {"suspended": 1}) if member is None: raise commands.CheckFailure( f"Please pick a starter pokémon by typing `{ctx.prefix}start` before using this command!" ) if member.suspended: raise commands.CheckFailure("Your account has been suspended.") return True
async def check_if_disabled(self, ctx): if not ctx.guild: raise commands.CheckFailure("You can't use that here!") if ctx.command.qualified_name in self.disabled_commands[ctx.guild.id]: raise commands.CheckFailure( "I'm sorry a server moderator has disabled this command.") if ctx.author.id in self.blocked: raise commands.CheckFailure( f"You have been blocked for: {self.blocked[ctx.author.id]}") return True
def predicate(ctx: Context): channel = ctx.channel if not isinstance(channel, discord.TextChannel): if dms: return True raise commands.CheckFailure( 'Dms are not counted as a bot channel.') if re.search(regex, channel.name) or category and re.search( regex, str(channel.category)): return True raise commands.CheckFailure('This channel is not a bot channel.')
async def verify(self, ctx): if not ctx.invoked_subcommand: await ctx.reply(l10n.format_value('verify-invalid-command')) return self.c.execute('SELECT Verified from main where Discord_UID = (:uid)', {'uid': ctx.author.id}) details = self.c.fetchone() if details: if details[0] == 'False': if ctx.invoked_subcommand.name == 'basic': raise commands.CheckFailure('AccountAlreadyLinked') else: raise commands.CheckFailure('UserAlreadyVerified')
async def verify_token(self, ctx, auth_token: str): """Takes an authentication token and elevates you to Verified LUHacker. Note that tokens expire after 30 minutes. Second step on the path to Grand Master Cyber Wizard. """ existing_user = await User.get(ctx.author.id) is_flagged = (existing_user is not None and existing_user.flagged_for_deletion is not None) if existing_user is not None and not is_flagged: raise commands.CheckFailure("It seems you've already registered.") user = token_tools.decode_auth_token(auth_token) if user is None: raise commands.CheckFailure( "That token is invalid or is older than 30 minutes and expired." ) user_id, user_email = user if user_id != ctx.author.id: raise commands.CheckFailure( "Seems you're not the same person that generated the token, go away." ) member: discord.Member = self.get_member_in_luhack(ctx.author.id) assert member is not None logger.info("Verifying member: %s", ctx.author) if is_flagged: await existing_user.update(flagged_for_deletion=None).apply() await ctx.send("Congrats, you've been re-verified!") await self.bot.log_message( f"re-verified member {member} ({member.id})") return user = User(discord_id=user_id, username=member.name, email=user_email) await user.create() await member.remove_roles(self.bot.potential_role(), self.bot.prospective_role()) await member.add_roles(self.bot.verified_role()) await ctx.send( "Permissions granted, you can now access all of the discord channels. You are now on the path to Grand Master Cyber Wizard!" ) await self.bot.log_message(f"verified member {member} ({member.id})")
async def _check_reaction_permissions(context, channel): # author might not be a Member, even in a guild, if it's a webhook. if not context.guild or not isinstance(context.author, discord.Member): return sender_permissions = channel.permissions_for(context.author) permissions = channel.permissions_for(context.guild.me) if not sender_permissions.read_message_history or not permissions.read_message_history: raise commands.CheckFailure(_('Unable to react: you and I both need permission to read message history.')) if not sender_permissions.add_reactions or not permissions.add_reactions: raise commands.CheckFailure(_('Unable to react: you and I both need permission to add reactions.')) if not sender_permissions.external_emojis or not permissions.external_emojis: raise commands.CheckFailure(_('Unable to react: you and I both need permission to use external emotes.'))
async def can_run_commands(self, ctx: context.Context) -> bool: if not ctx.guild and ctx.command.qualified_name in self.commands_not_allowed_dms: raise commands.NoPrivateMessage() if ctx.user_config.blacklisted is True and ctx.command.qualified_name not in { 'help', 'support' }: raise commands.CheckFailure( f'You are blacklisted from using this bot with the reason:\n\n`{ctx.user_config.blacklisted_reason}`' ) elif ctx.guild_config.blacklisted is True and ctx.command.qualified_name not in { 'help', 'support' }: raise commands.CheckFailure( f'This guild is blacklisted from using this bot with the reason:\n\n`{ctx.guild_config.blacklisted_reason}`' ) needed_permissions = { permission: value for permission, value in dict(self.text_permissions).items() if value is True } current_permissions = dict(ctx.channel.permissions_for( ctx.guild.me)) if ctx.guild else dict( ctx.channel.me.permissions_in(ctx.channel)) if ctx.command.cog and ctx.command.cog == self.get_cog( 'Music') and hasattr(ctx.author, 'voice') and ctx.author.voice is not None: needed_permissions.update({ permission: value for permission, value in dict(self.voice_permissions).items() if value is True }) current_permissions.update({ permission: value for permission, value in getattr( ctx.author.voice, 'channel', None).permissions_for( ctx.guild.me) if value is True }) missing = [ permissions for permissions, value in needed_permissions.items() if current_permissions[permissions] != value ] if missing: raise commands.BotMissingPermissions(missing) return True
async def vc_check(ctx: commands.Context): # pylint: disable=unused-argument """ Check for whether VC is available in this bot. """ if not discord.voice_client.has_nacl: raise commands.CheckFailure( "voice cannot be used because PyNaCl is not loaded") if not discord.opus.is_loaded(): raise commands.CheckFailure( "voice cannot be used because libopus is not loaded") return True
def predicate(ctx): if ctx.message.webhook_id is not None: return True if isinstance(ctx.message.channel, (discord.DMChannel, discord.GroupChannel)): if ctx.command.name == "help" or ctx.command.name == "ajuda": return True else: raise commands.NoPrivateMessage( '<:alert:739251822920728708>│``Você não pode mandar comandos em ' 'mensagens privadas!``') if not (isinstance( ctx.channel, (discord.DMChannel, discord.GroupChannel))) and kwargs.get( 'is_nsfw', False): if ctx.channel.is_nsfw() is False: raise commands.CheckFailure( "<:alert:739251822920728708>│``Esse comando apenas pode ser usado" " em um canal`` **nsfw!!**") if ctx.author.id == data['config']['owner_id'] and kwargs.get( 'is_owner', False): pass elif ctx.author.id in ctx.bot.staff and kwargs.get('is_owner', False): pass elif ctx.author.id != data['config']['owner_id'] and kwargs.get( 'is_owner', False): raise commands.CheckFailure( "<:alert:739251822920728708>│``Apenas meu criador pode usar esse comando!``" ) if kwargs.get("check_role", False): role = discord.utils.find( lambda r: r.name in kwargs.get("roles", []), ctx.author.roles) if role is None: raise commands.CheckFailure( "<:alert:739251822920728708>│``Você precisa de um cargo " "específico para usar esse comando!``") if kwargs.get('no_pm', False) or kwargs.get( 'is_owner', False) or kwargs.get('is_nsfw', False): perms = dict() for perm_ in kwargs.keys(): if perm_ in permissions: perms[perm_] = kwargs[perm_] return check_permissions(ctx, perms) return True
def predicate(ctx): if not ctx.guild: raise commands.CheckFailure("Only usable within a server") if not ctx.guild.me.voice: raise commands.CheckFailure("I am not in voice no need to stop") my_voice = ctx.guild.me.voice.channel if checks.is_owner_or_moderator_check(ctx.message): return True if ctx.guild.me.voice: if len(my_voice.members) == 2 and ctx.author in my_voice.members: return True if len(my_voice.members) == 1: return True raise commands.CheckFailure("Can only stop when nobody or" "only one in voice channel with me")
async def check_guild_permissions(ctx, perms, check=all): if await ctx.bot.is_owner(ctx.author): return True is_owner = await ctx.bot.is_owner(ctx.author) if is_owner: return True if ctx.guild is None: raise commands.CheckFailure('You must be in a guild to run this command!') if ctx.guild.id == 594276321937326091: # custom message for the support server raise commands.CheckFailure("You should run this command in your server! Get the invite link with `+invite`.") resolved = ctx.author.guild_permissions return check(getattr(resolved, name, None) == value for name, value in perms.items())
async def guessword(self, ctx, word: str): guesser = ctx.author room = here(ctx) game = room.game if word not in game.words: raise commands.CheckFailure( f"`{word}` not in word list. Check spelling and capitalization. You can edit your message or enter a new one." ) correct = room.resolve_word_guess(guesser, word) correct_string = {True: "right", False: "wrong"}[correct] await ctx.send( f"**{guesser.display_name}** (team **{game.get_secret_word(guesser)}**) guessed **{word}** for the opposing word, which is __{correct_string}__. Winning team: **{game.winning_word}**" ) # If this overrode a veto, say whether it would have succeeded if game.in_veto_phase: orig_guesser, orig_guessed_players = game.vetoable_team_guess correctness_message = self.team_guess_correctness_message( ctx, orig_guesser, orig_guessed_players, is_hypothetical=True) await ctx.send(correctness_message) await self.reveal_teams(ctx) await self.end_round_and_clean_up(ctx)
async def guessteam(self, ctx, *players: discord.Member): guessed_players = players guessed_players = list(guessed_players) guesser = ctx.author players_set = set(here(ctx).game.players) if not set(guessed_players) <= players_set: extra_players = list(set(guessed_players) - players_set) extra_player_names = [ player.display_name for player in extra_players ] extra_player_name_string = " and ".join(extra_player_names) phrase = { False: "is not a player", True: "are not players" }[len(extra_players) > 1] raise commands.CheckFailure( f"{extra_player_name_string} {phrase}. Use @ to autocomplete names to avoid typos. Names are case-sensitive. You can edit your message or enter a new one." ) # As a convenience, include the guesser in their own team guess if guesser not in guessed_players: guessed_players = [guesser] + guessed_players await self.guess_team_helper(ctx, guesser, guessed_players)
async def predicate(ctx): # See if we're even requesting anything if not any_item_names: ctx.bot.logger.warning(f"No role tiers input for is_upgrade_chat_subscriber for command {ctx.command.name}") return True # This returns a bool because it needs to return something truthy # Grab all purchased roles by the user try: purchases = await asyncio.wait_for( ctx.bot.upgrade_chat.get_orders(discord_id=ctx.author.id, type=upgradechat.UpgradeChatItemType.UPGRADE), timeout=3, ) except (asyncio.TimeoutError, upgradechat.UpgradeChatError): raise commands.CheckFailure("Upgrade.Chat is currently unable to process my request for subscribers - please try again later.") # See if they purchased anything that's correct output_items = [] for purchase in purchases: if purchase.type.name != "UPGRADE": continue if purchase.deleted is not None and purchase.deleted > dt.utcnow(): continue for order_item in purchase.order_items: product_name = order_item.product_name if product_name in any_item_names: output_items.append(product_name) if output_items: ctx.upgrade_chat_items = output_items return True # They didn't purchase anything [valid] raise IsNotUpgradeChatSubscriber()
async def boggle(self, ctx: Context): """Start's a game of Boggle. The board size can be set by command prefix. `(bb)big boggle` will result in a 5x5 board. `(bb)super big boggle` will result in a 6x6 board. Players have 3 minutes to find as many words as they can, the first person to find a word gets the points. """ # Ignore if rules invoke if ctx.invoked_subcommand is self.boggle_rules: return # Raise if game already running if ctx.channel in self.games: raise commands.CheckFailure( 'There is already a game running in this channel.') # Determine the game type game_type = self._get_game_type(ctx) # Start the game self.games[ctx.channel] = game = game_type(size=self._check_size(ctx)) await game.start(ctx, wait=False) # Wait for game to end def check(channel): return channel.id == ctx.channel.id await self.bot.wait_for('boggle_game_complete', check=check, timeout=200) if ctx.channel in self.games: del self.games[ctx.channel]
async def stop_(self, ctx): vc = ctx.voice_client try: channel = ctx.author.voice.channel if channel: pass except AttributeError: raise commands.CheckFailure('<:oc_status:519896814225457152>│``Entre num canal de voz!``') if not vc or not vc.is_connected(): return await ctx.send('<:alert_status:519896811192844288>│``Atualmente não estou tocando nada!``', delete_after=20) else: state = self.get_state(ctx.guild) if state.is_requester(ctx) is None: await self.cleanup(ctx.guild) return await ctx.send('<:stop:519896823196942336>│``Todas as músicas foram paradas!``', delete_after=20) if ctx.channel.permissions_for(ctx.author).administrator or state.is_requester(ctx): await ctx.send('<:stop:519896823196942336>│``Todas as músicas foram paradas!``', delete_after=20) await self.cleanup(ctx.guild) last_search[ctx.guild.id] = list() else: await ctx.send('<:ausente:589239789002162176>│``Você não tem permissão para fazer isso!``')
async def generate_token(self, ctx, email: email_tools.lancs_email): """Generates an authentication token, then emails it to the provided email. You must provide a valid lancaster email address or you will not get an authentication token. First step on the path to Grand Master Cyber Wizard """ existing_user = await User.query.where( (User.discord_id == ctx.author.id) | (User.email == email)).gino.first() if existing_user and existing_user.discord_id != ctx.author.id: await ctx.send( "Looks like you're already registered with this email address") return is_flagged = (existing_user is not None and existing_user.flagged_for_deletion is not None) if existing_user is not None and not is_flagged: raise commands.CheckFailure("It seems you've already registered.") auth_token = token_tools.generate_auth_token(ctx.author.id, email) logger.info("Generated token for user: %s, %s", ctx.author, auth_token) await email_tools.send_verify_email(email, auth_token) await ctx.send( f"Okay, I've sent an email to: `{email}` with your token!")
async def check_blacklist(ctx): if str(ctx.author.id) in bot.blacklist['users']: raise commands.CheckFailure( f'You have been blacklisted from using me. Please check you DMs for a reason or contact DevilJamJar#0001 to appeal.' ) else: return True
async def guessword(self, ctx, word: str): guesser = ctx.author if word not in here(ctx).game.words: raise commands.CheckFailure( f"`{word}` not in word list. Check spelling and capitalization. You can edit your message or enter a new one." ) correct = here(ctx).resolve_word_guess(guesser, word) correct_string = {True: "right", False: "wrong"}[correct] await ctx.send( f"**{guesser.display_name}** (team **{here(ctx).game.get_secret_word(guesser)}**) guessed **{word}** for the opposing word, which is __{correct_string}__. Winning team: **{here(ctx).game.winning_word}**" ) # If this overrode a veto, say whether it would have succeeded if here(ctx).game.in_veto_phase: orig_guesser, orig_guessed_players = here( ctx).game.vetoable_team_guess orig_guessed_players_string = names_list_string( orig_guessed_players) correct = here(ctx).game.check_team_guess(orig_guesser, orig_guessed_players) correct_string = {True: "right", False: "wrong"}[correct] await ctx.send( f"(The original guess by **{orig_guesser.display_name}** (team **{here(ctx).game.get_secret_word(orig_guesser)}**) of {orig_guessed_players_string} would have been _{correct_string}_.)" ) await self.reveal_teams(ctx) await self.end_round_and_clean_up(ctx)
async def can_run(self, ctx): original = ctx.command ctx.command = self try: if not (await ctx.bot.can_run(ctx)): raise commands.CheckFailure( 'The global check functions for command {0.qualified_name} failed.' .format(self)) cog = self.instance if cog is not None: try: local_check = getattr( cog, '_{0.__class__.__name__}__local_check'.format(cog)) except AttributeError: pass else: ret = await discord.utils.maybe_coroutine(local_check, ctx) if not ret: return False if ctx.author.id in ctx.bot.owners: return True predicates = self.checks if not predicates: return True return await discord.utils.async_all( predicate(ctx) for predicate in predicates) finally: ctx.command = original