向频道 discord.py 发送消息

时间:2021-05-15 20:41:23

标签: python discord.py

我在向特定频道发送消息时遇到问题,代码如下:

client = discord.Client()

@tasks.loop(seconds=10)
async def test2():
  channel = client.get_channel(836633672240332820)
  await channel.send('test')
  print('test')

test2.start()

我收到以下错误:

Unhandled exception in internal background task 'test2'.
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "main.py", line 297, in test2
    await channel.send('test')
AttributeError: 'NoneType' object has no attribute 'send'

有人能帮忙吗?

2 个答案:

答案 0 :(得分:1)

您收到该错误是因为 Dissertation diss = new Dissertation(50); IFlippable fdiss = new IFlippable(); //or Book bk = new Book(); Book bdiss = new Book(); //or IFlippable f1 = new IFlippable (1); 从缓存中获取通道对象,在循环的第一次迭代中,缓存根本没有完成加载,您可以在 get_channel 中使用 Client.wait_until_ready {1}} 函数:

before_loop

如果错误仍然存​​在,请确保您复制了正确的频道 ID。

参考:

答案 1 :(得分:1)

您可以只创建一个 on_ready def 并放置 test2.start() 但如果您想发送一次,那么它只会循环将您的代码放入 on_ready

@client.event
async def on_ready():
   test2.start()
@client.event
async def on_ready():
  channel = client.get_channel(836633672240332820)
  await channel.send("test")