让 Discord Bot 定期发送消息

时间:2021-07-07 04:36:47

标签: python discord discord.py bots

我正在尝试制作一个每 4 小时自动发送一次消息的机器人,但由于某种原因它不起作用。我查看了谷歌和堆栈溢出,但没有一个答案可以帮助我。 Discord 是否改变了机器人发送消息的方式?

@tasks.loop(seconds=20)
async def messages():
  channel = bot.get_channel(channel_id)
  response = "test"
  await channel.send(response)

messages.start()

如果我尝试运行此代码,则会出现此错误

AttributeError: 'NoneType' object has no attribute 'send'

任何帮助将不胜感激,感谢您的时间

2 个答案:

答案 0 :(得分:1)

使用 Client.loop.create_task(),您可以创建重复任务并 我添加了 client.wait_until_ready() 以等待机器人启动,asyncio.sleep(seconds)机器人将等待 4 小时。

async def message_loop():
await client.wait_until_ready()

while not client.is_closed():
    #your code here
    channel = bot.get_channel(channel_id)
    response = "test"
    await channel.send(response)

    await asyncio.sleep(60*60*4)#seconds*minute*hour
client.loop.create_task(message_loop())

答案 1 :(得分:1)

我自己设法修复了它。而不是 channel = bot.get_channel(channel_id) 使用 channel = client.get_channel(id=channel_id) 从客户端获取 id

async def messages():
  await client.wait_until_ready()
  while not client.is_closed():
    channel = client.get_channel(id=channel_id)
    response = "test"
    await channel.send(response)

    await asyncio.sleep(60*60*4)
client.loop.create_task(messages())