反垃圾邮件代码也不断向机器人发送垃圾邮件

时间:2021-07-17 20:07:33

标签: python discord discord.py

这是一个反垃圾邮件代码,用于防止垃圾邮件和其他东西。

time_window_milliseconds = 5000
max_msg_per_window = 5
author_msg_times = {}
# Struct:
# {
#    "<author_id>": ["<msg_time", "<msg_time>", ...],
#    "<author_id>": ["<msg_time"],
# }


@client.event
async def on_message(message):
    global author_msg_counts

    author_id = message.author.id

    # Get current epoch time in milliseconds
    curr_time = datetime.now().timestamp() * 1000

    # Make empty list for author id, if it does not exist
    if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    # Append the time of this message to the users list of message times
    author_msg_times[author_id].append(curr_time)

    # Find the beginning of our time window.
    expr_time = curr_time - time_window_milliseconds

    # Find message times which occurred before the start of our window
    expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    # Remove all the expired messages times from our list
    for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    # ^ note: we probably need to use a mutex here. Multiple threads
    # might be trying to update this at the same time. Not sure though.

    if len(author_msg_times[author_id]) > max_msg_per_window:
            await message.channel.send(f"{message.author.mention} stop spamming or i will mute you ?")
            await asyncio.sleep(4)
            await message.channel.send(f"{message.author.mention} stop spamming or i will mute you ?")

            muted = discord.utils.get(message.guild.roles, name="Muted")

            if not muted:
                muted = await message.guild.create_role(name="Muted")

            await message.author.send(f"You have been muted in {message.guild.name} for spamming | You'll be unmuted in 10 minutes.")
            await message.author.add_roles(muted)
            await message.channel.send(f"{message.author.mention} have been muted for 10 minutes.")
            await asyncio.sleep(600)
            await message.channel.send(f"{message.author.mention} have been unmuted | Reason: Time is over. ")
            await message.author.remove_roles(muted)
            await message.author.send(f"You have been unmuted from {message.guild.name}")

嘿伙计们,我在这里遇到错误。它工作正常,但是当有人继续发送垃圾邮件时,机器人会继续发送垃圾邮件,并且变得一团糟。大约一分钟后,机器人继续发送垃圾邮件,所以请停止发送垃圾邮件,否则我会让你静音。

1 个答案:

答案 0 :(得分:2)

您需要在事件中排除您自己的机器人消息。所以这应该有效:

@client.event
async def on_message(message):
    if message.author == client.user:
        return
#rest of your code