【问题标题】:How to make a timer command in discord.py?如何在 discord.py 中创建计时器命令?
【发布时间】:2021-01-16 21:39:21
【问题描述】:

我想做一个定时器命令。

    @commands.command()
    async def timer(self, ctx, seconds):
        try:
            secondint = int(seconds)
            if secondint > 300:
                await ctx.send("I dont think im allowed to do go above 300 seconds.")
                raise BaseException
            if secondint < 0 or secondint == 0:
                await ctx.send("I dont think im allowed to do negatives")
                raise BaseException
            message = await ctx.send("Timer: " + seconds)
            while True:
                secondint = secondint - 1
                if secondint == 0:
                    await message.edit(new_content=("Ended!"))
                    break
                await message.edit(new_content=("Timer: {0}".format(secondint)))
                await asyncio.sleep(1)
            await ctx.send(ctx.message.author.mention + " Your countdown Has ended!")
        except ValueError:
            await ctx.send("Must be a number!")

我试过了,但这不起作用,它不会像我想要的那样编​​辑消息并且没有错误。

【问题讨论】:

  • 只是把它放在这里,但这是实现计时器的一种非常糟糕的方式,因为它会占用整个线程并正在积极等待。这个问题的未来观众,请查看tasks.loopdiscord tasks

标签: python discord discord.py python-asyncio


【解决方案1】:

它不会编辑消息,因为 new_content 不是 Message.edit() 方法参数。
它只有:content / embed / suppress / delete_after / allowed_mentions。

你要找的是content:

@commands.command()
async def timer(self, ctx, seconds):
    try:
        secondint = int(seconds)
        if secondint > 300:
            await ctx.send("I dont think im allowed to do go above 300 seconds.")
            raise BaseException
        if secondint <= 0:
            await ctx.send("I dont think im allowed to do negatives")
            raise BaseException
        message = await ctx.send("Timer: {seconds}")
        while True:
            secondint -= 1
            if secondint == 0:
                await message.edit(content="Ended!")
                break
            await message.edit(content=f"Timer: {secondint}")
            await asyncio.sleep(1)
        await ctx.send(f"{ctx.author.mention} Your countdown Has ended!")
    except ValueError:
        await ctx.send("Must be a number!")

【讨论】:

    【解决方案2】:

    唯一有效的方法是如果你做这样的事情

    import asyncio
    
    @client.command()
    async def count(ctx, number:int):
        try:
            if number < 0:
                await ctx.send('number cant be a negative')
            elif number > 300:
                await ctx.send('number must be under 300')
            else:
                message = await ctx.send(number)
                while number != 0:
                    number -= 1
                    await message.edit(content=number)
                    await asyncio.sleep(1)
                await message.edit(content='Ended!')
    
        except ValueError:
            await ctx.send('time was not a number')
    

    【讨论】:

      【解决方案3】:

      好的,下面是上面标有绿色复选标记的脚本的修改版本。我进行了一些更改以使其更加用户友好(单位转换器将例如“5m”转换为 300 秒,而不是显示“90 秒”,而是显示“1 分 30 秒”等),并且更容易供大众使用。我不擅长编码,我处于初学者水平,但我希望这会有所帮助!

      @commands.command()
      async def timer(self, ctx, timeInput):
          try:
              try:
                  time = int(timeInput)
              except:
                  convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, 'S':1, 'M':60, 'H':3600, 'D':86400}
                  time = int(timeInput[:-1]) * convertTimeList[timeInput[-1]]
              if time > 86400:
                  await ctx.send("I can\'t do timers over a day long")
                  return
              if time <= 0:
                  await ctx.send("Timers don\'t go into negatives :/")
                  return
              if time >= 3600:
                  message = await ctx.send(f"Timer: {time//3600} hours {time%3600//60} minutes {time%60} seconds")
              elif time >= 60:
                  message = await ctx.send(f"Timer: {time//60} minutes {time%60} seconds")
              elif time < 60:
                  message = await ctx.send(f"Timer: {time} seconds")
              while True:
                  try:
                      await asyncio.sleep(5)
                      time -= 5
                      if time >= 3600:
                          await message.edit(content=f"Timer: {time//3600} hours {time %3600//60} minutes {time%60} seconds")
                      elif time >= 60:
                          await message.edit(content=f"Timer: {time//60} minutes {time%60} seconds")
                      elif time < 60:
                          await message.edit(content=f"Timer: {time} seconds")
                      if time <= 0:
                          await message.edit(content="Ended!")
                          await ctx.send(f"{ctx.author.mention} Your countdown Has ended!")
                          break
                  except:
                      break
          except:
              await ctx.send(f"Alright, first you gotta let me know how I\'m gonna time **{timeInput}**....")
      

      【讨论】:

        猜你喜欢
        • 2021-03-19
        • 2021-12-21
        • 2020-12-12
        • 1970-01-01
        • 1970-01-01
        • 2023-02-26
        • 2021-06-20
        • 1970-01-01
        • 2021-05-11
        相关资源
        最近更新 更多