在Python中Discord bot,计算来自用户的消息

时间:2017-06-11 19:32:17

标签: python bots discord

我目前正在尝试使用python创建一个机器人,从服务器上的通道收集统计信息。我想看看用户在某个频道发送了多少条消息。目前我的代码如下所示:

if message.content.startswith('!stat'):
        mesg = await client.send_message(message.channel, 'Calculating...')
        counter = 0
        async for msg in client.logs_from(message.channel, limit=9999999):
            if msg.author == message.author:
                counter += 1
        await client.edit_message(mesg, '{} has {} messages in {}.'.format(message.author, str(counter), message.channel))

这基本上可以满足我的需求,但计算所有消息的过程非常缓慢。是否有另一种方法可以实现相同的结果,但响应速度更快?

1 个答案:

答案 0 :(得分:0)

你可以:

  • 使用limit时降低client.logs_from。您也可以保留限制,因为机器人最有可能尝试获取不存在的消息。

  • 每个x消息与用户交互。例如:

    counter = 0
    repeat = 0
    for x in range(0, 4): # Repeats 4 times
        async for msg in client.logs_from(message.channel, limit=500):
            if msg.author == message.author:
                counter += 1
        repeat += 1
    await client.send_message(message.channel, "{} has {} out of the first {} messages in {}".format(message.author, str(counter), 500*repeat, message.channel))
    

它会返回这样的东西:

User has 26 out of the first 500 messages in channel
User has 51 out of the first 1000 messages in channel

discord.py API参考:http://discordpy.readthedocs.io/en/latest/api.html#discord.Client.logs_from