首页 > 解决方案 > 从未等待协程“get_quote”

问题描述

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

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")

标签: pythondiscord.pybots

解决方案


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

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()


推荐阅读