显然缺少一些代码,但这里是所有应该需要帮助的。
import os
import discord
import requests
import json
import asyncio
channel_id = 791884298810163200
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
async def sendQuote():
channel = client.get_channel(channel_id)
await channel.send(get_quote())
async def background_task():
#if not 8am, wait until 8am (ignoring the seconds place, doesn't have to be exactly 8am)
await sendQuote() #fix this
await asyncio.sleep(5) #change this to the number of seconds in a twenty four hour period when done testing
await background_task()
if __name__ == "__main__":
client.loop.create_task(background_task())
keep_alive()
client.run(my_secret)
我还没有添加等待直到8 am部分,因为它在测试中不需要。如果我移动channel = client.get_channel(channel_id)
await channel.send(get_quote())
进入on_ready()它打印引号所以我真的不确定sendQuote()
Task exception was never retrieved future: <Task finished name='Task-1' coro=<background_task() done, defined at main.py:31> exception=AttributeError("'NoneType' object has no attribute 'send'")> Traceback (most recent call last): File "main.py", line 33, in background_task await sendQuote()
#fix this File "main.py", line 28, in sendQuote await channel.send(get_quote()) AttributeError: 'NoneType' object has no attribute 'send
我执行了你的代码,唯一的问题不是等待我在上面的评论中提到的client.wait_until_ready()
。在on_ready()
作为客户端/bot仍然被设置之前,channel = client.get_channel(channel_id)
返回None
,这导致下面的Attribute Error
。
AttributeError: 'NoneType' object has no attribute 'send'
请在官方文档中找到wait_until_ready
或on_ready
API调用的完整信息。
下面是完整的代码,稍微修改了一下,
import os
import discord
import requests
import json
import asyncio
channel_id = 000000000000000000
client = discord.Client()
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
async def sendQuote():
# wait till the client has executed on_ready().
await client.wait_until_ready()
channel = client.get_channel(channel_id)
await channel.send(get_quote())
async def background_task():
#if not 8am, wait until 8am (ignoring the seconds place, doesn't have to be exactly 8am)
await sendQuote() #fix this
await asyncio.sleep(5) #change this to the number of seconds in a twenty four hour period when done testing
await background_task()
if __name__ == "__main__":
client.loop.create_task(background_task())
#keep_alive() - unknown function code, so commented it in here.
client.run(my_secret)
你这样做不是个好主意。
你正在做background_task()
的递归调用,这将工作一段时间,但你会遇到递归错误或早或晚,你的代码将失败。
查看来自discord.py的Tasks
扩展,它为重复出现的任务提供了函数,正是您想要的:)
https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html