【问题标题】:How can I automatically split a list up based on a given requirement?如何根据给定要求自动拆分列表?
【发布时间】:2019-07-24 04:41:02
【问题描述】:

在 Discord 上,您只能接收字符长度为 2000 或以下的消息。我正在尝试将机器人所在的每个服务器的服务器名称、成员数量和服务器 ID 附加到列表中,然后将列表发送到频道。

但是,由于列表长度超过 2000,我尝试将其拆分,但是该方法要求每次随着列表变大手动更新它。如何使脚本根据需要多少“拆分”自动拆分列表,然后发送这些“拆分”?

到目前为止我所拥有的,它有效,但不是自动的:

@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

【问题讨论】:

  • 不直接相关,但您应该使用库的内置检查而不是命令中的if owner: ... else: pass
  • 是的 - 这只是我为测试命令而添加的临时内容 - 肯定会改变它!谢谢!
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: python discord discord.py discord.py-rewrite


【解决方案1】:

你有一个serverslist,你可以将它传递给一个构建

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

然后在你的命令中

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 2020-11-19
  • 2020-06-22
  • 2019-03-06
  • 2020-07-18
  • 2019-01-11
  • 1970-01-01
相关资源
最近更新 更多