簡體   English   中英

發送消息到通道 discord.py

[英]Send message to channel 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'

Any1 能夠提供幫助嗎?

您收到該錯誤是因為get_channel從緩存中獲取通道 object,在循環的第一次迭代中,緩存根本沒有完成加載,您可以在before_loop function 中使用Client.wait_until_ready

client = discord.Client()

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

@test2.before_loop
async def before_test2():
    await client.wait_until_ready()

test2.start()

如果錯誤仍然存在,請確保您復制了正確的頻道 ID。

參考:

您可以只制作一個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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM