所以当我尝试运行我的discord bot时,我得到这个错误消息:
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]}")
下面是我的代码:
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")
我试图阅读其他stackoverflow文章,但当我试图做它说它告诉我,我不能在函数外使用await。但是当我使用
修复它时async def main():
# do other async things
await my_async_function()
# start the client
async with client:
await client.start(TOKEN)
并执行asynnio .run(main()),它不起作用,并告诉我
RuntimeError: asyncio.run() cannot be called from a running event loop
有办法解决这个问题吗?谢谢你。
正如在评论中提到的,在2.0中加载扩展是异步的。您需要使用client.start()
和asyncio
。
正如错误提示所说,您不能有一个已经在运行的事件循环。Discord有自己的事件循环来管理事物,所以你必须使用get_event_loop
来获得它。然后,run_until_complete
在这里就足够了,因为不需要运行其他任何东西。
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())