【发布时间】:2021-06-09 13:44:05
【问题描述】:
我有一个命令可以查找服务器中最旧和最新的用户。它检查每个用户,直到找到所有必要的信息。它工作正常,直到我在一个有 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)
我对 Discord 机器人还很陌生,从 YouTube 或这里学到了一切。虽然这是我第一次真正寻求帮助。有什么想法吗??
【问题讨论】:
标签: performance optimization discord.py