I’m working on a Discord bot that posts location coordinates to a text channel. The bot runs fine for about 2 minutes then crashes with a “task was destroyed” error message. I’m still learning Python so any explanations would be really helpful.
Someone mentioned the issue might be with the external library using the requests module instead of async requests. Could you help me convert this code to use aiohttp instead of the requests library for async compatibility? I need the find_locations function to work with async but I’m not sure how to implement that properly.
This error happens when blocking operations mess with async code. Your LocationAPI is probably making synchronous requests that block the event loop, causing Discord.py to timeout and kill tasks. Don’t just switch to aiohttp yet - wrap your blocking API calls in a thread executor first. Use asyncio.get_event_loop().run_in_executor(None, api_handler.scan_locations, search_area) to run blocking operations in a separate thread without freezing the main loop. Also, you’re using deprecated Discord.py methods like send_message and is_logged_in - these don’t exist in newer versions. Switch to channel.send() and handle connections through bot.run() instead of manual login/logout. That manual connection handling in your main_loop is making things unstable too.
Yeah, I’ve run into this before. You’re mixing sync and async operations wrong. bot_client.login() doesn’t exist in newer discord.py versions - just use bot.run(token) instead. That while loop is also breaking things because Discord expects proper event handling, not manual loops.
The task destruction error occurs when blocking synchronous calls interfere with the timing of the async event loop. Your LocationAPI likely uses requests, which can completely block the execution. While switching to aiohttp would indeed require a comprehensive rewrite of your API class to replace all requests.get() calls with aiohttp.ClientSession().get() and convert methods to async, I recommend starting with adjustments to your existing structure. The core issue lies in your while loop and manual connection handling. Discord.py is designed to utilize bot.run(), which automatically manages connections, so I suggest removing your connect_bot() and main_loop() functions. Instead, employ event handlers through @bot_client.event decorators alongside bot_client.run(). Be wary of the continual sleep calls, as they can cause conflicts with Discord’s heartbeat. If blocking persists after changing the connection logic, consider using asyncio.to_thread() for API calls; this approach is simpler than a full rewrite of LocationAPI.