如何防止用户在频道中发送多条消息?

2022-01-15 00:00:00 python python-3.x discord.py

问题描述

User 1: Hello!
User 1: How are you?
User 2: I'm good.
User 2: hbu
User 3: hey guys!
User 1: i'm doing fine

我正在尝试从用户 1 和用户 2 中删除第二条消息,这样任何用户都只能发送一条消息.我被告知要使用 channel.history,但我想不出一种方法来比较消息的作者以确保它们不是同一个人.

I'm trying to delete the second message from User 1 and User 2, so that any user can only send a single message. I was told to use channel.history, but I can't think of a way to compare the author's of the messages to make sure they aren't the same person.

这就是我想要的:我想防止重复发布:

This is what I want: I want to prevent double posting:

User 1: Hello! How are you?
User 2: I'm good, hbu.
User 3: hey guys!
User 1: i'm doing fine

我只是不知道如何使用 channel.history 来做到这一点.

I just don't know how to use channel.history to do this.


解决方案

您可以使用 on_message() 事件并将频道历史记录的限制设置为 2:

You can use the on_message() event and set the channel history's limit to 2 for this:

@bot.event
async def on_message(message):
    recent_author = (await message.channel.history(limit=2).flatten())[1].author
    if message.author == recent_author:
        await message.delete()

history() 协程首先获取最新消息,除非另有说明,因此您可以将限制设置为 2 以获取用户刚刚发送的消息之前的最新消息.

The history() coroutine gets the newest messages first, unless specified otherwise, so you can set the limit to 2 to get the most recent message before the one the user just sent.

参考资料:

  • Messageable.history()
  • Message.author
  • Message.delete()

相关文章