async def convert(self, ctx, argument) -> discord.TextChannel: match = ID_REGEX.match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) if match is None or not ctx.guild: raise commands.ChannelNotFound(argument) channel_id = int(match.group(1)) result = ctx.guild.get_channel(channel_id) if not isinstance(result, discord.TextChannel): raise commands.ChannelNotFound(argument) return result
async def convert(self, ctx, argument): bot = ctx.bot guild = ctx.guild try: return await super().convert(ctx, argument) except commands.ChannelNotFound: if guild: categories = {c.name.casefold(): c for c in guild.categories} else: categories = { c.name.casefold(): c for c in bot.get_all_channels() if isinstance(c, discord.CategoryChannel) } result = get_close_matches(argument.casefold(), categories.keys(), n=1, cutoff=0.75) if result: result = categories[result[0]] if not isinstance(result, discord.CategoryChannel): raise commands.ChannelNotFound(argument) return result
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 move(self, ctx, *, arguments): """ Move a thread to another category. `category` may be a category ID, mention, or name. `options` is a string which takes in arguments on how to perform the move. Ex: "silently" """ split_args = arguments.strip('"').split(" ") category = None # manually parse arguments, consumes as much of args as possible for category for i in range(len(split_args)): try: if i == 0: fmt = arguments else: fmt = " ".join(split_args[:-i]) category = await SimilarCategoryConverter().convert(ctx, fmt) except commands.BadArgument: if i == len(split_args) - 1: # last one raise pass else: break if not category: raise commands.ChannelNotFound(arguments) options = " ".join(arguments.split(" ")[-i:]) thread = ctx.thread silent = False if options: silent_words = ["silent", "silently"] silent = any(word in silent_words for word in options.split()) await thread.channel.edit(category=category, sync_permissions=True) if self.bot.config["thread_move_notify"] and not silent: embed = discord.Embed( title=self.bot.config["thread_move_title"], description=self.bot.config["thread_move_response"], color=self.bot.main_color, ) await thread.recipient.send(embed=embed) if self.bot.config["thread_move_notify_mods"]: mention = self.bot.config["mention"] await thread.channel.send(f"{mention}, thread has been moved.") sent_emoji, _ = await self.bot.retrieve_emoji() await self.bot.add_reaction(ctx.message, sent_emoji)
async def command_enable_disable_handler( self, ctx: commands.Context, command: str, channel: Optional[Union[discord.TextChannel, str]], toggle: bool, ): channel = channel or ctx.channel channels = ctx.guild.channels + ["all"] if channel not in channels: raise commands.ChannelNotFound(channel) full_command = self.bot.get_command(command) if not full_command: full_command = self.bot.get_cog(command) is_cog = True else: is_cog = False if not full_command: raise CommandToggleError(f"Command {command} not found!") if full_command in self.get_commands() or command in ["core", "config"]: raise CommandToggleError("You can't enable/disable the core commands!") valid_channels = ctx.guild.text_channels if channel == "all" else [ctx.channel] guild = self.bot.guilds_cache.get(ctx.guild.id) for text_channel in valid_channels: record, _ = await CommandModel.get_or_create( guild=guild, name=full_command.qualified_name if is_cog else full_command.name, channel=text_channel.id, ) record.is_cog = is_cog record.enabled = toggle await record.save() # Clearing the cache self.bot.commands_cache[ctx.guild.id] = None toggle_str = "enabled" if toggle else "disabled" await ctx.reply(f"`{command}` has been {toggle_str} for `{channel}`!")
def get_channel(self, channel_name): """ Returns a discord.TextChannel object :param channel_name: The name of the channel :return: The TextChannel object with the given name :raise: ChannelNotFound if the channel name was not found in the database """ if type(channel_name) is int: # some funcions may call this method with a channel id return super().get_channel(channel_name) elif channel_name in self._channel_cache: channel_id = self._channel_cache[channel_name] else: db = Database() channel_id = db.query("SELECT id FROM text_channels WHERE name = ?", (channel_name,))[0] if channel_id is not None: self._channel_cache[channel_name] = channel_id else: raise commands.ChannelNotFound("Bad channel name argument.") return super().get_channel(channel_id)
async def convert(self, ctx, argument): bot = ctx.bot guild = ctx.guild try: return await super().convert(ctx, argument) except commands.ChannelNotFound: def check(c): return isinstance(c, discord.CategoryChannel) and c.name.lower().startswith( argument.lower() ) if guild: result = discord.utils.find(check, guild.categories) else: result = discord.utils.find(check, bot.get_all_channels()) if not isinstance(result, discord.CategoryChannel): raise commands.ChannelNotFound(argument) return result
async def get_channel_or_thread_message(self, msg_tuple: MessageTuple) -> discord.Message: """Get message from channel or thread. Args: msg_tuple (MessageTuple): The message tuple. Raises: commands.MessageNotFound: If the message is not found. commands.ChannelNotFound: If the channel is not found. commands.GuildNotFound: If the guild is not found. discord.Forbidden: If the bot does not have permission to access the message. discord.HTTPException: If the request failed. Returns: discord.Message: The message. """ if msg_tuple.guild_id is None: channel = self.bot.get_channel(msg_tuple.channel_or_thread_id) if channel is None: raise commands.ChannelNotFound(str(msg_tuple.channel_or_thread_id)) return await lazy_load_message(channel, msg_tuple.msg_id) elif guild := self.bot.get_guild(msg_tuple.guild_id): if channel_or_thread := guild.get_channel_or_thread(msg_tuple.channel_or_thread_id): return await lazy_load_message(channel_or_thread, msg_tuple.msg_id)
commands.GuildNotFound: If the guild is not found. discord.Forbidden: If the bot does not have permission to access the message. discord.HTTPException: If the request failed. Returns: discord.Message: The message. """ if msg_tuple.guild_id is None: channel = self.bot.get_channel(msg_tuple.channel_or_thread_id) if channel is None: raise commands.ChannelNotFound(str(msg_tuple.channel_or_thread_id)) return await lazy_load_message(channel, msg_tuple.msg_id) elif guild := self.bot.get_guild(msg_tuple.guild_id): if channel_or_thread := guild.get_channel_or_thread(msg_tuple.channel_or_thread_id): return await lazy_load_message(channel_or_thread, msg_tuple.msg_id) raise commands.ChannelNotFound(str(msg_tuple.channel_or_thread_id)) raise commands.GuildNotFound(str(msg_tuple.guild_id)) async def _get_last_message_from_author(self, author_id: int, limit=100) -> discord.Message: async for msg in self.history(limit=limit, before=self.message): if msg.author.id == author_id: return msg raise commands.MessageNotFound(str(author_id)) async def _get_message_from_unknown_channel_or_thread(self, msg_id: int) -> discord.Message: if msg := discord.utils.find(lambda msg: msg.id == msg_id, self.bot.cached_messages): return msg try: return await lazy_load_message(self, msg_id) except (commands.MessageNotFound, discord.Forbidden): if not self.guild: