我目前正在用Python做一个不和谐的机器人。我要创建一个命令,其中有两个参数选项:
我已经尝试过类似的功能来确定它是否是字符串...
def isint(s):
try:
int(s)
isint = True
except ValueError:
isint = False
return isint
...但是它返回此错误:
TypeError: '<=' not supported between instances of 'str' and 'int'
这是我尝试过的命令的当前最新代码:
@commands.command()
@commands.has_role("Clear Chat Key")
async def clear(self, ctx, amount: typing.Union[str, int] = 10):
number = isint(amount)
if number == False:
if amount == 'all':
await ctx.channel.purge(limit = inf)
else:
await ctx.send('Invalid amount.')
if number == True:
await ctx.channel.purge(limit = amount)
else:
await ctx.send('Invalid amount.')
有关此错误的完整追溯信息如下:
Traceback (most recent call last):
File "C:\Users\44794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\44794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\44794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<=' not supported between instances of 'str' and 'int'
请在这里忍受,我是Python的新手。
编辑: 感谢您为我提供帮助!这是我在其他人需要时使用的代码:
def is_int(x):
if x.isdigit():
return True
return False
@commands.command()
@commands.has_role("Clear Chat Key")
async def clear(self, ctx, amount: typing.Union[str, int] = 10):
number = is_int(amount)
if number == False:
if amount == 'all':
await ctx.channel.purge(limit = inf)
else:
await ctx.send('Invalid amount.')
if number == True:
amount = int(amount)
await ctx.channel.purge(limit = amount)
else:
await ctx.send('Invalid amount.')
再次感谢您的帮助!
答案 0 :(得分:0)
请尝试使用此功能代替功能isint
:
# clear function
number = amount.__class__.__name__ == 'int'
答案 1 :(得分:0)
您可以使用字符串的.isdigit()
方法。
请记住,这将为底片返回False
:
>>> my_str = "123"
>>> my_str.isdigit()
True
>>> other_str = "-123"
>>> my_str.isdigit()
False
工作示例:
def is_int(some_value):
if some_input.isdigit():
return True
return False
some_input = input("Enter some numbers or words!\n-> ")
print(is_int(some_input))
参考: