[Utils] Text to file (#2849)

This commit is contained in:
El Laggron 2019-08-26 02:13:21 +02:00 committed by Toby Harradine
parent 580c4429e8
commit 43da727a9f
2 changed files with 30 additions and 0 deletions

View File

@ -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.

View File

@ -1,6 +1,7 @@
import itertools import itertools
import datetime import datetime
from typing import Sequence, Iterator, List, Optional from typing import Sequence, Iterator, List, Optional
from io import BytesIO
import discord import discord
@ -429,3 +430,30 @@ def humanize_timedelta(
strings.append(f"{period_value} {unit}") strings.append(f"{period_value} {unit}")
return ", ".join(strings) 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)