how do you convert a python code that requires use

2020-04-01 03:48发布

问题:

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 would like to make it directly into a discord bot so everyone can use it. How do I all the bot to take in a user msg after a code is given

here is an example of kinda what I want:

-.botcalc
--this is discord bot, enter first number:
-1
--enter second number:
-2
--1+2 = 3

回答1:

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



回答2:

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}")