首页 > 解决方案 > discord.py:关于如何加快此命令处理时间的想法

问题描述

我有一个命令可以查找服务器中最旧和最新的用户。它检查每个用户,直到找到所有必要的信息。它工作正常,直到我在一个有 2000 个用户的服务器中使用它需要大约 10 秒的时间来处理,并且我不能在那个时候使用任何其他命令来处理机器人。命令代码:

    @commands.command()
    async def oldest(self, ctx, page: int=1):
        await oldest_newest(self, ctx, page, "Oldest")
    # tnewest
    @commands.command()
    async def newest(self, ctx, page: int=1):
        await oldest_newest(self, ctx, page, "Newest")

async def oldest_newest(self, ctx, page, sort_type):
    page = abs(int(page))
    if page > 99: page = 99

    x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = x9 = x10 = None
    searchint = (page-1)*10
    for x in ctx.guild.members:
        if sort_type == "Oldest": creation_pos = sum(m.created_at < x.created_at for m in ctx.guild.members if m.created_at is not None) + 1
        if sort_type == "Newest": creation_pos = sum(m.created_at > x.created_at for m in ctx.guild.members if m.created_at is not None) + 1
        if creation_pos == searchint+1: x1 = x
        if creation_pos == searchint+2: x2 = x
        if creation_pos == searchint+3: x3 = x
        if creation_pos == searchint+4: x4 = x
        if creation_pos == searchint+5: x5 = x
        if creation_pos == searchint+6: x6 = x
        if creation_pos == searchint+7: x7 = x
        if creation_pos == searchint+8: x8 = x
        if creation_pos == searchint+9: x9 = x
        if creation_pos == searchint+10: x10 = x 
    
    members_sorted =[]
    if x1 is not None: members_sorted.append(x1)
    if x2 is not None: members_sorted.append(x2)
    if x3 is not None: members_sorted.append(x3)
    if x4 is not None: members_sorted.append(x4)
    if x5 is not None: members_sorted.append(x5)
    if x6 is not None: members_sorted.append(x6)
    if x7 is not None: members_sorted.append(x7)
    if x8 is not None: members_sorted.append(x8)
    if x9 is not None: members_sorted.append(x9)
    if x10 is not None: members_sorted.append(x10)

    cycle_int = 0
    output_string = ""
    for x in members_sorted:
        cycle_int = cycle_int + 1
        output_string += f"**{cycle_int+((page-1)*10)}** - {x} - {x.created_at.strftime('%d/%m/%Y')}\n"

    em = discord.Embed(color=self.client.Blue)
    em.add_field(name=f"{sort_type} accounts in **{ctx.guild.name}**", value=output_string, inline=False)

    em.set_footer(text=f"Page: {page}")
    em.timestamp = datetime.utcnow()
        
    await ctx.send(embed=em)

我对不和谐机器人还很陌生,从 YouTube 或这里学到了一切。虽然这是我第一次真正寻求帮助。有任何想法吗??

标签: performanceoptimizationdiscord.py

解决方案


我不能 100% 确定它是否更快,因为我无法在大型服务器上自己测试它,但是您可以尝试让每个成员连同他们的 created_at 日期,将其附加到列表中,然后按 created_at 对列表进行排序日期。

非常简化的例子:

    @commands.command()
    async def oldestmember(self, ctx):
        everyuser = []
        for member in ctx.guild.members:
            userinfo = (member.name, member.created_at)
            everyuser.append(userinfo)
    
        everyuser.sort(key=lambda x:x[1])

        print(everyuser)

然后,如果您想获得最新的成员,您可以使用everyuser.reverse().

希望这至少有一点帮助


推荐阅读