【问题标题】:Making a guessing game in discord.py在 discord.py 中做一个猜谜游戏
【发布时间】:2020-12-29 02:10:16
【问题描述】:

我一直在尝试制作一个不和谐的机器人,它会在发送!play 消息时开始游戏。在游戏中,有一个变量的值是随机选择的,如果您预测正确的数字(1 到 10 之间),则将发送"You win" 消息,如果大于或小于则将相应地发送消息。我知道我搞砸了,因为我是第一次使用 discord.py。 我的代码:

    if message.content.startswith("!play"):
        await message.channel.send("Choose a number between 1-10. Enter numerical values only.")
        num = random.randint(1,10)  
        try:   
            if message.content.startswith(str(num)):
                await message.channel.send("You won.")
            elif int(message.content) > num:
                await message.channel.send("Go a bit lower.")
            elif int(message.content) < num:
                await message.channel.send("Go a bit up.")
        except Exception as e:
            await message.channel.send("Check inputs.")

请帮忙

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    这里:

    # imports the discord module and the random module.
    import discord
    from discord.ext import commands
    import random
    
    client = discord.Client()
    
    
    client = commands.Bot(command_prefix = "!")
    Token = "" #your token
    
    
    @client.event
    async def on_message(message):
        if message.content.startswith("!play"): #the play command to start the guessing game.
            channel = message.channel
            await channel.send("Choose a number between 1-10. Enter numerical values only.") #message that tells about the start of the game
    
            # generates a random number and turns it into a string
            number1 = random.randint(1,10)        
            number2 = str(number1)
    
    
            def check(m):
                return m.content == number2 and m.channel == channel 
            """
              The check function, first it checks if the message is the correct number.
              Then it checks if the channel is the same channel as the channel that the play command was sent in.
              If both is true, then it returns true. Else it returns false.
            """
            
            msg = await client.wait_for('message', check=check) #waits for the check function to return true
            await channel.send("Correct answer {.author}" .format(msg)) #sends the correct answer message
            
    client.run(Token)
    

    这应该可行。 我在这里有一个工作机器人:https://discord.com/api/oauth2/authorize?client_id=793152585346711573&permissions=8&scope=bot
    示例:https://i.stack.imgur.com/ou60F.png

    【讨论】:

    • 您的解决方案有效!非常感谢。如果您能解释一下它是如何工作的,那就太好了
    • 我添加了解释。
    猜你喜欢
    • 2021-07-25
    • 2021-08-01
    • 2021-08-02
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2020-11-22
    相关资源
    最近更新 更多