我正在研发一个调平机器人.我发现了获得XP的一个主要问题,它很容易被滥用.我想让它在用户发送消息后有一个冷却时间,这样当用户在一个渠道向XP农场发送垃圾邮件时,他们对每条消息有0.5秒的冷却时间,以防止垃圾邮件.如果你发了很多垃圾短信,你很容易就能登上榜首,我不希望这种情况发生.每件事都与它一起工作,XPyield ,排行榜,以及升级消息.我在互联网上寻找了这个问题的答案,但没有一个起到帮助作用.有人知道吗?请多多关照!:)

代码:

@bot.event
async def on_message(message):
    if not message.author.bot:
        # specify the encoding as utf-8 when opening the file
        with open('level.json','r', encoding='utf-8') as f:
            users = json.load(f)
        await update_data(users, message.author,message.guild)
        await add_experience(users, message.author, 4, message.guild)
        await level_up(users, message.author,message.channel, message.guild)

        # specify the encoding as utf-8 when writing the file
        with open('level.json','w', encoding='utf-8') as f:
            json.dump(users, f)
    await bot.process_commands(message)




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

async def add_experience(users, user, exp, server):
  users[str(user.guild.id)][str(user.id)]['experience'] += exp

async def level_up(users, user, channel, server):
  experience = users[str(user.guild.id)][str(user.id)]['experience']
  lvl_start = users[str(user.guild.id)][str(user.id)]['level']
  lvl_end = int(experience ** (1/4))
  if str(user.guild.id) != '757383943116030074':
    if lvl_start < lvl_end:
      await channel.send(':fire: {} has leveled up to **Level {}!**'.format(user.mention, lvl_end))
      users[str(user.guild.id)][str(user.id)]['level'] = lvl_end
      embed=discord.Embed(title=':fire: {} has leveled up to **Level {}!**'.format(user.mention, lvl_end), color=0x38ff6a)
      await bot.get_channel(log_channel_id).send(embed=embed)

@bot.command(aliases = ['rank','lvl'])
async def level(ctx,member: discord.Member = None):
    if not member:
        user = ctx.message.author
        # specify the encoding as utf-8 when opening the file
        with open('level.json','r', encoding='utf-8') as f:
            users = json.load(f)
        lvl = users[str(ctx.guild.id)][str(user.id)]['level']
        exp = users[str(ctx.guild.id)][str(user.id)]['experience']

        embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP " ,color = discord.Color.green())
        embed.set_author(name = ctx.author, icon_url = ctx.author.avatar.url)
        await ctx.send(embed = embed)
    else:
      # specify the encoding as utf-8 when opening the file
      with open('level.json','r', encoding='utf-8') as f:
          users = json.load(f)
      lvl = users[str(ctx.guild.id)][str(member.id)]['level']
      exp = users[str(ctx.guild.id)][str(member.id)]['experience']
      embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP" ,color = discord.Color.green())
      embed.set_author(name = member, icon_url = member.avatar.url)

      await ctx.send(embed = embed)

JSON文件示例:

{
  "757383943116030074": {
    "123456789012345678": {
      "experience": 0,
      "level": 1
    }
  }
}

推荐答案

您可以使用字典来跟踪每个用户的最后一条消息时间,然后判断此时间戳以实施冷却.

# Create a dictionary to keep track of last message times
message_cooldown = {}

@bot.event
async def on_message(message):
    if not message.author.bot:
        # Check if the user is in the cooldown dictionary
        if message.author.id in message_cooldown:
            current_time = time.time()
            last_message_time = message_cooldown[message.author.id]

            # Check if the user's cooldown has expired (0.5 seconds cooldown)
            if current_time - last_message_time < 0.5:
                return

        with open('level.json', 'r', encoding='utf-8') as f:
            users = json.load(f)
        await update_data(users, message.author, message.guild)
        await add_experience(users, message.author, 4, message.guild)
        await level_up(users, message.author, message.channel, message.guild)

        # Update the last message time for the user
        message_cooldown[message.author.id] = time.time()

        with open('level.json', 'w', encoding='utf-8') as f:
            json.dump(users, f)
    await bot.process_commands(message)

在这里,我们使用Time模块来计算每个用户的消息之间经过的时间,并设置0.5秒的冷却时间.Message_Cooldown字典存储每个用户的最后一条消息时间.如果冷却时间尚未到期,则忽略该消息.

Python相关问答推荐

如何将我的位置与光强度数据匹配到折射图案曲线中?

创建带有二维码的Flask应用程序,可重定向到特定端点

查找下一个值=实际值加上使用极点的50%

通过交换 node 对链接列表进行 Select 排序

优化在numpy数组中非零值周围创建缓冲区的函数的性能

在Python中对分层父/子列表进行排序

当多个值具有相同模式时返回空

如何将双框框列中的成对变成两个新列

使用索引列表列表对列进行切片并获取行方向的向量长度

在Python Attrs包中,如何在field_Transformer函数中添加字段?

当独立的网络调用不应该互相阻塞时,'

PyQt5,如何使每个对象的 colored颜色 不同?'

使用密钥字典重新配置嵌套字典密钥名

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

计算分布的标准差

具有相同图例 colored颜色 和标签的堆叠子图

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

Autocad使用pyautocad/comtypes将对象从一个图形复制到另一个图形

为什么dict. items()可以快速查找?

如果服务器设置为不侦听创建,则QWebSocket客户端不连接到QWebSocketServer;如果服务器稍后开始侦听,则不连接