【问题标题】:How to improve antispam function discord.py?如何改进反垃圾邮件功能 discord.py?
【发布时间】:2021-08-17 23:11:42
【问题描述】:

我正在制作一个不和谐的机器人,并且我内置了反垃圾邮件功能,但我想改进它。我不希望此功能对某些角色做出反应,例如管理员或版主(因此我希望此功能不对某些角色做出反应,因此管理员可以发送垃圾邮件)。另外我有垃圾邮件频道,我不希望此功能起作用,我该怎么做?最后但并非最不重要的一点是:如何删除相同的(垃圾邮件)消息?因为我的机器人所做的是:它说“停止垃圾邮件”。但我想删除相同的消息。非常感谢!我希望你能帮助我!

代码:

    import os
    import discord
    import datetime
    
    intents = discord.Intents.all()
    bot = commands.Bot(command_prefix='$', intents=intents)
    
    time_window_milliseconds = 5000
    max_msg_per_window = 5
    author_msg_times = {}
    
    @bot.event
    async def on_message(ctx): #spam allowed in channel and for admins? How to make?
    
      global author_msg_counts
    
      author_id = ctx.author.id
      curr_time = datetime.datetime.now().timestamp() * 1000
    
      if not author_msg_times.get(author_id, False):
          author_msg_times[author_id] = []
    
      author_msg_times[author_id].append(curr_time)
    
      expr_time = curr_time - time_window_milliseconds
    
      expired_msgs = [
          msg_time for msg_time in author_msg_times[author_id]
          if msg_time < expr_time
      ]
      for msg_time in expired_msgs:
          author_msg_times[author_id].remove(msg_time)
    
      if len(author_msg_times[author_id]) > max_msg_per_window:
        await ctx.delete(ctx)
        await ctx.send("Stop Spamming")
    
      else:
        print("You are good to go!")
              
    bot.run(os.getenv('token'))

【问题讨论】:

    标签: datetime discord discord.py message spam-prevention


    【解决方案1】:

    关于角色的第一个问题,您应该在垃圾邮件检查开始时添加:

    if ctx.author.guild_permissions.manage_messages:
        return
    

    这将使其不会影响任何有权删除消息的成员(这将是版主或管理员)。

    你也可以这样做

    if ctx.channel.id == [id here]:
        return
    

    将 [id here] 替换为您的垃圾邮件频道的 ID。 最后,将await ctx.send("Stop Spamming") 放在await ctx.delete(ctx) 之前,并确保您的机器人有权删除消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-21
      • 2019-12-26
      • 2014-05-19
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      相关资源
      最近更新 更多