【问题标题】:Discord.py commands wont work after calling the main function调用 main 函数后,Discord.py 命令将不起作用
【发布时间】:2021-08-11 01:04:26
【问题描述】:

我想将 Discord 机器人与命令行应用程序结合起来。但是,在启动时调用函数 fruit() 后,我的 discord bot 命令将不起作用(没有错误)。机器人运行后,fruit() 函数将无限运行。 client.run 之后的任何代码都将不起作用。有什么解决方案可以修复我的代码,以便在运行脚本时激活命令并运行机器人,然后永远运行 main 函数?

from discord.ext import commands
token = "my token"
client = commands.Bot(command_prefix=">")

def fruit():
    option = input("Choose a fruit, 1 for banana, 2 for lime")
    if option == 1:
        print("Bananas are sweet")
        fruit()
    elif option == 2:
        print("Limes are sour")
        fruit()
    else:
        print("Invalid option")
        fruit()

@client.command()
async def sayhi(ctx):
    await ctx.send("Hi")

@client.event
async def on_ready():
    fruit()

client.run(token)```

【问题讨论】:

  • 尝试输入here的一些解决方案。此外,您可能希望更改代码,以免最终达到递归限制。

标签: python discord discord.py


【解决方案1】:

input 是一个阻塞函数 (what does "blocking" mean),它会阻塞你的整个线程,直到它完成,你可以使用类似 aioconsole.ainput 的东西或制作你自己的非阻塞输入函数:

async def ainput(text):
    return await client.loop.run_in_executor(None, input, text)
    
async def fruit():
    option = await ainput("Choose a fruit, 1 for banana, 2 for lime")
    if option == '1': # `input` by default returns a string, so comparing to an integer will not work
        print("Bananas are sweet")
        await fruit()
    elif option == '2':
        print("Limes are sour")
        await fruit()
    else:
        print("Invalid option")
        await fruit()

@client.event
async def on_ready():
    await fruit()

需要注意的一点是,fruit 现在是一个协程,应该等待它。

正如 duckboycool 所说,您可能想稍微更改一下代码,以免达到递归限制(while 循环可以解决问题)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2019-07-23
    • 1970-01-01
    • 2021-07-27
    • 2022-01-24
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多