So when I try to run my discord bot I get this error message:
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
2022-04-30T22:38:44.714019 00:00 app[worker.1]: client.load_extension(f"cogs.{file[:-3]}")
Here is my code:
if __name__ == '__main__':
# When running this file, if it is the 'main' file
# I.E its not being imported from anther python file run this
for file in os.listdir("./cogs"):
if file.endswith(".py") and not file.startswith("_"):
client.load_extension(f"cogs.{file[:-3]}")
client.run("random token here")
I tried to read the other stackoverflow article on this but when I tried to do what it said it told me I cannot use await outside of function. But when I fix it using
async def main():
# do other async things
await my_async_function()
# start the client
async with client:
await client.start(TOKEN)
and do asycnio.run(main()) it does not work and tells me that
RuntimeError: asyncio.run() cannot be called from a running event loop
Is there a way to fix this? Thank you.
CodePudding user response:
As mentioned in the comments, in 2.0 loading extensions is async. You need to use client.start() with asyncio.
As the error says, you can't have an already running event loop. Discord has its own event loop to manage things, so you'll have to use get_event_loop to get it instead. Then, run_until_complete suffices here because nothing else needs to run.
import asyncio
async def main():
# if you need to, initialize other things, such as aiohttp
await client.load_extension('my_extension') # change to whatever you need
await client.start('token')
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
