【问题标题】:How can I run a command from another command?如何从另一个命令运行命令?
【发布时间】:2022-01-24 14:46:52
【问题描述】:

我正在尝试编写一个 Discord 机器人,如果我运行某个命令,程序的一部分会运行,但另一部分不会。

例如:在我的例子中,当他们输入"?m" 时,他们会收到一条消息说"xy",但是在接下来的 90 秒内,他们将无法再次调用该命令。如果他们在这 90 秒内调用它,另一个名为 "?x" 的命令将运行。

有人可以帮帮我吗?

【问题讨论】:

  • 尝试调用?x 命令的函数(使用await),传递相同的Context

标签: python discord discord.py


【解决方案1】:

您可以使用bot.invoke() 方法:

@bot.command()
async def x(ctx):
    pass  # whatever here


@bot.command()
async def m(ctx):
    if something:
        ctx.command = bot.get_command("x")
        await bot.invoke(ctx)  # invoke a command called x

【讨论】:

    【解决方案2】:

    使用 Python 的 time 模块,您可以检查自上次成功调用命令以来的时间。 time.time() 返回当前时间(表示为自 1970 年 1 月 1 日以来的秒数)。

    从另一个命令中调用一个命令可以像使用任何其他协程一样简单地使用await 调用它,并将相同的上下文传递给它。

    import time
    from discord.ext.commands import Bot
    from tokens import TOKEN
    
    bot = Bot(command_prefix='?')
    # Set the initial time as 0 (effectly 1970) so it was definitely long
    # ago for the command to now be called.
    last_called = 0
    
    @bot.command()
    async def hi(ctx):
        # Compare the current time to when the command was last successfully
        # called.
        global last_called
        now = time.time()
        if now - last_called <= 90:
            await not_now(ctx)
        else:
            last_called = now
            await ctx.send('Hello')
    
    @bot.command()
    async def not_now(ctx):
        await ctx.send('Please wait a minute.')
    
    bot.run(TOKEN)
    

    使用全局变量通常不是最好的主意,但不幸的是,将Bot 子类化以将数据更整齐地封装到单个对象中是quite clunky

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多