这是一个反垃圾邮件代码,以防止垃圾邮件和东西。
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}")嘿,伙计们,我这里有个错误。它工作正常,但是当有人继续发送垃圾邮件时,机器人就会继续发送垃圾邮件,它就会变得一团糟。大约一分钟后,机器人继续发送垃圾邮件,所以停止垃圾邮件,否则我将使您静音。
发布于 2021-07-18 07:52:20
你需要在事件中排除你自己的机器人消息。因此,这应该是可行的:
@client.event
async def on_message(message):
if message.author == client.user:
return
#rest of your codehttps://stackoverflow.com/questions/68423937
复制相似问题