为了账号安全,请及时绑定邮箱和手机立即绑定

当我发送号码时,discord.py 机器人没有响应。猜数字游戏的一部分

当我发送号码时,discord.py 机器人没有响应。猜数字游戏的一部分

智慧大石 2024-01-04 09:47:11
我需要有关 Discord.py 的帮助我尝试创建一个猜谜游戏。机器人会创建一个 1 到 20(包括 20)之间的随机数,然后您尝试在 6 次或少于 6 次的时间内猜测它。当您发送号码时,它会告诉您该号码是否太高/太低。这是我的代码:@client.command()async def guessnumber(ctx):    user = ctx.author    await ctx.send(f"Hello {user}! I'm thinking of a number between 1 and 20. You are given 6 tries to find the number. Good luck!")    secretNumber = random.randint(1,20)    for guessesTaken in range(1,7):        guess = int(input())        if guess < secretNumber:            await ctx.send("Your guess is too low")        elif guess > secretNumber:            await ctx.send("Your guess is too high")        else:            break        if guess == secretNumber:        await ctx.send(f"GG! You correctly guessed the number!")    else:        await ctx.send(f"Nope, sorry, you took to many guesses. The number I was thinking of was {secretNumber}")但是,当我发送命令时,它会发送开头部分,但是当我发送数字时,它不会响应。
查看完整描述

1 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

该input()功能用于console输入,而不是 Discord。要在 Discord 中等待消息,请使用client.wait_for():


message = await client.wait_for("message")

您还可以编写一个check函数来检查消息是否符合您的条件:


def checkfunction(message):

    return message.author == ctx.author and ctx.channel == message.channel and message.content.isdigit() 


message = await client.wait_for("message", check=checkfunction)

如果 check 函数返回 True,则代码将继续,否则它将等待另一条消息。

您现在可以将其实现到您的代码中:


@client.command()

async def guessnumber(ctx):


    await ctx.send(f"Hello {ctx.author.name}! I'm thinking of a number between 1 and 20. You are given 6 tries to find the number. Good luck!")

    secretNumber = random.randint(1,20)


    def check(message):

        return message.author == ctx.author and message.channel == ctx.channel  and message.content.isdigit()


    for guessesTaken in range(6):


        guess = int((await client.wait_for('message', check=check)).content)


        if guess < secretNumber:

            await ctx.send("Your guess is too low")

        elif guess > secretNumber:

            await ctx.send("Your guess is too high")

        else:

            await ctx.send(f"GG! You correctly guessed the number in {guessesTaken + 1} guesses!")


    else:

        await ctx.send(f"Nope, sorry, you took too many guesses. The number I was thinking of was {secretNumber}")


查看完整回答
反对 回复 2024-01-04
  • 1 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信