async def create_db_pool():
database_url = ''
client.pg_con = await asyncpg.create_pool(database_url, ssl="require")
所以我在我的discord bot代码中有这个功能,但当我尝试使用运行这个代码时
client.loop.run_until_complete(create_db_pool())
我得到以下错误,目前我正在寻找一个解决方法或任何方法来解决它
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
您必须使用master
版本的discord.py
它最近引入了asyncio
的突破性变化,其中之一就是这样。CCD_ 4在CCD_。这个要点解释了什么是变化以及如何进行变通。
第一种方法是在commands.Bot
子类中引入setup_hook()
函数,并在中使用await create_db_pool()
class MyBot(commands.Bot):
def __init__(self, **kwargs):
super().__init__(**kwarg)
self.pg_conn: = None
async def create_db_pool(self): # making it a bound function in my example
database_url = ''
self.pg_con = await asyncpg.create_pool(database_url, ssl="require")
async def setup_hook(self):
await self.create_db_pool() # no need to use `loop.run_*` here, you are inside an async function
或者您也可以在main()
功能中执行此操作
async def main():
await create_db_pool() # again, no need to run with AbstractLoopEvent if you can await
await bot.start(TOKEN)
asyncio.run(main())
您是否在同步上下文中运行机器人程序?代码应该看起来像:
async def on_message(ctx): ...
还请出示一些代码。但我认为学习异步模块会有所帮助。无论如何,试试这个:
import asyncio
async def create_db_pool() -> None: ... # Your code
loop = asyncio.get_event_loop()
loop.run_until_complete(function_async())
loop.close()
这不会异步运行你的函数,但你似乎不想这样做。但它实际上应该成功地运行函数。