为什么我的discord机器人不发送每日消息

2024-10-02 16:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

显然有些代码丢失了,但这里是所有需要帮助的代码

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点”部分,因为它在测试中不是必需的。如果我移动channel = client.get_channel(channel_id)await channel.send(get_quote())in 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

Tags: inimportclientsendidjsontaskget
1条回答
网友
1楼 · 发布于 2024-10-02 16:28:39

我执行了您的代码,唯一的问题不是等待我在comment above中提到的client.wait_until_ready()。在on_ready()作为客户端/bot仍在安装之前,channel = client.get_channel(channel_id)返回None,这将导致下面的Attribute Error

AttributeError: 'NoneType' object has no attribute 'send'

请在discordpy official documentation中查找有关wait_until_readyon_readyAPI调用的完整信息

下面是我的完整代码,稍作修改

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)

相关问题 更多 >