首页 > 解决方案 > 如何限制一次输出的字符数,以便图像到 ASCII 转换器输出不一致,每条消息限制为 2000 个字符

问题描述

我有一个与 discord bot 一起工作的图像到 ASCII 转换器,因此人们可以将图像发送给它,它会下载图像并将其转换为 ASCII 并将其发送回给他们,但是由于 Discord 将每个消息限制为 2000 个字符,因此它经常会卡住制作图像大小合理。

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

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

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

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

标签: pythondiscord.pyascii-artimage-conversion

解决方案


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

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

注意:下面的这个例子假设你有一个channel发送消息,用ctxoruser或任何你的意图替换它。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)

推荐阅读