繁体   English   中英

如何在命令后在 discord.py 中获取用户输入

[英]How to get user input in discord.py after command

我想知道如何在命令字符串之后获取用户输入。 我有一个名为p!spam的命令,我希望它执行p!spam (message) (amount of times) ,但我不知道如何执行此操作。 有人能帮我吗?

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('p!spam'):

为简单起见,我建议将消息应该发送的次数放在消息之前。
以下代码的命令语法为:

p!spam [# of times to repeat] [message]
@client.event
async def on_message(message):
    if message.author.id == client.user.id:
        return

    if message.content.startswith('p!spam'):
        parts = message.content.split(' ')
        del parts[0]
        number = int(parts.pop(0))
        msg = ' '.join(parts)
        for k in range(number):
            await message.channel.send(msg)

on_message方法不是命令,而是事件。

使用on_message()事件,

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('p!spam'):
        try:
            spam = split(' ')
            length = len(spam)
            amount = int(spam[length - 1])
            del spam[0]
            del spam[length - 1]
            for i in range (amount):
                await message.channel.send(' '.join(spam))
        except:
            await message.channel.send('Sorry, something went wrong.')

    await client.process_commands(ctx)     # Important for commands to work

调用此命令的消息如下所示(我相信这就是您要查找的内容):

p.spam 这是我的垃圾邮件。 10

另一种方法,金额在开头:

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('p!spam'):
        try:
            spam = split(' ')
            amount = int(spam[1])
            del spam[0]
            del spam[1]
            for i in range (amount):
                await message.channel.send(' '.join(spam))
        except:
            await message.channel.send('Sorry, something went wrong.')

    await client.process_commands(ctx)     # Important for commands to work

调用此命令的消息如下所示:

p.spam 10 这是我的垃圾邮件。


使用命令执行此操作会容易得多,您只需执行以下操作:

@client.command
async def spam(ctx, amount, *, spam):
    for i in range(int(amount)):
        await ctx.send(spam)

调用此命令的消息如下所示:

p.spam 10 这是我的垃圾邮件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM