【问题标题】:Coroutine 'get_quote' was never awaited从未等待协程'get_quote'
【发布时间】:2021-06-01 22:58:32
【问题描述】:

因此,我无法运行此代码来为我正在创建的不和谐机器人打印随机报价, 我不断收到此错误,而不是随机引用:

Warning (from warnings module):
  File "C:\Users\amber\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343
    await coro(*args, **kwargs)
RuntimeWarning: coroutine 'get_quote' was never awaited

这是我正在使用的代码:

# bot.py
import discord
import os
import requests
import json

client = discord.Client()

async def get_quote():
  response = requests.get("https://zenquotes.io/api/random")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)


@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    if message.content.startswith('-m inspire'):
        quote = get_quote()
        await message.channel.send(quote)

client.run("token here")

【问题讨论】:

    标签: python discord.py bots


    【解决方案1】:

    当我们定义一个同步函数时

    def somefunction(arg, arg2):
        # do something
    

    我们可以简单地用somefunction(input, input2)调用它

    当我们这样定义时,

    async def somefunction(#some expected input):
         # do something
    

    它是一个异步函数,它是一个需要等待的协程

    所以我们用await somfunction(#some input)来称呼它

    正如你的错误所说,你的 "coroutine" get_quote 函数从未被等待

    要调用它,请使用await get_quote() 而不仅仅是get_quote()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2021-10-22
      • 2019-12-15
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多