首页 文章

Discord.py检查输入是否为int

提问于
浏览
1

我正在尝试使用discord.py为我的机器人编写一个抽奖命令,并希望用户可以执行以下命令来启动抽奖:

!抽奖时间获奖者名称EG:!抽奖60 1馅饼

我遇到的问题是创建验证以检查前两个输入是否为数字并且 Headers 不是空白 . 目前这是我对命令的代码:

@bot.command(pass_context=True)
async def raffle(ctx, time, winners, title):    

    if time != int or winners != int or title != "":
        await bot.say("{} raffle has been started for {} seconds and there will be {} winner(s)!".format(title, time, winners))
    else:
        await bot.say("Seems you went wrong! Raffle format is: !raffle time winners title")
        return

但是我没有运气并且收到以下错误:

Ignoring exception in command raffle
Traceback (most recent call last):
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke
    yield from self.prepare(ctx)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 345, in prepare
    yield from self._parse_arguments(ctx)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 304, in _parse_arguments
    transformed = yield from self.transform(ctx, param)
  File "C:\Users\kairj\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 212, in transform
    raise MissingRequiredArgument('{0.name} is a required argument that is missing.'.format(param))
discord.ext.commands.errors.MissingRequiredArgument: time is a required argument that is missing.

任何帮助都会很棒,因为我确信这是一个简单的错误!

提前致谢

2 回答

  • 0

    请尝试使用 isinstance 代替:

    if not isinstance(time, int)
    
  • 0

    你定义的实际上是两个检查 . 第一个是你要确保你的命令有3个参数,第二个是确保前两个是int .

    第一个实际上是由内部的ext.commands处理的 . 要捕获它,您需要定义一个 on_command_error 事件方法 .

    @bot.event
    def on_command_error(exc, ctx):
        if isinstance(exc, commands.errors.MissingRequiredArgument):
            # Send a message here
            return
    
        # If nothing is caught, reraise the error so that it goes to console.
        raise exc
    

    第二个是检查整数,正如@Luke McPuke所说的那样简单

    if not isinstance(time, int)
    

相关问题