Reputation: 128
I need help with Discord.py
I tried to create a guessing game. The bot creates a random number between 1 and 20 (including 20), and then you try to guess it in 6 or less than 6 tries. When you send a number, it will tell you if thats too high/low.
Here is my code:
@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}")
However, when I send the command, it will send the beginning part, but when I send a number, it won't respond.
Upvotes: 1
Views: 267
Reputation: 555
The input()
function is for console
input, not Discord. To await a message in Discord, use client.wait_for()
:
message = await client.wait_for("message")
You can also write a check
function to check if the message matches your conditions:
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)
If the checkfunction returns True, the code will continue, else it will wait for another message.
You can now implement this into your code:
@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}")
You can find more about the client.wait_for()
function here.
Upvotes: 1