I’m working on a Discord bot in Python and running into an asyncio issue. I have a command that calls a function named get_user_stats() which fetches data from an API using urllib and saves it to a file. The function works fine when tested separately, but when triggered through the bot, I get this error message:
Task was destroyed but it is pending! task: Task pending coro=<_run_event() running at /usr/local/lib/python3.5/site-packages/discord/client.py:307> wait_for=Future pending cb=[Task._wakeup(), BaseSelectorEventLoop._sock_connect_done(964)()]>
The weird part is it only fails about 75% of the time. Sometimes it runs perfectly fine. Here’s my message handler:
async def on_message(message):
if message.content.startswith('!stats'):
await client.send_message(message.channel, "Processing request...")
get_user_stats()
await client.send_message(message.channel, "Done")
I’m still learning asyncio so I might be missing something obvious here. Any help would be great!
yeah ive had the same issue. mixing sync and async can mess up the event loop. try using asyncio.create_task() or make sure to await the function correctly. those random failures come from urllib blocking your code; aiohttp would be a better choice.
This happened to me all the time when I built my first bot. Your get_user_stats() function is blocking the event loop because it’s synchronous. This makes discord.py’s internal tasks get stuck waiting, and when asyncio shuts down, it finds these unfinished tasks and throws that error. It’s intermittent because network latency varies - short API calls finish before causing problems, but longer ones trigger the timeout. Quick fix: add await asyncio.sleep(0.01) after your sync call to give the event loop a break. But you really should convert to async with aiohttp or use loop.run_in_executor(). Trust me, I spent days debugging the same random failures before figuring this out.
Had this exact problem when I started making Discord bots. You’re calling get_user_stats() as a sync function inside async code, which blocks the event loop. urllib freezes everything during network requests, so asyncio kills your pending tasks. Fix it by either making get_user_stats() async with aiohttp, or wrap the sync call: await asyncio.get_event_loop().run_in_executor(None, get_user_stats) to run it in a separate thread. The 75% failure rate happens because it depends on API response time - quick responses finish before timeout, slow ones get killed. I’d go with aiohttp since it’s built for async and way more reliable.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.