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.