Python discord.ext.commands.clean_content() Examples

The following are 11 code examples of discord.ext.commands.clean_content(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord.ext.commands , or try the search function .
Example #1
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
def preserve(self, context, should_preserve: bool, *names: commands.clean_content):
		"""Sets preservation status of emotes."""
		names = set(names)
		messages = {}
		success_message = (
			_('**Succesfully preserved:**')
			if should_preserve else
			_('**Succesfully un-preserved:**'))
		for name in names:
			try:
				emote = await self.db.set_emote_preservation(name, should_preserve)
			except errors.EmoteNotFoundError as ex:
				messages.setdefault(self._humanize_errors(ex), []).append(fr'\:{name}:')
			else:
				messages.setdefault((0, success_message), []).append(str(emote))
				self.bot.dispatch(f'emote_{"un" if not should_preserve else ""}preserve', emote)

		messages = sorted(messages.items())
		message = self._format_errors(messages)
		await context.send(message)

	## Events 
Example #2
Source File: timers.py    From NabBot with Apache License 2.0 6 votes vote down vote up
def remindme(self, ctx: NabCtx, when: TimeString, *, what: clean_content):
        """Creates a personal reminder.

        You will be notified in the same channel when the time is over."""
        now = dt.datetime.now(tz=dt.timezone.utc)
        expires = now + dt.timedelta(seconds=when.seconds)
        await self.create_timer(now, expires, what, ReminderType.CUSTOM, ctx.author.id, {"message": ctx.message.id,
                                                                                         "channel": ctx.channel.id})
        await ctx.success(f"Ok, I will remind you in {when.original} about: {what}")

    # endregion

    # Auxiliary functions 
Example #3
Source File: doc.py    From bot with MIT License 5 votes vote down vote up
def docs_group(self, ctx: commands.Context, symbol: commands.clean_content = None) -> None:
        """Lookup documentation for Python symbols."""
        await ctx.invoke(self.get_command, symbol) 
Example #4
Source File: misc.py    From RemixBot with MIT License 5 votes vote down vote up
def say(self, ctx, *, message: commands.clean_content()):
        '''Say something as the bot'''
        voted = await self.upvoted(ctx.author.id)
        if not voted:
            return await ctx.send(f'To use this command, you must upvote RemixBot here: https://discordbots.org/bot/{self.bot.user.id}')
        try:
            await ctx.message.delete()
        except discord.Forbidden:
            pass
        await ctx.send(message) 
Example #5
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def blacklist(self, context, user: UserOrMember, *,
		reason: commands.clean_content(
			fix_channel_mentions=True,  # blacklist messages are global, so we don't want "#invalid-channel"
			escape_markdown=True,
			use_nicknames=False,
		) = None
	):
		"""Prevent a user from using commands and the emote auto response.
		If you don't provide a reason, the user will be un-blacklisted.
		"""
		await self.db.set_user_blacklist(user.id, reason)
		if reason is None:
			await context.send(_('User un-blacklisted.'))
		else:
			await context.send(_('User blacklisted with reason “{reason}”.').format(**locals())) 
Example #6
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def _extract_emotes(self,
		message: discord.Message,
		content: str = None,
		*,
		callback,
		log_usage=False,
	):
		"""Extract emotes according to predicate.
		Callback is a coroutine function taking three arguments: token, out: StringIO, and emotes_used: set
		For each token, callback will be called with these arguments.
		out is the StringIO that holds the extracted string to return, and emotes_used is a set
		containing the IDs of all emotes that were used, for logging purposes.

		Returns extracted_message: str, has_emotes: bool.
		"""

		out = io.StringIO()
		emotes_used = set()

		if content is None:
			content = message.content

		# we make a new one each time otherwise two tasks might use the same lexer at the same time
		lexer = utils.lexer.new()

		lexer.input(content)
		for toke1 in iter(lexer.token, None):
			await callback(toke1, out, emotes_used)

		result = out.getvalue() if emotes_used else content

		if log_usage:
			for emote in emotes_used:
				await self.db.log_emote_use(emote)

		return utils.clean_content(self.bot, message, result), bool(emotes_used) 
Example #7
Source File: rng.py    From nano-chan with MIT License 5 votes vote down vote up
def choose(self, ctx, *choices: commands.clean_content):
        """Chooses between multiple choices.
        To denote multiple choices, you should use double quotes.
        """
        if len(choices) < 2:
            return await ctx.send('Not enough choices to pick from.')

        await ctx.send(rng.choice(choices) 
Example #8
Source File: pingy.py    From nano-chan with MIT License 5 votes vote down vote up
def pingy(self, ctx, *roles: commands.clean_content):
        """
        Pings all the roles in the command
        """
        if not roles:
            await ctx.send(":thinking:", delete_after=3)
            await ctx.message.delete()
        guild_roles = ctx.guild.roles
        found_roles = []
        for role in roles:
            if role.lower() not in \
                    ['dedicated', 'updated', 'events', 'moderator',
                     'admin', 'representative']:
                continue
            guild_role = find(
                lambda m: m.name.lower() == role.lower(), guild_roles)
            if not guild_role:
                continue
            found_roles.append(guild_role)
        if not found_roles:
            await ctx.send(
                ":joy: lmao no roles there bud :100:", delete_after=3)
            await ctx.message.delete()
            return
        mention_str = ""
        for role in found_roles:
            await role.edit(mentionable=True)
            mention_str += f'{role.mention} '
        await ctx.send(mention_str)
        await ctx.message.delete()
        for role in found_roles:
            await role.edit(mentionable=False) 
Example #9
Source File: doc.py    From bot with MIT License 4 votes vote down vote up
def get_command(self, ctx: commands.Context, symbol: commands.clean_content = None) -> None:
        """
        Return a documentation embed for a given symbol.

        If no symbol is given, return a list of all available inventories.

        Examples:
            !docs
            !docs aiohttp
            !docs aiohttp.ClientSession
            !docs get aiohttp.ClientSession
        """
        if symbol is None:
            inventory_embed = discord.Embed(
                title=f"All inventories (`{len(self.base_urls)}` total)",
                colour=discord.Colour.blue()
            )

            lines = sorted(f"• [`{name}`]({url})" for name, url in self.base_urls.items())
            if self.base_urls:
                await LinePaginator.paginate(lines, ctx, inventory_embed, max_size=400, empty=False)

            else:
                inventory_embed.description = "Hmmm, seems like there's nothing here yet."
                await ctx.send(embed=inventory_embed)

        else:
            # Fetching documentation for a symbol (at least for the first time, since
            # caching is used) takes quite some time, so let's send typing to indicate
            # that we got the command, but are still working on it.
            async with ctx.typing():
                doc_embed = await self.get_symbol_embed(symbol)

            if doc_embed is None:
                error_embed = discord.Embed(
                    description=f"Sorry, I could not find any documentation for `{symbol}`.",
                    colour=discord.Colour.red()
                )
                error_message = await ctx.send(embed=error_embed)
                with suppress(NotFound):
                    await error_message.delete(delay=NOT_FOUND_DELETE_DELAY)
                    await ctx.message.delete(delay=NOT_FOUND_DELETE_DELAY)
            else:
                await ctx.send(embed=doc_embed) 
Example #10
Source File: modmail.py    From modmail with GNU Affero General Public License v3.0 4 votes vote down vote up
def snippet_add(self, ctx, name: str.lower, *, value: commands.clean_content):
        """
        Add a snippet.

        Simply to add a snippet, do: ```
        {prefix}snippet add hey hello there :)
        ```
        then when you type `{prefix}hey`, "hello there :)" will get sent to the recipient.

        To add a multi-word snippet name, use quotes: ```
        {prefix}snippet add "two word" this is a two word snippet.
        ```
        """
        if name in self.bot.snippets:
            embed = discord.Embed(
                title="Error",
                color=self.bot.error_color,
                description=f"Snippet `{name}` already exists.",
            )
            return await ctx.send(embed=embed)

        if name in self.bot.aliases:
            embed = discord.Embed(
                title="Error",
                color=self.bot.error_color,
                description=f"An alias that shares the same name exists: `{name}`.",
            )
            return await ctx.send(embed=embed)

        if len(name) > 120:
            embed = discord.Embed(
                title="Error",
                color=self.bot.error_color,
                description="Snippet names cannot be longer than 120 characters.",
            )
            return await ctx.send(embed=embed)

        self.bot.snippets[name] = value
        await self.bot.config.update()

        embed = discord.Embed(
            title="Added snippet",
            color=self.bot.main_color,
            description="Successfully created snippet.",
        )
        return await ctx.send(embed=embed) 
Example #11
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 4 votes vote down vote up
def remove(self, context, *names: commands.clean_content):
		"""Removes one or more emotes from the bot. You must own all of them.

		Optional arguments:
			-f, --force Whether to forcibly remove the emotes. This option can only be used by emote moderators.
		"""

		try:
			opts, names = getopt.gnu_getopt(names, 'f', ('force',))
		except getopt.GetoptError:
			opts = []
		opts = frozenset(dict(opts))

		force = False
		if '-f' in opts or '--force' in opts:
			if not await self.db.is_moderator(context.author.id):
				return await context.send(_('Error: only emote moderators may forcibly remove emotes.'))
			force = True

		logger = (
			(lambda emote: self.logger.on_emote_force_remove(emote, context.author))
			if force
			else self.logger.on_emote_remove)

		if not names:
			return await context.send(_('Error: you must provide the name of at least one emote to remove'))
		messages = {}

		async with context.typing():
			for name in names:
				arg = fr'\:{name}:'

				try:
					emote = await self.db.get_emote(name)
				except BaseException as error:  # XXX
					messages.setdefault(self._humanize_errors(error), []).append(arg)
					continue

				# log the emote removal *first* because if we were to do it afterwards,
				# the emote would not display (since it's already removed)
				removal_messages = await logger(emote)
				try:
					await self.db.remove_emote(emote, context.author.id, force=force)
				except (errors.ConnoisseurError, errors.DiscordError) as error:
					messages.setdefault(self._humanize_errors(error), []).append(arg)
					# undo the log
					await asyncio.gather(*map(operator.methodcaller('delete'), removal_messages), return_exceptions=True)
				else:
					message = _('**Successfully deleted:**')
					messages.setdefault((0, message), []).append(emote.escaped_name())

		messages = sorted(messages.items())
		message = self._format_errors(messages)
		await context.send(message)