RuntimeError: no active event loop in Discord bot using Asyncio

I’m working on a Python script for a Discord bot that retrieves stock data. My libraries are updated, but I’m encountering an issue within the function scheduled_task. Below is the relevant function code:

@tasks.loop(hours=24)
async def scheduled_task():
    url = 'https://finance.yahoo.com/quote/^QMI'
    response = requests.get(url)
    document = BeautifulSoup(response.text, 'html.parser')
    premarket_info = ''
    try:
        price_info = document.find_all('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find_all('span')
        premarket_info = 'NASDAQ 100 Pre Market\t' + price_info[0].text + '\t' + price_info[1].text
    except:
        premarket_info = 'No data available'

    for guild in bot.guilds:
        for channel in guild.channels:
            try:
                embed_message = fetch_news()
                await channel.send(embed=embed_message)
                await channel.send(premarket_info)
            except Exception:
                continue

The error message I receive is:

File "D:\Tradlytics\bot.py", line 173, in <module>
scheduled_task.start()
File "C:\path\to\discord\ext\tasks\__init__.py", line 398, in start
self._task = asyncio.create_task(self._loop(*args, **kwargs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Lib\asyncio\tasks.py", line 381, in create_task
loop = events.get_running_loop()
       ^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no active event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited

I can’t identify the source of this problem. Any ideas?

Based on my experience, this issue seems related to trying to start a task before an event loop is available. You should ensure your bot is running within an async context. If you have not already, try using asyncio.run() when you start your main function where the bot is initiated. This ensures an event loop is created before any tasks attempt to start. Additionally, check that your Discord bot’s on_ready event is fully awaited before invoking any scheduled tasks.