async def create_db_pool():
database_url = ''
client.pg_con = await asyncpg.create_pool(database_url, ssl="require")
所以我在我的不和諧機器人代碼中有這個功能但是當我嘗試使用運行這個代碼時
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
uj5u.com熱心網友回復:
您必須使用它的master版本,discord.py
它最近引入了帶有 的重大更改asyncio,其中之一就是這個。
在背景關系client.loop中不再可訪問。這個要點解釋了變化是什么以及如何解決。sync
第一種方法是在子類中引入一個setup_hook()函式commands.Bot并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())
uj5u.com熱心網友回復:
您是否在同步背景關系中運行您的機器人?代碼應類似于:
async def on_message(ctx): ...
還請顯示一些代碼。但我認為學習 asyncio 模塊會有所幫助。無論如何,試試這個:
import asyncio
async def create_db_pool() -> None: ... # Your code
loop = asyncio.get_event_loop()
loop.run_until_complete(function_async())
loop.close()
這不會異步運行您的函式,但您似乎不希望這樣做。但它實際上應該成功運行該功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450403.html
上一篇:日期復制停止回圈陳述句按預期運行
