【问题标题】:How could I grab all chat messages in a specific channel in a discord server using discord.py?如何使用 discord.py 在不和谐服务器的特定频道中获取所有聊天消息?
【发布时间】:2021-01-20 11:57:44
【问题描述】:

我的机器人有管理员权限,所以我只是想知道是否可以从 1 个频道获取所有消息,例如 #general。

【问题讨论】:

    标签: discord bots discord.py discord.py-rewrite


    【解决方案1】:

    频道历史

    这是可能的,有一个函数可以做到这一点:channel.history()

    此函数可用于检索在频道中发送的所有消息。但是,如果您要检索包含数千条消息的频道中的所有消息,则速度非常慢。


    示例

    此示例展示了如何检索在特定频道中发送的每条消息:

    async def get_history_of_channel(channel):
        messages = await channel.history(limit=None) # adding None lets us retrieve every message
        for message in messages:
            # do something with that message
            print(message.content)
    

    参考文献

    【讨论】:

      【解决方案2】:
      • 您可以使用channel.history 执行此操作
      • map 将函数应用于每个元素。
      • flatten 使其成为一个列表。

      您可以将限制更改为None 以获取所有消息,但这需要一些时间。

      def transform(message):
          return message.content
      
      
      @bot.command()
      async def history(ctx, channel: discord.TextChannel):
          messages_in_channel = await channel.history(limit=10).map(transform).flatten()
      
          print(messages_in_channel)
      

      用法:{prefix}history #channel_mention

      【讨论】:

      • 会打印到控制台吗?机器人不会这么说
      • 这只是为了显示你想要的是数据。例如,您可以按照您想要的方式输出它。 await ctx.send('\n'.join(messages_in_channel))。请记住,有字符限制。
      猜你喜欢
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多