python - 从未等待协程“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")
解决方案
当我们定义一个同步函数时
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()
推荐阅读
- react-data-grid - 简单排序示例
- javascript - 我正在尝试将 db 值导出到全局范围,以便可以在其他模块中使用
- vba - 如何按主题和年龄过滤?
- gcc - 使用我自己的静态/动态库:如何编译和链接(正确做事的正确方法)
- javascript - 控制器中的 removeEventListener
- perl - 如何在 activeperl 中安装包模块(手动)
- ios - 是否可以通过在 iOS 上通过企业分发分发应用程序来测试应用内订阅真实?
- java - 如何使用 iText 将签名附加到 pdf?
- javascript - 订阅推送通知时总是抛出注册失败错误
- cassandra - cqlsh.py COPY FROM 无法解析时间戳