【问题标题】:RuntimeWarning: coroutine 'script' was never awaited content = str(content) if content is not None else NoneRuntimeWarning: coroutine 'script' is never awaited content = str(content) if content is not None else None
【发布时间】:2020-12-01 01:43:45
【问题描述】:

我正在尝试在 python3.8 和 discord.py 中创建一个不和谐机器人,其目的是读取文本文件,然后将每个单词作为单独的消息输出到服务器中。 目前,这是我用来尝试将脚本输出为每条单独消息的函数:

async def script():
    with open("test.py", 'r') as f:
        for line in f:
            print('\n'.join(line.split()))

此函数随后应用于以下内容:

@client.event
async def on_message(message):
    if message.content.startswith('r!help'):
        channel = message.channel
        await channel.send('Help')
    elif message.content.startswith('r!start'):
        channel = message.channel
        await script()
        await channel.send(script())

但是,我最终得到一个错误说明

RuntimeWarning: coroutine 'script' was never awaited
  content = str(content) if content is not None else None
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

我认为这是因为我的协程脚本没有被等待,但我正在等待它为 await script() 但当然,这似乎不起作用。相反,脚本正在pycharm IDE中打印到我的终端上,因此不仅没有等待协程,而且没有将其发送到服务器中的适当通道(这可能是因为它没有等待)。如果有人能向我解释为什么没有等待协程并指出如何解决这个问题的正确方向,我将不胜感激。

【问题讨论】:

    标签: python async-await discord discord.py discord.py-rewrite


    【解决方案1】:

    您之前在等待 script,但在 await channel.send(script()) 中您并没有在等待,但是这会导致错误为 script返回无

    这是修改后的代码

    script函数

    async def script(channel):
        with open("test.py", 'r') as f:
            for line in f:
                await channel.send('\n'.join(line.split()))
    

    on_message事件

    @client.event
    async def on_message(message):
        if message.content.startswith('r!help'):
            channel = message.channel
            await channel.send('Help')
        elif message.content.startswith('r!start'):
            channel = message.channel
            await script(channel)
    

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      相关资源
      最近更新 更多