diff --git a/changelog.d/2849.misc.rst b/changelog.d/2849.misc.rst new file mode 100644 index 000000000..6d6074e8a --- /dev/null +++ b/changelog.d/2849.misc.rst @@ -0,0 +1,2 @@ +Added the function ``redbot.core.utils.chat_formatting.text_to_file`` to +prepare a long text to be send as a file. diff --git a/redbot/core/utils/chat_formatting.py b/redbot/core/utils/chat_formatting.py index 52380013e..a73abf78c 100644 --- a/redbot/core/utils/chat_formatting.py +++ b/redbot/core/utils/chat_formatting.py @@ -1,6 +1,7 @@ import itertools import datetime from typing import Sequence, Iterator, List, Optional +from io import BytesIO import discord @@ -429,3 +430,30 @@ def humanize_timedelta( strings.append(f"{period_value} {unit}") return ", ".join(strings) + + +def text_to_file( + text: str, filename: str = "file.txt", *, spoiler: bool = False, encoding: str = "utf-8" +): + """Prepares text to be sent as a file on Discord, without character limit. + + This writes text into a bytes object that can be used for the ``file`` or ``files`` parameters + of :meth:`discord.abc.Messageable.send`. + + Parameters + ---------- + text: str + The text to put in your file. + filename: str + The name of the file sent. Defaults to ``file.txt``. + spoiler: bool + Whether the attachment is a spoiler. Defaults to ``False``. + + Returns + ------- + discord.File + The file containing your text. + + """ + file = BytesIO(text.encode(encoding)) + return discord.File(file, filename, spoiler=spoiler)