繁体   English   中英

discord.py 返回带有 ValueError 的输入:int() 的无效文字,基数为 10:'hey'

[英]discord.py returns input with ValueError: invalid literal for int() with base 10: 'hey'

我正在制作一个不和谐机器人,它将接受输入并将其存储在一个 int 变量中,以便稍后将其写入文本文件:

@client.command()
async def createproject(ctx):

    def check(m):
        return m.author == ctx.message.author
    
    await ctx.send("This is a test")
    msg = await client.wait_for("message", check = check, timeout = 30)
    desc = int(msg.content)
    await ctx.send(desc)

机器人成功地发送了“这是一条测试消息”并且它一直完美运行,直到出现这个错误

指定的错误代码是:

File "c:/Users/data/Desktop/discord bot/main.py", line 101, in createproject
    desc = int(msg.content)
ValueError: invalid literal for int() with base 10: 'hey'

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

Traceback (most recent call last):
  File "C:\Users\data\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\data\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\data\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: 
ValueError: invalid literal for int() with base 10: 'hey'

感谢您的帮助。

在第 9 行中,您尝试使用desc = int(msg.content)msg.content更改为整数。 但是,如果消息包含非数字字母,则会引发此错误。 如果您只想获取整数消息,可以使用str.isdigit函数。 你可以检查一下:

msg = await client.wait_for("message", check = check, timeout = 30)
if msg.isdigit():
    desc = int(msg.content)

所以你的代码应该是这样的:

@client.command()
async def createproject(ctx):

    def check(m):
        return m.author == ctx.message.author
    
    await ctx.send("This is a test")
    msg = await client.wait_for("message", check = check, timeout = 30)
    if msg.isdigit():
        desc = int(msg.content)
    else:
        await ctx.send('Please type numbers only')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM