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

后端 未结 2 924
自闭症患者
自闭症患者 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:38

    Using wait_for

    async def botcalc(self, ctx):
            author = ctx.author
            numbers = []
    
            def check(m):
                return m.author ==  author
    
            for _ in ('first', 'second'):
                await ctx.send(f"enter {_} number")
                num = ""
                while not num.isdigit():
                    num = await client.wait_for('message', check=check)
                numbers.append[int(num)]
    
            await channel.send(f'{numbers[0]}+{numbers[1]}={sum{numbers)}')
    

    edit

    Added a check

    0 讨论(0)
  • 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}")
    
    0 讨论(0)
提交回复
热议问题