mime
mime

Reputation: 312

while True loop in async stops other parts of code from working Discord.py

I'm making a discord bot.

What my discord bot does listens to messages throughout the server and prints it real-time.

However, I also want the code to constantly recieve input from me from the console and print it out in a particular server ID. The following is my code:

@bot.event
async def on_message(message):
    # Prints message


@bot.event
async def on_ready():
    # Execute on-ready stuff
    while True:
        kb = input(">>>")

        #Delivers the message into a certain channel

The problem is after the while True loop is executed, the other on_message functions stop working. I have seen other similar questions but I don't understand the async functions.

Could someone tell me how to both receive input continuously and print out incoming messages real-time?

Upvotes: 2

Views: 1739

Answers (1)

user4815162342
user4815162342

Reputation: 154846

The problem is not in while True, the problem is in the built-in input function, which is blocking and not async. Asyncio is based on cooperative multi-tasking, which means that your coroutine must choose to allow other code to run by awaiting something. Since your while loop doesn't await anything, it blocks everything else.

Look into the aioconsole package which provides an async version of input.

Upvotes: 2

Related Questions