how do you convert a python code that requires user input to work in a discord bot?

后端 未结 2 907
自闭症患者
自闭症患者 2021-01-16 17:55

So I have a piece of code and it requires user input multiple times (and what is inputed is not alway the same). Instead of passing the code to everyone in my discord I woul

2条回答
  •  心在旅途
    2021-01-16 18:57

    There are two ways you could write this command: one is using the "conversation" style in your question

    from discord.ext.commands import Bot
    
    bot = Bot("!")
    
    def check(ctx):
        return lambda m: m.author == ctx.author and m.channel == ctx.channel
    
    async def get_input_of_type(func, ctx):
        while True:
            try:
                msg = await bot.wait_for('message', check=check(ctx))
                return func(msg.content)
            except ValueError:
                continue
    
    @bot.command()
    async def calc(ctx):
        await ctx.send("What is the first number?")
        firstnum = await get_input_of_type(int, ctx)
        await ctx.send("What is the second number?")
        secondnum = await get_input_of_type(int, ctx)
        await ctx.send(f"{firstnum} + {secondnum} = {firstnum+secondnum}")
    

    The second is to use converters to accept arguments as part of the command invocation

    @bot.command()
    async def calc(ctx, firstnum: int, secondnum: int):
        await ctx.send(f"{firstnum} + {secondnum} = {firstnum+secondnum}")
    

提交回复
热议问题