首页 > 解决方案 > 你如何检查一个字符串是否可以转换为 int,如果可以,转换它?(Python,涉及discord.py重写)

问题描述

我目前正在用 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.')

再次感谢您帮助我!

标签: url-rewritingintdiscord.py

解决方案


尝试使用它而不是你的函数isint

# clear function
number = amount.__class__.__name__ == 'int'

推荐阅读