【问题标题】:discord.py terminal command prompt `input()` function blockingdiscord.py 终端命令提示符`input()` 功能阻塞
【发布时间】:2020-06-05 22:15:03
【问题描述】:

我正在尝试在我的机器人的终端上创建一个命令行,其中包含一些基本命令,例如 send <channel ID> <text>exit。这是我当前的代码:

async def start_bot():
    await client.start('token')

@tasks.loop(count=1)
async def cli():
    '''Implement the bot command line interface.'''
    try:
        while True:
            command = input(f'{c.bdarkblue}>>>{c.end} ') # my formatting
            command = command.split()
            command, subcommand = command[0], command[1:]
            if command == 'exit':
                os.kill(os.getpid(), 15) # there is sigterm catching in other parts of my code that save everything
            if command == 'send':
                client.get_channel(int(subcommand[0])).send(' '.join(subcommand[1:]))
            if command == 'send_all_guilds':
                for guild in client.guilds:
                    try:
                        guild.system_channel.send(' '.join(subcommand))
                    except discord.errors.Forbidden:
                        print(f'{c.darkwhite}Failed to send to guild ID: {guild.id} Name: {guild.name}{c.end}')
    except Exception as e:
        print(e)

cli.start()
asyncio.get_event_loop().run_until_complete(start_bot())

问题是在input() 发生时没有任何代码执行,并且在输入函数前加上await 会得到object str can't be used in 'await' expression。仅当我对引发异常的命令执行某些操作时(例如在客户端尚未启动时尝试发送消息),机器人才会启动。 input() 有其他异步替代方案吗?

(每当我说“命令”时,我指的是终端命令,而不是不和谐的机器人命令,like this

【问题讨论】:

    标签: python python-3.x discord.py coroutine


    【解决方案1】:

    Python 的输入函数是阻塞的。没有简单的方法可以解决这个问题。我建议你看看this 的帖子。但是,请注意,它仅适用于 Windows。

    如果您想自己对此进行更多研究,请查看线程。

    【讨论】:

      【解决方案2】:

      Python 的输入功能会停止所有代码,直到有人输入,这意味着无法绕过它,除非您创建自己的输入系统(不推荐)

      如果您确实需要输入,请查看线程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-16
        • 2019-05-01
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 2013-12-16
        • 2020-11-22
        • 2020-03-19
        相关资源
        最近更新 更多