【问题标题】:Make /afk command accept numbers not letters in python使 /afk 命令在 python 中接受数字而不是字母
【发布时间】:2021-04-11 21:37:04
【问题描述】:

我希望当有人执行 /AFK 并写字母而不是数字时,它应该显示类似“输入数字而不是字母”的内容。这是我的代码:

async def afk(ctx, mins : int):
    current_nick = ctx.author.nick
    await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.", delete_after=5)
    await ctx.author.edit(nick=f"[AFK]{ctx.author.name}")

    counter = 0
    while counter <= int(mins):
        counter += 1
        await asyncio.sleep(60)

        if counter == int(mins):
            await ctx.author.edit(nick=current_nick)
            await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
            break```

【问题讨论】:

    标签: python command discord discord.py


    【解决方案1】:

    你需要去掉 typehint 然后使用 try/except

    async def afk(ctx, mins):
        try:
            mins = int(mins)
        except ValueError:
            return await ctx.send("input numbers not letters")
        # your other code
    

    【讨论】:

      【解决方案2】:

      试试这个:

      async def afk(ctx, mins : int):
          try:
              mins = int(mins)
          except ValueError:
              # ...
              # <send the message here.>
              # ...
              return
      
          current_nick = ctx.author.nick
          await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.", delete_after=5)
          await ctx.author.edit(nick=f"[AFK]{ctx.author.name}")
      
          asyncio.sleep(60 * mins)
      
          await ctx.author.edit(nick=current_nick)
          await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
      

      在这里,我们尝试将 mins 转换为 int,如果失败,则发送消息。否则,照常继续。我认为您也可以像我在这里所做的那样删除 while 循环和 if 语句。

      【讨论】:

      • 它不起作用,如果他们执行 /afk bruh,我的代码曾经显示为“有人在 bruh 时刻陷入困境”,但使用您的代码它不会向某些人发送任何消息原因。如何发送消息?我做了await ctx.send('Please use numbers.') 这是错的吗?
      【解决方案3】:

      一般我同意@Poojan's answer,但有一种比try/except 更简单的方法:

      async def afk(ctx, mins):
          if not mins.isdigit():
              return await ctx.send("input numbers not letters")
          mins = int(mins)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-22
        • 2022-11-25
        • 1970-01-01
        • 2022-11-02
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 2021-01-22
        相关资源
        最近更新 更多