如何识别变量的类型?

时间:2019-05-25 11:48:03

标签: discord.py

我正在为不和谐创建一个清晰的命令,所以我想这样做,以便每当您输入字符串而不是int时,它都会在聊天室中发送一条消息“请使用数字”。

我已经尝试过if isinstance(amount, int):,但似乎不起作用。

脚本V

@client.command()
async def clear(ctx, amount=1):
    role = discord.utils.get(ctx.guild.roles, name="[+] Admin")
    if role in ctx.author.roles:
        if isinstance(amount, int):
            print('int')
        else:
            print('str')

    else:
        await ctx.send(f'You lack the permissions.', delete_after=3)```

> It can identiy if it is an int value

``` Bot is ready. int```

> But not strings.

```Bot is ready.
Ignoring exception in command clear:
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 367, in _actual_conversion
    return converter(argument)
ValueError: invalid literal for int() with base 10: 'Hello'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\bot.py", line 859, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 718, in invoke
    await self.prepare(ctx)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 682, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 596, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 452, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 405, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 376, in _actual_conversion
    raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "amount".

1 个答案:

答案 0 :(得分:0)

使用converter并编写一个error handler来处理如果输入不能转换为int引发的错误:

从discord.ext.commands导入BadArgument

@client.command()
async def clear(ctx, amount: int=1):
    ...

@clear.error
async def clear_error(ctx, error):
    if isinstance(error, BadArgument):
        await ctx.send("Invalid integer argument.")
    else:
        raise error