【问题标题】:How can I get a list of all the messages in a channel and then pick a random message from that list to send as a message?如何获取频道中所有消息的列表,然后从该列表中选择一条随机消息作为消息发送?
【发布时间】:2021-01-16 10:07:33
【问题描述】:

我之前尝试在 StackOverflow 上寻找这个问题的答案,发现 this。我在 discord.py rewrite 1.5.0 上的 Python 3.7 上进行了尝试。它应该从我发送它的频道给我一条随机消息,并将其作为消息发送。

因此,如果频道中的许多消息中有一条消息,例如:

给我带来痛苦,先生。

它将发送该消息,但每次运行命令时选择发送的消息将是随机的。

这是我的代码:(出于安全原因,该频道已匿名)

channel = client.get_channel(123456789101112131)
messages = await channel.history(limit=200).flatten()
await ctx.send(f"{random.choice(messages)}")

它不是随机消息,而是给我一堆与发送消息的公会/频道/作者有关的垃圾信息。这虽然有帮助,但不是我想要的。

如果有帮助,这里是 gubbins(不过是匿名的):

<Message id=42365698915833262 channel=<TextChannel id=123456789101112131 name='general' position=1 nsfw=False news=False category_id=None> type=<MessageType.default: 0> author=<Member id=481541758625098605 name='me' discriminator='4444' bot=False nick=None guild=<Guild id=111222333444555666 name='GUILDNAME' shard_id=None chunked=True member_count=4>> flags=<MessageFlags value=0>>

(对不起,如果我不做代码,它将无法正确显示)

我不知道它为什么这样做。我知道我做错了什么,但我不知道如何解决它。我是一名业余程序员,所以我可能会遗漏一些非常明显的东西。如果您想知道,我正在使用 client.command() 作为代码。

【问题讨论】:

    标签: python python-3.x discord discord.py discord.py-rewrite


    【解决方案1】:

    快速浏览一下 discord.py 的文档,the history() method you're using 看起来像是返回了 Messages 的列表。 docs for that type 表明它有一个 content property,这听起来像你想要的:

    content

    消息的实际内容。

    您的代码导致整个 Message 对象转换为字符串,这就是为什么您会看到内部表示的各个部分(category_iddiscriminator 等)。试试这个:

    await ctx.send(f"{random.choice(messages).content}")
    

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2018-12-15
      • 2020-09-24
      • 2021-06-28
      • 2021-01-19
      相关资源
      最近更新 更多