Python Discord.py检查输入是否为int
我正在尝试使用discord.py为我的bot编写一个抽奖命令,希望用户可以执行以下命令来启动抽奖: !!抽奖时间优胜者头衔如:!抽奖60 1派 我遇到的问题是创建验证来检查前两个输入是否为数字,以及标题是否为空。目前,这是我的命令代码:Python Discord.py检查输入是否为int,python,discord.py,Python,Discord.py,我正在尝试使用discord.py为我的bot编写一个抽奖命令,希望用户可以执行以下命令来启动抽奖: !!抽奖时间优胜者头衔如:!抽奖60 1派 我遇到的问题是创建验证来检查前两个输入是否为数字,以及标题是否为空。目前,这是我的命令代码: @bot.command(pass_context=True) async def raffle(ctx, time, winners, title): if time != int or winners != int or title !=
@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.
任何帮助都将是伟大的,因为我相信这是一个简单的错误的地方
提前感谢尝试改用
isinstance
:
if not isinstance(time, int)
您定义的实际上是两个检查。第一个是要确保命令有3个参数,第二个是要确保前两个是int 第一个命令实际上是由ext.commands在内部处理的。要捕获它,您需要定义一个
on\u命令\u错误
事件方法
@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
第二个是检查int,正如@Luke McPuke所说的,这很简单
if not isinstance(time, int)
时间!=int
etc没有意义。用try/except.把它包装起来,你能详细说明一下吗?我在谷歌上搜索了try/except,但我不知道它如何与代码相匹配。我正在打电话,所以我无法写答案。但您当前的方法是检查某些内容是否等于内置方法。相反,使用try/except尝试将您的输入转换为intI don't think I understand OP实际要求的内容。似乎他们需要对输入使用try/except或断言,但他们的错误消息使他们似乎没有在函数中包含除此raffle()之外的必要参数。我要寻找的是一种检查以下三个输入是否正确的方法!抽奖有效。例如时间和胜利者是整数,标题不为空。@KaiJones那么是的,断言类型(时间)==int,“时间参数不是整数”
或者使用isinstance
达到同样的效果也可以。你的标题代码应该很好。谢谢你的回复,我想我明白你的意思了。我现在有下面的代码与您的更改,但仍然得到相同的问题。如果我把它放进去!抽奖我得到一个控制台错误,如果我把!抽奖6我被发送到报表的其他部分。