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

折月煮酒 提交于 2020-01-11 07:47:08

问题


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


来源:https://stackoverflow.com/questions/54798621/how-do-you-convert-a-python-code-that-requires-user-input-to-work-in-a-discord-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!