我如何限制图像到 ASCII 转换器一次输出的字符数以不一致的方式输出,每条消息限制为 2000 个字符

How can I limit the number of characters output at a time for image to ASCII converter to output in discord with 2000 character limit per message

我有一个图像到 ASCII 转换器与 discord bot 一起使用,这样人们就可以向它发送图像,它下载它并将其转换为 ASCII 并将其发回给他们,但是由于 Discord 将消息限制为每条消息 2000 个字符制作尺寸合理的图像时经常卡住。

我使用 this 教程来转换图像,我相信这行代码:

asciiImage = "\n".join(newImageData[i:(i + newWidth)] for i in range(0, pixelCount, newWidth))

是我需要修复的那个,我相信它将图像的每一行连接到一个基于 newWidth 变量的换行符,你在给它图像时输入它。我如何限制它只添加行直到下一行超过 2000,输出它(或将它添加到列表中)然后重复直到它完成图像?

抱歉,如果这有点令人困惑。

您可以在 for 循环中对其进行迭代并跟踪字符串的当前大小。如果添加下一行会使它太大,请发送它,重置字符串并继续。

然后,如有必要,发送字符串的最后一部分(不会在 for 循环中自动发送)。

注意:下面这个例子假设你有一个channel来发送消息,用ctxuser替换它或不管你的意图是什么。 Channel 只是为了这个例子。

# Entire ascii image as a list of lines (not joined into one string)
asciiImage = list(newImageData[i:(i + newWidth)] for i in range(0, pixelCount, newWidth))

# String to send
send_str = ""

for line in asciiImage:
    # Adding this line would make it too big
    # 1998 = 2000 - 2, 2 characters for the newline (\n) that would be added
    if len(send_str) + len(line) > 1998:
        # Send the current part
        await channel.send(send_str)
        # Reset the string
        send_str = ""

    # Add this line to the string
    send_str += line + "\n"
    
# Send the remaining part
if send_str:
    await channel.send(send_str)