在一个不和谐的服务器上找到“前10名”用户的最佳(即最快)方法是什么不和谐.py

2024-03-29 12:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向Python discord bot添加一些基本的stat bot功能。事实上我已经有了一种非常慢的方法。我希望bot最多能在2到3秒钟内做出响应,但即使在我的小型个人服务器上,仅仅用我的代码计算它也花了很长时间:

@bot.command(pass_context=True)
@is_Admin()
async def top10(ctx):
    """Prints a pretty graph of top 10 users in the server"""
    server = ctx.guild
    users = [[0 for x in range(0, len(server.members))] for x in range(0, 2)] 
    users[0] = [u.id for u in server.members]
    h = 0
    for channel in server.text_channels:
        hist = await channel.history(limit=None).flatten()
        for message in hist:
            au = message.author
            if au.bot == False:
                try:
                    i = users[0].index(au.id)
                    users[1][i] += 1
                except ValueError as e:
                    pass

就像我说的,很慢。我想一定有更好的方法来做到这一点,而不是获取服务器中每个频道的完整历史记录,然后计算用户发出消息的次数,但我被难住了。有人帮忙吗?你知道吗


Tags: 方法in服务器idforserverbotchannel
1条回答
网友
1楼 · 发布于 2024-03-29 12:27:47

您可以对代码进行更多的优化以使其运行得更快,因为您正在访问所有文本通道中发送的每一条消息,甚至文档都指出将limit设置为None是一个缓慢的操作:

limit (Optional[int]) – The number of messages to retrieve. If None, retrieves every message in the channel. Note, however, that this would make it a slow operation.

不过,仍然可以进行一些小的优化,例如在开始时不创建三个成员列表,并使用collections模块以方便统计。你知道吗

from collections import Counter

@bot.command(pass_context=True)
@is_Admin()
async def top10(ctx):
    top = Counter()      
    for channel in ctx.guild.text_channels:
        async for message in channel.history(limit=None):
            author = message.author
            if not author.bot:
                top[author.id] += 1
    print([x[0] for x in top.most_common(10)])

相关问题 更多 >