【问题标题】:How to keep track of messages sent in discord.py如何跟踪 discord.py 中发送的消息
【发布时间】:2021-02-28 02:33:41
【问题描述】:
我想跟踪并为 discord.py 中发送的每条消息分配一个编号,我正在构建一个反垃圾邮件机器人,基本上每次有人发送消息时,我都希望它添加到用户消息数量的计数器中已经发送了一定的时间,然后我希望它每隔 5 秒重置一次计数器。
@b.event
async def on_message(message):
await b.process_commands(message)
#Add 1 to a user specific counter
if counter > 5:
await message.send("Stop sending messages")
#Reset the counter every 20 seconds
【问题讨论】:
标签:
python
python-3.x
discord
discord.py
【解决方案1】:
首先,您需要创建一个字典来跟踪每个用户发送了多少消息。
spam_logger = {}
其次,当发送消息时,您希望将用户添加到字典中。如果用户存在于字典中,我们在他们发送的消息数量上加一,如果他们不存在于字典中,我们添加他们的名字并给它一个值。
@client.event
async def on_message(message):
global spam_logger
try:
spam_logger[str(message.author)] += 1
except KeyError:
spam_logger[str(message.author)] = 1
第三,我们要检查用户是否发送了超过 5 条消息。
for name, messages_sent in spam_logger.items():
if messages_sent >= 5:
await message.channel.send(f'Stop sending messages!')
最后,我们希望每 5 秒清除一次列表。
@tasks.loop(seconds=5)
async def clear_spam_logger():
global spam_logger
spam_logger.clear()
@clear_spam_logger.before_loop
async def before():
await client.wait_until_ready()
clear_spam_logger.start()