如何防止 Python Discord Bot 因垃圾邮件而升级

How To Prevent Leveling Up From Spam For A Python Discord Bot

所以,最近我一直在 python 开发一个 discord 机器人,当你在 discord 服务器上聊天时,它会提升你的水平,许多流行的机器人,如 Carl Bot 和 MEE6 都有这样的功能,我觉得很有趣;所以我想尝试重新创建它。该机器人工作得非常好,但它确实有一些我想尝试并修复的警告,因为没有办法检查您的等级或获得服务器前 10 名玩家的排行榜。但是,我想在这里找到并解决的问题是您可以发送垃圾邮件;毫无意义的消息和许多只需要一两个的消息。那么,我该怎么做,我怎样才能防止我的系统中产生垃圾邮件。如有任何帮助,我们将不胜感激!

from discord.ext import commands
import json
import discord
import os
import random
import time

client = commands.Bot(command_prefix = "!")

#On Ready Event.
@client.event
async def on_ready():
  print("Bot Ready.")
  time.sleep(1)
  print("Logged In As:  {0.user}".format(client))

#Function For Getting A Users Information And Level Them Up.
@client.event
async def on_member_join(member):
  with open("users.json", "r") as f:
    users = json.load(f)

  await update_data(users, member)

  with open("users.json", "w") as f:
    json.dump(users, f)

#Function For Sending Messages.
@client.event
async def on_message(message):
  with open("users.json", "r") as f:
    users = json.load(f)

  await update_data(users, message.author)
  await add_experience(users, message.author, 5)
  await level_up(users, message.author, message.channel)

  with open("users.json", "w") as f:
    json.dump(users, f)

async def update_data(users, user):
  if not str(user.id) in users:
    users[str(user.id)] = {}
    users[str(user.id)]["experience"] = 0
    users[str(user.id)]["level"] = 1

async def add_experience(users, user, exprience):
  users[str(user.id)]["experience"] += exprience

async def level_up(users, user, channel):
  experience = users[str(user.id)]["experience"]
  level_start = users[str(user.id)]["level"]
  level_end = int(experience ** (1/4))

  if level_start < level_end:
    await channel.send(f"{user.mention} Has Leveled Up!  They Have Leveled Up To Level {level_end}!")
    users[str(user.id)]["level"] = level_end

client.run(os.getenv("Token"))
client.run(os.environ["Token"])

确保会员不会发送垃圾邮件并仍然获得积分的方法是请求某种形式的计时系统。为此,您需要能够存储数据。但是,您可能不需要持久性数据存储并且可以使用字典。

在这个例子中,我存储了一个成员的最后一条消息,以秒为单位从 time.time() 开始,并检查他们最后记录的消息时间戳是否 从现在开始小于 60 秒.这将只允许成员一次收到他们的消息分钟数。此外,请注意我只在收到积分后更新会员的最后一条消息。这可确保他们仍然可以每分钟发送多条消息,并且仍会因间隔一分钟的消息而获得积分。

from time import time

member_messages = {}

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

    current_time = time()
    last_message_requirement = current_time - 60  # Change this cooldown (in seconds) however you like

    if member_messages.get(message.author.id, 0) <= last_message_requirement:
        with open("users.json", "r") as f:
            users = json.load(f)

        await update_data(users, message.author)
        await add_experience(users, message.author, 5)
        await level_up(users, message.author, message.channel)

        with open("users.json", "w") as f:
            json.dump(users, f)

        member_messages[message.author.id] = current_time