-3

I'm trying to make a command line on the terminal in my bot that has some basic commands like send <channel ID> <text> and exit. Here is my current code:

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())

The problem is that none of the code executes while the input() is happening, and prefixing the input function with await gives object str can't be used in 'await' expression. The bot starts only when I do something with the commands that raises an exception (like trying to send a message while the client hasn't started). Is there another asynchronous alternative to input()?

(Whenever I say "command", I refer to the terminal commands, and not the discord bot commands, like this

Eric Jin
  • 3,836
  • 4
  • 19
  • 45

2 Answers2

1

Python's input function is blocking. There is no easy way around this. I suggest you take a look at this post. However, be aware that it is windows only.

If you want to investigate this more yourself, take a look at threading.

0rdinal
  • 641
  • 4
  • 17
0

Python's input function stops all of the code until someone gives input, this means that there is no way to bypass it, unless you create your own input system (not recommended)

If you truly do need the input, take a look at threading.

Oblique
  • 560
  • 1
  • 4
  • 18