【问题标题】:discord.py rewrite | How would I make this into an integer?discord.py 重写 |我怎么把它变成一个整数?
【发布时间】:2019-02-15 20:12:04
【问题描述】:

我正在尝试创建一个激活随机数猜谜游戏的命令。显然,我被困在前几行。我已经写了我认为会起作用的东西,但是它可能是公然错误的。我希望它将不和谐服务器上的消息更改为 int,因此它将在我的 if 语句中工作。

这是我第一次使用 discord.py 制作机器人,所以我遇到了很多障碍。我不完全确定错误告诉我什么,所以我无法尝试任何修复。这是代码:

async def numgame(context):
    number = random.randint(1,100)
    for guess in range(0,5):
        await context.send('Pick a number between 1 and 100')
        Message = await client.wait_for('message')
        Message = int(Message)
        if Message.cleant_content > number:
            await context.send(guess + ' guesses left...')
            asyncio.sleep(1)
            await context.send('Try going lower')
            asyncio.sleep(1)
       elif Message.clean_content < number:
            await context.send(guess + ' guesses left...')
            asyncio.sleep(1)
            await context.send('Try going higher')
            asyncio.sleep(1)
        else:
            await context.send('You guessed it! Good job!')
    if number != Message:
        await context.send('Tough luck!')

每当我在我的 discord 服务器中执行命令时,我的 shell 都会给我这个错误:

discord.ext.commands.errors.CommandInvokeError:命令引发异常:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“消息”

我不太确定它在告诉我什么。如前所述,我希望“消息”是一个整数,但我得到了错误。但我们将不胜感激! [还是初学者,别太苛刻:(]

【问题讨论】:

    标签: python python-3.x discord.py discord.py-rewrite


    【解决方案1】:

    wait_for('message') 返回一个Message 对象,int 还不知道如何处理。您需要将 Message.content 转换为 int。下面是您的代码以及其他一些更改:

    def check(message):
        try:
            int(message.content)
            return True
        except ValueError:
            return False
    
    @bot.command()
    async def numgame(context):
        number = random.randint(1,100)
        for guess in range(0,5):
            await context.send('Pick a number between 1 and 100')
            msg = await client.wait_for('message', check=check)
            attempt = int(msg.content)
            if attempt > number:
                await context.send(str(guess) + ' guesses left...')
                await asyncio.sleep(1)
                await context.send('Try going lower')
                await asyncio.sleep(1)
           elif attempt < number:
                await context.send(str(guess) + ' guesses left...')
                await asyncio.sleep(1)
                await context.send('Try going higher')
                await asyncio.sleep(1)
            else:
                await context.send('You guessed it! Good job!')
                break 
        else:
            await context.send("You didn't get it")
    

    【讨论】:

    • 将其更改为“await context.send(str(guess) + ' guesses left...')”后,它工作正常!非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2021-09-28
    • 2020-11-06
    相关资源
    最近更新 更多