如何使用 discord.py 自动发送消息?

时间:2021-04-14 16:00:06

标签: python discord.py

import discord,random,asyncio
from discord.ext import commands
client = commands.Bot(command_prefix = '/')

async def auto_send():
    await send_msg('GOOD MORNING!')       
    await asyncio.sleep(28800)

async def send_msg(msg):
    channel = await client.fetch_channel('channel_id')
    await channel.send(msg)

client.loop.create_task(auto_send())
client.run(token)

错误:

Task exception was never retrieved
future: <Task finished name='Task-2' coro=<auto_send() done, defined at C:\Users\StudMuffin\Desktop\Things\Discord Bots\Youtube Channel YT\Youtube_get.py:31> exception=AttributeError("'NoneType' object has no attribute 'request'")>
Traceback (most recent call last):
  File "C:\Users\StudMuffin\Desktop\Things\Discord Bots\Youtube Channel YT\Youtube_get.py", line 41, in auto_send
    await send_msg('GOOD MORNING!')
  File "C:\Users\StudMuffin\Desktop\Things\Discord Bots\Youtube Channel YT\Youtube_get.py", line 50, in send_msg
    channel = await client.fetch_channel(channel_id)
  File "C:\Users\StudMuffin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 1457, in fetch_channel
    data = await self.http.get_channel(channel_id)
  File "C:\Users\StudMuffin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 185, in request
    async with self.__session.request(method, url, **kwargs) as r:
AttributeError: 'NoneType' object has no attribute 'request'

我不明白这个错误。我在想,也许通过以某种方式循环消息它正在做一些我没有意识到的事情,因此它没有按照我的意图工作。还是我循环这个异步函数的方式?

1 个答案:

答案 0 :(得分:0)

我认为错误是由于协程没有被所需的 discord.py 装饰器之一装饰。

但是,在这种情况下,您可能需要查看 tasks.loop

@tasks.loop(hours=8.0)
async def auto_send():
    channel = await client.fetch_channel('channel_id')
    await channel.send('GOOD MORNING!')