How can I automatically split a list up based on a given requirement?

若如初见. 提交于 2021-02-11 15:21:02

问题


On Discord, you can only have messages of character length 2000 or under. I am trying to append the server name, member amount and server ID for each server that the bot is in to a list, and then sending the list to a channel.

However, as the list length exceeds 2000 I have tried to split it up, however the method requires it to be updated every time manually as the list gets larger. How can I make the script automatically split up the list based on how many 'splits' are required and then send those 'splits'?

What I have so far, which works, but is not automatic:

@commands.command()
async def getallservers(self, ctx):
    serverslist = []

    def split_list(alist, wanted_parts=1):
        length = len(alist)
        return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
                for i in range(wanted_parts) ]

    if ctx.author.id == 204616460797083648:
        for x in self.bot.guilds:
            serverslist.append(f'{x.name}: **{len(x.members)}** - {x.id}\n')

        q1,q2,q3,q4,q5,q6 = split_list(serverslist, wanted_parts=6)

        embed = discord.Embed(title='Server List')

        embed.description = ''.join(q1)
        await ctx.send(embed=embed)
        embed.description = ''.join(q2)
        await ctx.send(embed=embed)
        embed.description = ''.join(q3)
        await ctx.send(embed=embed)
        embed.description = ''.join(q4)
        await ctx.send(embed=embed)
        embed.description = ''.join(q5)
        await ctx.send(embed=embed)
        embed.description = ''.join(q6)
        await ctx.send(embed=embed)
    else:
        pass

回答1:


One you have the serverslist, you can pass it to a function that builds < 2000 character pages

def paginate(lines, chars=2000):
    size = 0
    message = []
    for line in lines:
        if len(line) + size > chars:
            yield message
            message = []
            size = 0
        message.append(line)
        size += len(line)
    yield message

then in your command

for message in paginate(serverlist):
    embed.description = ''.join(message)
    await ctx.send(embed=embed)


来源:https://stackoverflow.com/questions/54956638/how-can-i-automatically-split-a-list-up-based-on-a-given-requirement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!