url-rewriting - 你如何检查一个字符串是否可以转换为 int,如果可以,转换它?(Python,涉及discord.py重写)
问题描述
我目前正在用 Python 制作一个不和谐的机器人。我想创建一个命令,其中您有两个参数选项:
- 删除一定数量消息的整数
- 和单词'all'(一个字符串)删除频道中的所有消息。
我试过这样的函数来确定它是否是一个字符串......
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.')
再次感谢您帮助我!
解决方案
尝试使用它而不是你的函数isint
:
# clear function
number = amount.__class__.__name__ == 'int'
推荐阅读
- vue.js - 在 Nuxt 颜色模式下使用 SCSS 变量
- php - PHP关闭期间的“断管”E_NOTICE,关闭套接字上的陈旧数据?
- python - 绘制 Pandas 数据集
- javascript - Node.js 限制 API 请求并将队列限制为 1
- python - discord bot command import text from text file
- rest - 从 Bitbucket rest api 获取 SonarQube PR 装饰状态
- tensorflow - 谷歌深度学习平台无法使用 tensorflow 2.3
- django - SMTP 数据错误。550 b 表单地址与已验证的发件人身份不匹配
- java - 图像未在第二个活动中显示
- node.js - 访问/修改 React 服务器代码