【问题标题】:Make Discord Bot Send Regular Messages让 Discord Bot 发送常规消息
【发布时间】:2021-09-17 15:35:18
【问题描述】:

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

@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'

我们将不胜感激,感谢您的宝贵时间

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案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())
    

    【讨论】:

    • 它仍然给我同样的错误,AttributeError: 'NoneType' object has no attribute 'send'。由于某种原因,机器人无法正确获取频道,但我什至查看了 get_channel 函数的文档并将 id 作为整数传递,但它仍然给出相同的错误,我很困惑为什么
    • 我设法修复了它,而不是 bot.get_channel(channel_id),我使用了 client.get_channel(id=channel_id)。非常感谢您的帮助,我仍然使用您的代码使其重复出现
    【解决方案2】:

    设法自己修复它。而不是 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())
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2020-12-01
      • 2021-03-02
      • 2021-01-12
      • 2021-06-05
      • 2020-12-03
      • 2021-06-17
      • 2021-07-06
      • 1970-01-01
      相关资源
      最近更新 更多