I’m developing a Python bot that communicates through websockets, and I’ve structured the logic in different files. However, I’m encountering persistent errors related to the asynchronous management when attempting to run the bot. Here are the errors:
RuntimeError: Cannot close a running event loop
sys:1: RuntimeWarning: coroutine 'Application.shutdown' was never awaited
sys:1: RuntimeWarning: coroutine 'Application.initialize' was never awaited
Here is a simplified version of my bot’s main asynchronous setup:
async def send_notification_to_chat(bot, message, chat_id):
try:
await bot.send_message(chat_id=chat_id, text=message)
print("Message sent successfully.")
except Exception as e:
print(f"Failed to send message: {str(e)}")
async def main():
bot = Bot(token="your-token-here")
application = Application.builder().bot(bot).build()
chat_id = "chat_number"
asyncio.create_task(logs_Tokens(lambda x, y, z: send_notification_to_chat(x, y, z), bot, chat_id))
try:
await application.initialize()
await application.run_polling()
finally:
await application.shutdown()
async def logs_Tokens(callback, bot, chat_id):
uri = "wss://your-websocket-uri"
while True:
async with websockets.connect(uri) as websocket:
# Websocket interaction omitted for brevity
while True:
message = await websocket.recv()
# Message processing omitted for brevity
await callback(bot, "Token activity detected!", chat_id)
I suspect the issue lies in how I manage the asynchronous tasks, especially with starting and shutting down the application. I’ve been trying different approaches to manage the event loop and coroutine handling, but none have resolved the issues.
Could anyone help me identify what might be wrong with my asynchronous setup and how to properly manage the event loop and coroutines in this context?
I expected the application to initialize without errors, handle real-time websocket messages, and shut down cleanly when done. The main aim was for the bot to continuously process incoming messages and respond accordingly without interruption or error messages.
Instead of a smooth operation, I encountered multiple errors. Upon running the bot, I received a RuntimeError indicating that the event loop could not be closed while running. Additionally, I saw warnings stating that the Application.shutdown and Application.initialize coroutines were never awaited. This resulted in the bot not functioning as intended, with improper handling of asynchronous tasks leading to unmanaged event loops and unawaited coroutines.