dimanche 17 mai 2020

how can I do a check before adding if it would make it too long string

I have been trying to work with Discord limitation of embeds which are 1028 characters. Meaning if we go above that characters we will not be able to post a embed due to the limitation.

I have been trying to figure out how I can do it as "safe" and as possible as it can be. Now right I have a test data:

{
    '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']
}

and I did managed to create a code that adds a new embed if it reaches the embed:

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.

I got a tip from someone telling me:

If the 1028 limit is for the entire data object you would need to do some constraint solving, and decide whether you would rather have just the sizes if it doesn't fit, There is no generic solution without knowing your desired behavior here.

The question is that how can I do a check before adding if it would make it too long?

Aucun commentaire:

Enregistrer un commentaire