python - 如何每分钟使用 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'
我能做些什么来解决这个问题?
解决方案
你得到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)
参考:
推荐阅读
- mysql - 索引一个mysql表(网格搜索)
- excel - 使用文件路径中的单元格值循环遍历单元格并导入 CSV 文件
- git - 具有功能分支的正确 git 工作流程
- docker - Docker - “命令 '/bin/sh -c apt-get install nodejs' 返回一个非零代码:100”
- c# - Tryparse 不适合我并且 ParseExact 可以工作,但是当包含额外空间时它会失败
- c# - 具有可变模型类型的局部视图
- mysql - 在包含三列的表中搜索,其中搜索条件可能只有一列、两列或三列?
- python-2.7 - matplotlib fill_between y1 和 y2 参数的问题?
- javascript - 使用 Javascript 变量放置 Google 地图标记位置
- java - Android ART Crash 试图抛出 ArrayOutOfBoundsException