【问题标题】:Is it possible to make a command !messages @user是否可以发出命令 !messages @user
【发布时间】:2020-08-18 03:51:44
【问题描述】:

我正在尝试创建一个命令,当有人键入例如“!messages @mee6”时,它会显示该人在服务器中说了多少消息。所以说如果我输入“a”“b”“c”然后输入“!messages” 机器人会回复“@user 已在此服务器中发送 3 条消息。有谁知道这是否可行,如果可以,我将如何在 discord.py 中执行此操作?

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    您可以通过迭代服务器中的每个文本通道,然后迭代通道中的每条消息来做到这一点。然后统计用户发送的消息量。

    @bot.command()
    async def message(ctx, user: discord.User):
      count = 0
      for channel in ctx.message.guild.text_channels:
        async for message in channel.history(limit=None):
          if message.author.id == user.id:
            count += 1
    
      await ctx.channel.send(('{} has sent {} messages').format(user.mention, count))
    

    【讨论】:

      【解决方案2】:

      这是我的方法,但我相信这样做需要一些时间,特别是如果服务器很大,因为您正在检查每个频道。

      
      @bot.command()
      async def messages(ctx, user: discord.Member = None):
          if user is None:
              # no user selected author is the user now
              user = ctx.author
          counter = 0
      
          for channel in ctx.guild.text_channels:
              async for message in channel.history(limit=None):
                  if message.author == user:
                      counter += 1
      
          await ctx.send(f'{user.mention} has sent {counter} messages')
      

      【讨论】:

        【解决方案3】:

        原理如下: 您必须利用 Message Received 事件。收到消息后,更新此人的计数,并在运行 !messages 命令时显示金额。

        遍历服务器中的每个通道并过滤来自用户的所有消息非常低效且耗时,而且它可能会限制您的机器人速率。

        【讨论】:

          【解决方案4】:

          使用事件on_message(),这样您就可以从现在开始统计来自每个用户的消息。

          创建一个字典,其中包含用户作为键,消息数量作为值

          users_msg = {}
          
          @client.event
          async def on_message(message):
          
              #If this is the first user messsage
              if message.author not in users_msg:
                  users_msg[message.author] = 1
          
              else:
                  users_msg[message.author] += 1
          
              if message.content.startswith("!message"):
          
                  #Return a list containing all user mentions on the message
                  user = message.mentions
          
                  #Send the first user mention amount of messages
                  await message.channel.send(f'{user[0].mention} has sent {users_msg[user[0]]}'
          
                  #If you want so you can loop through every user mention on the command !message
                  #for mentions in user:
                      #await message.channel.send(f'{mentions.mention} has sent {users_msg[mentions]}')
          

          【讨论】:

            猜你喜欢
            • 2010-09-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-19
            相关资源
            最近更新 更多