rab*_*ton 3 python time python-3.x discord discord.py
对于不和谐机器人和 python 以及构建反垃圾邮件机器人来说非常陌生,这是我的代码:
import discord
from discord.ext import commands
import time
b = commands.Bot(command_prefix='not a bot')
b.remove_command("help")
@b.event
async def on_ready():
print('Bot is Ready')
authors = {}
authors1 = []
@b.event
async def on_message(ctx):
global authors
global authors1
author_id = ctx.author.id
for author2 in authors1:
if author_id == author2:
authors[author_id] += 1
else:
authors[author_id] = 1
authors1.append(author_id)
stop = False
timer = 5
while stop == False:
if timer > 0:
time.sleep(0.985)
timer -= 1
if authors[author_id] > 5:
await ctx.send("Stop Spamming")
else:
timer = 5
authors[author_id] = 0
b.run('stack overflow')
Run Code Online (Sandbox Code Playgroud)
基本上,在每条消息上,它都会获取每个用户的不和谐 ID,然后为其分配一个值,默认值为 1,因为用户刚刚发送了一条消息,其中 while 循环启动是一个计时器,每 5 秒重置一次,如果发送该消息的用户message 已发送 5 条消息,它告诉他们停止发送垃圾邮件,我不知道为什么会收到错误,而且由于我是 python 新手,我可以使任何代码更简单,如果您能让我,我将不胜感激知道。
这是我不断收到的错误
Bot is Ready
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\12488\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 333, in _run_even
await coro(*args, **kwargs)
File "C:\Users\12488\Downloads\Bot\antispam.py", line 31, in on_message
if authors[author_id] > 5:
KeyError: 234295307759108106
Run Code Online (Sandbox Code Playgroud)
一些东西:
无论如何,我认为下面的代码将完成您想要的操作。
import discord
from discord.ext import commands
import datetime
import time
b = commands.Bot(command_prefix='not a bot')
b.remove_command("help")
time_window_milliseconds = 5000
max_msg_per_window = 5
author_msg_times = {}
# Struct:
# {
# "<author_id>": ["<msg_time>", "<msg_time>", ...],
# "<author_id>": ["<msg_time>"],
# }
@b.event
async def on_ready():
print('Bot is Ready')
@b.event
async def on_message(ctx):
global author_msg_counts
author_id = ctx.author.id
# Get current epoch time in milliseconds
curr_time = datetime.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 ctx.send("Stop Spamming")
b.run('stack overflow')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7134 次 |
| 最近记录: |