Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion botcore/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Useful utilities and tools for Discord bot development."""

from botcore.utils import _monkey_patches, caching, channel, interactions, logging, members, regex, scheduling
from botcore.utils import _monkey_patches, caching, channel, commands, interactions, logging, members, regex, scheduling
from botcore.utils._extensions import unqualify


Expand All @@ -24,6 +24,7 @@ def apply_monkey_patches() -> None:
apply_monkey_patches,
caching,
channel,
commands,
interactions,
logging,
members,
Expand Down
38 changes: 38 additions & 0 deletions botcore/utils/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from typing import Optional

from discord import Message
from discord.ext.commands import BadArgument, Context, clean_content


async def clean_text_or_reply(ctx: Context, text: Optional[str] = None) -> str:
"""
Cleans a text argument or replied message's content.

Args:
ctx: The command's context
text: The provided text argument of the command (if given)

Raises:
:exc:`discord.ext.commands.BadArgument`
`text` wasn't provided and there's no reply message / reply message content.

Returns:
The cleaned version of `text`, if given, else replied message.
"""
clean_content_converter = clean_content(fix_channel_mentions=True)

if text:
return await clean_content_converter.convert(ctx, text)

if (
(replied_message := getattr(ctx.message.reference, "resolved", None)) # message has a cached reference
and isinstance(replied_message, Message) # referenced message hasn't been deleted
):
if not (content := ctx.message.reference.resolved.content):
# The referenced message doesn't have a content (e.g. embed/image), so raise error
raise BadArgument("The referenced message doesn't have a text content.")

return await clean_content_converter.convert(ctx, content)

# No text provided, and either no message was referenced or we can't access the content
raise BadArgument("Couldn't find text to clean. Provide a string or reply to a message to use its content.")
3 changes: 3 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
Changelog
=========

- :feature:`101` Add a utility to clean a string or referenced message's content


- :release:`7.4.0 <17th July 2022>`
- :feature:`106` Add an optional ``message`` attr to :obj:`botcore.utils.interactions.ViewWithUserAndRoleCheck`. On view timeout, this message has its view removed if set.

Expand Down