python - 如何获取 channel 中所有消息的列表,然后从该列表中随机选择一条消息作为消息发送?

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

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

因此,如果 channel 中的众多消息中有一条消息,例如:

Bring me pain, sir.

它会发送该消息,但每次运行命令时选择发送的消息都会被随机化。

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

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

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

如果有帮助,这里是古宾(匿名,但是):

<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() 。

最佳答案

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

content

The actual contents of the message.

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

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

关于python - 如何获取 channel 中所有消息的列表,然后从该列表中随机选择一条消息作为消息发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64142597/

相关文章:

python - 如何在 Python 的 seaborn 中将 tsplot 与 FacetGrid 一起使用?

python - multiprocessing.Value 无法正确存储 float

python - 为什么它重复即使 WHILE 循环更改为 False

python - PyQt5 和 Anaconda : ModuleNotFoundError: No module named 'PyQt5'

javascript - 在纯粹的、基于浏览器的 JavaScript 中接收不和谐消息?

python - 使用列表项将列表项转换为字典

python - 如何为 to_csv() 设置空格作为分隔符? - Python

python - `yield from` 可以与什么样的对象一起使用?

javascript - 如何让 Discord 机器人等待我的消息?

python - 如何使用discord.py删除角色?