【问题标题】:Random tips. Discord.py随机提示。不和谐.py
【发布时间】:2021-09-09 20:18:28
【问题描述】:

我希望我的机器人在运行命令时从提示列表中发送随机提示。

另外,我希望它只偶尔显示提示。

我的意思是,例如,用户键入命令hi 然后它当然应该说hi。但只有在命令运行一定次数时才会显示提示。

所以如果命令运行 5 次,那么我希望我的命令每执行 5 次,应该显示一个提示。

不像我有一个发送随机提示的命令。

例如,如果我有一个 unban 命令,它可以每运行 5 次命令发送一个提示,例如“你也可以使用 kick 和 ban 命令。使用 -help 了解更多信息。”

我希望你明白我想说的,这就是你需要的所有信息。

这是受到 Dank Memer 的启发

【问题讨论】:

    标签: discord discord.py


    【解决方案1】:

    只需以某种方式存储一个计数器并使用random 模块来选择一个随机提示

    如果对命令使用函数:

    import random
    hi_counter = 0
    hi_tips = [
      "You can also use kick and ban commands. Use `-help` for more info.",
      "a tip",
      "another tip",
      "yet another tip",
    ]
    
    @bot.command('hi')
    async def hi(ctx):
      global hi_counter, hi_tips
      await ctx.send('hi')
      hi_counter += 1
      if hi_counter % 5 == 0:
        await asyncio.sleep(1)
        await ctx.send(random.choice(hi_tips))
    

    如果您将 Cog 用于命令:

    import random
    
    class hi(commands.Cog):
      def __init__(self, bot):
        self.bot = bot
        self.counter = 0
        self.tips = [
          "You can also use kick and ban commands. Use `-help` for more info.",
          "a tip",
          "another tip",
          "yet another tip",
        ]
    
      @commands.command('hi')
      async def hi(self, ctx):
        await ctx.send('hi')
        self.counter += 1
        if self.counter % 5 == 0:
          await asyncio.sleep(1)
          await ctx.send(random.choice(self.tips))
    
    def setup(bot):
      bot.add_cog(hi(bot))
    

    如果你想为此做一个装饰器,你也可以这样做:

    import random
    
    def tips(times: int, tips: List[str]):
      counter = 0
    
      def decorator(func):
        nonlocal counter, tips
        async def wrapper(*args, **kwargs):
          nonlocal counter, tips
          ctx = func(*args, **kwargs)
          counter += 1
          if counter % times == 0:
            await asyncio.sleep(1)
            await ctx.send(random.choice(tips))
        return wrapper
      return decorator
    
    # Use it like:
    @bot.command('hi')
    @tips(5, [
      "You can also use kick and ban commands. Use `-help` for more info.",
      "a tip",
      "another tip",
      "yet another tip",
    ])
    async def hi(ctx):
      global hi_counter, hi_tips
      await ctx.send('hi')
      return ctx # MAKE SURE TO RETURN `ctx` OR THE DECORATOR WON'T WORK
    

    【讨论】:

    • 您的回答非常有帮助,但是,您能否稍微解释一下您的回答。因为我对 discord.py 有点陌生。非常感谢您的解释。
    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2021-11-20
    • 1970-01-01
    • 2021-07-07
    • 2020-12-18
    • 2021-09-30
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多