如何获取频道中所有消息的列表,然后从该列表中随机选择一条消息作为消息发送?
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?
我之前尝试在 Whosebug 上寻找这个问题的答案并找到了 。我在 Python 3.7 上试用了 discord.py 重写 1.5.0。它应该从我发送它的频道给我一条随机消息,并将其作为消息发送。
所以如果在频道的众多消息中有这样一条消息:
Bring me pain, sir.
它会发送该消息,但每次命令 运行.
时,选择发送的消息将随机化
这是我的代码:(出于安全原因,该频道是匿名的)
channel = client.get_channel(123456789101112131)
messages = await channel.history(limit=200).flatten()
await ctx.send(f"{random.choice(messages)}")
它给了我一堆与发送消息的 guild/channel/author 有关的垃圾信息,而不是随机消息。这虽然有帮助,但不是我想要的。
如果有帮助,这里是 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() 作为代码。
快速浏览 discord.py、the history()
method you're using looks like it returns a list of Messages. The docs for that type show that it has a content
property 的文档,这听起来像您想要的:
content
The actual contents of the message.
您的代码导致整个 Message 对象被转换为字符串,这就是为什么您会看到内部表示的各个部分(category_id
、discriminator
等)。试试这个:
await ctx.send(f"{random.choice(messages).content}")
我之前尝试在 Whosebug 上寻找这个问题的答案并找到了
所以如果在频道的众多消息中有这样一条消息:
Bring me pain, sir.
它会发送该消息,但每次命令 运行.
时,选择发送的消息将随机化这是我的代码:(出于安全原因,该频道是匿名的)
channel = client.get_channel(123456789101112131)
messages = await channel.history(limit=200).flatten()
await ctx.send(f"{random.choice(messages)}")
它给了我一堆与发送消息的 guild/channel/author 有关的垃圾信息,而不是随机消息。这虽然有帮助,但不是我想要的。
如果有帮助,这里是 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() 作为代码。
快速浏览 discord.py、the history()
method you're using looks like it returns a list of Messages. The docs for that type show that it has a content
property 的文档,这听起来像您想要的:
content
The actual contents of the message.
您的代码导致整个 Message 对象被转换为字符串,这就是为什么您会看到内部表示的各个部分(category_id
、discriminator
等)。试试这个:
await ctx.send(f"{random.choice(messages).content}")