Bot crashes with task destruction error

My Discord bot keeps failing after running for a few minutes

I created a Discord bot that posts location data to a chat room. The bot works fine at first but crashes after about 2 minutes with a “task was destroyed” message. I’m still learning Python so any explanation would be helpful.

import discord
import asyncio
import time
import datetime

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

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

async def location_scanner():
    target_channel = discord.Object(id='my_channel_id')
    search_area = (
              (40.12345, -74.56789), # Southwest corner
              (40.98765, -74.12345) # Northeast corner
              ) # Manhattan area
    try:
        print(api_client.authenticate('my_username', 'my_password'))
        print(api_client.get_api_url())
        print(api_client.get_user_data())
        
        for location in api_client.scan_locations(search_area):
            current_time = time.time()
            time_str = datetime.datetime.fromtimestamp(current_time).strftime('%H:%M:%S')
            message = "[" + time_str + "]" + str(location)
            await client.send_message(target_channel, message)
            print(message)
    except Exception as error:
        print(str(error))
        client.logout()
    asyncio.sleep(1)

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

Someone mentioned the issue might be with the location API library using synchronous requests. Could you help me convert it to use aiohttp instead of the requests library? I need to make the scan_locations function async but I’m not sure how to do that properly.

The main problem here is that you’re calling asyncio.sleep(1) at the end of location_scanner() without awaiting it. This creates a coroutine object that gets garbage collected immediately, causing the “task was destroyed” error. Change that line to await asyncio.sleep(1). Also, your connect_to_server() function is calling the old synchronous client.login() method which doesn’t work properly in an async context. You should be using await client.start('my-bot-token') instead of the login/logout pattern. The blocking API calls are definitely an issue too, but fixing these async/await problems should stop the immediate crashes you’re experiencing.

looks like ur mixing blocking and async code which is causing the task destruction. the location_api calls are probly blocking the event loop. try wrapping those sync calls in await asyncio.get_event_loop().run_in_executor(None, api_client.scan_locations, search_area) instead of converting everything to aiohttp right away

I had similar issues when I started working with discord.py. The core problem is that you’re treating the Discord client incorrectly - you shouldn’t be manually calling login/logout in a loop like that. Instead, restructure your code to use the proper event-driven approach. Create an on_ready event handler and start your background task there using client.loop.create_task(). Also, that while not client.is_closed loop in background_worker() is going to cause problems because you’re essentially running an infinite loop that competes with Discord’s own event loop. Replace the whole background_worker approach with a proper task that gets started once when the bot connects. The blocking API calls others mentioned are definitely part of the issue, but your bot architecture needs fixing first before tackling the aiohttp conversion.