首页 > 解决方案 > 如何每分钟使用 discord.py 发送一条不和谐的消息

问题描述

import discord
from discord.ext import tasks

client = discord.Client()
channel = client.get_channel(CHANNEL-ID)

@tasks.loop(minutes=1)
async def test():
    await channel.send("test")

@client.event
async def on_ready():
    test.start()


TOKEN = "MYTOKEN"


client.run(TOKEN)

我从discord.py 中的 Sending message every minute 中得到了这个代码,它说它应该可以工作,但我不断收到以下错误:

Unhandled exception in internal background task 'test'.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/tasks/__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "/Users/me/Coding/Py/Gmail/bot.py", line 9, in test
    await channel.send("test")
AttributeError: 'NoneType' object has no attribute 'send'

我能做些什么来解决这个问题?

标签: pythondiscorddiscord.pydiscord.py-rewritepython-3.9

解决方案


你得到None是因为客户端的缓存还没有加载。

如果您打算稍后添加命令,commands.Bot(...)我还建议您使用。继承,所以你现在可以做的任何事情,你也可以用.discord.Client()commands.Bot()Client()Bot()

要解决此问题,您可以在on_ready事件中获取用户:

@tasks.loop(minutes=1)
async def test(channel):
    await channel.send("test")

@bot.event
async def on_ready()
    channel = bot.get_channel(ID_HERE)
    test.start(channel=channel)

如果您仍然获得None,则需要启用特权意图。这可以通过以下代码完成,并在您的应用程序页面中启用以下按钮:

intents = discord.Intents().all()

bot = commands.Bot(command_prefix=..., intents=intents)

在此处输入图像描述


参考:


推荐阅读