Discord bot keeps crashing with task destruction error

I’m working on a Discord bot that’s supposed to send location data to a chat channel. Everything seems to work fine at first, but after running for about 2 minutes, it crashes with an error saying the task was destroyed.

I’m pretty new to Python and async programming, so I’m not sure what’s causing this issue. Someone mentioned that the problem might be related to the skiplagged library using the requests module instead of aiohttp for async operations.

Here’s my current code:

import discord
import asyncio
import time
import datetime

from location_api import LocationAPI
bot = discord.Client()
api_client = LocationAPI()

def connect_to_server():
    bot.login('bot-token')

async def search_locations():
    target_channel = discord.Object(id='channel_id')
    search_area = (
        (40.76356269219236, -73.98657795715332),
        (40.7854671345488, -73.95812508392333)
    )
    
    try:
        print(api_client.login_with_credentials('user_id', 'user_password'))
        print(api_client.get_api_endpoint())
        print(api_client.get_user_profile())
        
        for location in api_client.search_locations(search_area):
            timestamp = time.time()
            time_str = datetime.datetime.fromtimestamp(timestamp).strftime('%H:%M:%S')
            message = "[" + time_str + "]" + str(location)
            await bot.send_message(target_channel, message)
            print(message)
    except Exception as error:
        print(str(error))
        bot.logout()
    asyncio.sleep(1)

async def background_worker():
    target_channel = discord.Object(id='channel_id')
    while not bot.is_closed:
        if not bot.is_logged_in:
            connect_to_server()
        else:
            await search_locations()
        await asyncio.sleep(5)

Could someone help me understand why the task keeps getting destroyed? Also, if the issue is really with the requests library, how can I convert it to use aiohttp instead?

You’re getting that task destruction error because your bot is doing blocking operations inside async functions. I’ve hit this exact same issue when mixing sync and async code wrong.

The main problem is calling bot.login() inside connect_to_server() - that’s a sync function being called from async context, which messes up the event loop. Your api_client.login_with_credentials() and other API calls are probably blocking operations too, and they shouldn’t run in the main async loop.

Here’s what fixed it for me: wrap all the blocking API calls in asyncio.create_task() or use loop.run_in_executor() to run them in a separate thread. Also, handle bot login differently - move it outside your background worker loop and use proper async bot initialization.

One more thing - you’re missing await before asyncio.sleep(1) in your search_locations function. That’ll also cause task destruction problems since the coroutine isn’t being awaited properly.

Task destruction happens because you’re mixing sync and async operations wrong. Your api_client methods are blocking the event loop, so Discord’s internal tasks timeout and get destroyed. I hit this exact issue when scraping data for my bot. LocationAPI probably uses requests under the hood, which blocks the entire event loop. Discord.py needs non-blocking operations - when your API calls take too long, it kills the tasks. You need an async version of your location API or wrap those calls in asyncio.to_thread() (Python 3.9+) or loop.run_in_executor() (older versions). Also, your bot architecture is broken - don’t call bot.login() inside your background worker. Initialize the bot at startup, then just handle location searching in your background task. Another red flag: bot.send_message() is deprecated. Switch to channel.send() with proper channel objects. The combo of blocking calls and deprecated methods is what’s causing the instability.

your event loop’s getting blocked by sync operations. when you call those api methods without making them async, discord.py can’t send heartbeats properly and drops the connection. wrap your location api calls in asyncio.get_event_loop().run_in_executor(None, your_function) to run them in a thread pool instead of blocking the main loop.