简体   繁体   中英

Discord.py Guessing game taking a number as an input

I am trying to make a number guessing game with discord.py. My problem is that I can't figure out how to take a number/variable as input. This is my code:

if command.startswith('r?guess'):

await message.channel.send("Starting...")
time.sleep(1)
number = random.randint(1,10)
print(number)
await message.channel.send('guess the number with r numbergess(number here) its 1-10!')
if command.startswith('r?numberguess '):
    number = int(command.split(" ")[1])
if 1 <= number <= 10:
    if guess == number:
          print("you got it!")
    else:
          print("placeholder")

Some help would be greatly appreciated. Thanks..

As @Poojan said use wait_for . Here is how I made this mini game.

import discord
from discord.ext import commands
import random
from random import randrange

client = commands.Bot(command_prefix = "?")
Token = "XXXXXXXX" #your token


@client.event
async def on_message(message):
    if message.content.startswith("?start"): #command to start quessing game
        channel = message.channel
        await channel.send("Quess the number from 0-10 by writing number in this channel!") #message that tells about the start of the game

        number1 = random.randint(1,10) #picking random number from 1 - 10 and printing it
        print(number1)
        
        number2 = str(number1) #converting int to str

        def check(m):
            return m.content == number2 and m.channel == channel #checking answers
        
        msg = await client.wait_for('message', check=check)
        await channel.send("Correct answer {.author}" .format(msg)) #tells who got the answer

You should use wait_for with a check

def check(m):
    return m.author == message.author and m.channel == message.channel

message = await bot.wait_for("message", check=check)
message = int(message.content.split(" ")[1])

What you can do further is add a limited time for the user to input a number and use try-except to convert message.content to int as sometimes user won't send a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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