简体   繁体   English

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

[英]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?

I tried looking on StackOverflow for the answer to this question before and found this .我之前尝试在 StackOverflow 上寻找这个问题的答案,并找到了这个 I tried it out on Python 3.7 on discord.py rewrite 1.5.0.我在 Python 3.7 上的 discord.py rewrite 1.5.0 上进行了尝试。 It should give me a random message from the channel I sent it in, and send it as a message.它应该从我发送它的频道中给我一条随机消息,并将其作为消息发送。

So if there was a message among the many messages in the channel like:因此,如果频道中的许多消息中有一条消息,例如:

Bring me pain, sir.给我带来痛苦,先生。

It would send that message, but the message chosen to be sent would be randomized each time the command would be run.它会发送该消息,但每次运行该命令时,选择发送的消息都会随机化。

Here's my code: (the channel is anonymized for safety reasons)这是我的代码:(出于安全原因,频道已匿名)

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

Instead of a random message, it gives me a bunch of junk information relating to the guild/channel/author that sent the message.它不是随机消息,而是给我一堆与发送消息的公会/频道/作者相关的垃圾信息。 Which, while helpful, isn't what I'm going for.这虽然有帮助,但不是我想要的。

If it helps, here's the gubbins (anonymized, however):如果有帮助,这里是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>>

(sorry, it won't show correctly if I don't make it code) (抱歉,如果我不编写代码,它将无法正确显示)

I have no idea why it's doing this.我不知道为什么要这样做。 I know I'm doing something wrong, but I don't know how to fix it.我知道我做错了什么,但我不知道如何解决。 I'm an amateur programmer, so I might be missing something completely obvious.我是一名业余程序员,所以我可能会遗漏一些非常明显的东西。 I'm using a client.command() for the code, in case you are wondering.我正在使用 client.command() 作为代码,以防您想知道。

From a quick glance at the docs for discord.py, the history() method you're using looks like it returns a list of Messages .快速浏览一下 discord.py 的文档, 您使用的history()方法看起来像是返回一个Messages列表。 The docs for that type show that it has a content property , which sounds like what you want:类型文档显示,它有一个content属性,这听起来像你想要什么:

content

The actual contents of the message.消息的实际内容。

Your code is causing the whole Message object to be converted to a string, which is why you're seeing various parts of the internal representation ( category_id , discriminator , etc.).您的代码导致整个 Message 对象转换为字符串,这就是为什么您会看到内部表示的各个部分( category_iddiscriminator等)。 Try this instead:试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM