問題描述
client.run(TOKEN) 命令阻止其他集團 (client.run(TOKEN) command blocks other blocs)
我寫了一個這樣的程序
client = commands.Bot(command_prefix='!')
@client.event
async def on_ready():
user = await client.fetch_user(ID)
await DMChannel.send(user, plus)
client.run(TOKEN)
print("Okay")
但是
print("Okay")
命令不起作用。你能幫幫我嗎?
參考解法
方法 1:
client.run(TOKEN)
stops the code at that point. Any code underneath it will run only after the bot has been shutdown. Put any code that you want to run immediately above client.run(TOKEN)
方法 2:
That is due to the mechanics of how does asyncio works. In the nutshell, asyncio creates a loop, which is a blocking code meaning that nothing outside of it won't run until loop finishes, and inside of that loop asyncio makes coroutines work asynchronous, that just how architecture works, nothing to do about it.
Client.run()
actually runs bot's asyncio loop and that's why nothing after that command works (at least until the point when you stop your bot).
To make your commands work you have to put them before calling Client.run()
or which is better in my view ‑ to add them into the loop by calling Client.loop.create_task(your async function)
. Take into account, that function you pass into the create_task
should be without brackets and that must be an async function.
And yes, you should call create_task
before running the loop, or from the loop itself.
(by Dombili81、Mathias、langley)