Py学习  »  Python

如何转换需要用户输入才能在不协调bot中工作的python代码?

Charlie Watson • 5 年前 • 1750 次点击  

所以我有一段代码,它需要用户多次输入(输入的内容并不总是一样的)。我不想把代码传给我不和谐的人,我想把它直接变成一个不和谐的机器人,这样每个人都可以使用它。在给定代码后,如何让所有机器人接收用户消息

这里有一个我想要的例子:

-.botcalc公司
--这是discord机器人,请输入第一个号码:
-1个
--输入第二个号码:
-2个
--1+2=3

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51107
 
1750 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Patrick Haugh
Reply   •   1 楼
Patrick Haugh    6 年前

有两种方法可以编写此命令:一种是在问题中使用“对话”样式

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

二是使用 converters 接受参数作为命令调用的一部分

@bot.command()
async def calc(ctx, firstnum: int, secondnum: int):
    await ctx.send(f"{firstnum} + {secondnum} = {firstnum+secondnum}")
Jab
Reply   •   2 楼
Jab    6 年前

使用 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)}')

编辑

添加支票