如何每分钟使用 discord.py 以不和谐的方式发送消息

时间:2021-01-02 15:34:25

标签: python discord discord.py discord.py-rewrite python-3.9

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)

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

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'

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

您收到 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)

enter image description here


参考: