我如何限制字符输出的数量在一次图像到ASCII转换器输出与每条消息2000字符限制不一致



我有一个图像到ASCII转换器与一个不和谐机器人工作,所以人们可以给它发送一个图像,它下载它并将其转换为ASCII并将其发送回给他们,但由于不和谐限制消息为2000个字符,它经常卡住制作合理大小的图像。

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

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)

最新更新