1

I am in the middle of having two of my bots interfacing with each other via a ZMQ server, unfortunately that also requires a second loop for the receiver, so i started looking around the web for solutions and came up with this:

async def interfaceSocket():
    while True:
        message = socket.recv()
        time.sleep(1)
        socket.send(b"World")
    await asyncio.sleep(3)

@client.event
async def on_ready():
    print('logged in as:')
    print(client.user.name)

client.loop.create_task(interfaceSocket())
client.run(TOKEN)

I basically added the interfaceSocket function to the event loop as a task as another while loop so i can constantly check the socket receiver while also checking the on_message listener from the discord bot itself but for some reason, the loop still interrupts the main event loop. Why is this?

1 Answer 1

2

Although interfaceSocket is technically a task, it doesn't await anything in its while loop and uses blocking calls such as socket.recv() and time.sleep(). Because of that it blocks the whole event loop while it waits for something to happen.

If socket refers to a ZMQ socket, you should be using the ZMQ asyncio interface, i.e. use zmq.asyncio.Context to create a zmq.asyncio.Socket instead of. Then interfaceSocket can use await and become a well-behaved coroutine:

async def interfaceSocket():
    while True:
        message = await socket.recv()
        await asyncio.sleep(1)
        await socket.send(b"World")
Sign up to request clarification or add additional context in comments.

4 Comments

I see what you mean, while this does work I get a TypeError of 'object bytes cannot be used in await expression' not quite sure what that means though, it happens on the socket receive line
@Myronaz The prerequisite for the code to work is that socket be an instance of zmq.asyncio.Socket. If that is not the case, you cannot await it. How do you obtain the socket?
I obtain the socket through context = zmq.Context() and then socket = context.socket(zmq.REP)
@Myronaz You should be using zmq.asyncio.Context instead, which is the "context for creating asyncio-complatible Sockets". Please refer to the documentation also linked from the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.