Discord.py 异步函数不提供任何输出,也不做任何事情

Discord.py async function does not give any output and does not do anything

代码如下:

print('hmm1') #testing, this one prints
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='&')
client.run('my token', bot=False)

async def testFunction():
    print('hmm') #<- this one does not print.
    channel = await client.get_channel(708848617301082164)
    message_id=715307791379595275
    msg = await client.get_message(channel, message_id)
    await msg.edit(content="L")
    await msg.edit(content="W")
    print('edited message!')
testFunction()
# none of the above works. I only get "hmm1" printed in console.

我不知道发生了什么,因为控制台中几乎没有错误或任何类型的输出。有人知道这个问题吗?

如果您不熟悉异步函数,则需要对它们进行 awaited。协程的例子可以在msg.edit(...中看到,因为edit()是一个协程,所以你需要await这样:await testFunction()

此外,client.get_channel()client.get_message() 不是协程,因此不需要等待它们。

正如 Eric 提到的,您还需要将 client.run('... 移到文件的最后一行,否则它将阻止脚本的其余部分。以下是代码的结构:

# imports

# commands, events, functions

# last line
client.run('...

看起来您也在使用一些旧文档,因为 d.py 已移至重写 (v1.x),看起来您使用的 client.get_message()实际上来自 v0.16.x.

我建议您阅读 these changes 以熟悉重写。尽量避免使用过时的教程。

作为一个小小的开端,您的 await client.get_message(channel, message_id) 应该变成 await channel.fetch_message(message_id)


参考文献: