如何在添加前检查,如果它会使字符串太长

我一直在尝试使用1028个字符的嵌入的Discord限制。这意味着,如果超出该字符,由于限制,我们将无法发布嵌入内容。

我一直在尝试找出如何“尽可能安全”地做到这一点。现在,我有一个测试数据:

{
    'sizes': ['<https://test.com&token=e4d6j4f25476dcee4b08744d382dc405b&ipa=1768677|36>',
              '<https://test.com&token=e4d64f25g476dcee4b08744d382dc405b&ipa=1768878|37>',
              '<https://test.com&token=e4d64f25h476dcee4b08744d382dc405b&ipa=1763879|38>',
              '<https://test.com&token=e4d64f254g76dcee4b08744d382dc405b&ipa=1769880|39',
              '<https://test.com&token=e4d64f2547ö6dcee4b08744d382dc405b&ipa=1768881|40',
              '<https://test.com&token=e4d64f25k476dcee4b08744d382dc405b&ipa=1766882|41',
              '<https://test.com&token=e4d64f25j476dcee4b08744d382dc405b&ipa=1768583|42',
              '<https://test.com&token=e4d64f25l476dcee4b08744d382dc405b&ipa=1768484|43',
              '<https://test.com&token=e4d6t4f25476dcee4b08744d382dc405b&ipa=1768385|44']
}

并且我确实设法创建了一个代码,如果到达嵌入,则会添加一个新的嵌入:

characterCount, i = 0, 0
for j, item in enumerate(sizelist):

    if len(item) + characterCount > 900:
        data['attachments'][0]['fields'].append(
            {
                'title': 'Sizes',
                'value': '\n'.join(sizelist[i:j]) if len(sizelist) else '*Sizes not found*',
                'short': True
            }
        )
        characterCount, i = len(item), j
    else:
        characterCount += len(item)
if characterCount:
    data['attachments'][0]['fields'].append(
        {
            'title': 'Sizes',
            'value': '\n'.join(sizelist[i:]) if len(sizelist) else '*Sizes not found*',
            'short': True
        }
    )

The problem I am facing as you can see is that I do just have a check if if len(item) + characterCount > 900: and that means there is still a chance that if I find a exact characters that is lower than 900 but still extends the accepted embed then I will get failed.

我从有人告诉我的提示:

如果1028限制适用于整个数据对象,则需要执行   解决一些约束,并决定您是否愿意   如果尺寸不合适,那么没有通用的解决方案   在这里知道您想要的行为。

问题是,如果添加时间太长,如何在添加之前进行检查?

评论