用 Python 编写 Discord 机器人 - 如何让它自动发送消息?

时间:2021-01-27 17:03:50

标签: python discord.py

我想让我的机器人每十分钟自动向频道发送一张图像。这是我的代码:

def job():
  channel = client.get_channel(803842308139253760)
  channel.send(file=discord.File(random.choice('image1', 'image2', 'image3))

schedule.every(10).minutes.do(job)

while True:
  schedule.run_pending()
  time.sleep(1)

我知道日程安排有效。但由于某种原因,它无法发送消息。我收到此错误:AttributeError: 'NoneType' object has no attribute 'send'。我是编程新手,因此不胜感激!

1 个答案:

答案 0 :(得分:1)

您收到该错误是因为通道变量是 NoneNoneType 没有任何属性/方法),因为它不在内部缓存中,您正在阻止整个线程,所以它永远不会加载。我猜我可以修复您的代码,但对于后台任务来说是一个非常糟糕的解决方案。幸运的是,discord.py 带有用于执行此类操作的内置扩展程序,这里有一个示例:

from discord.ext import tasks

@tasks.loop(minutes=10) # You can either pass seconds, minutes or hours
async def send_image(channel: discord.TextChannel):
    image = discord.File("path here")
    await channel.send(file=image)


# Starting the task (you can also do it on the `on_ready` event so it starts when the bot is running)
@client.command()
async def start(ctx):
    channel = client.get_channel(ID_HERE)
    send_image.start(channel)


# Using the `on_ready` event
@client.event
async def on_ready():
    await client.wait_until_ready() # Waiting till the internal cache is done loading

    channel = client.get_channel(ID_HERE)
    send_image.start(channel)


@client.command()
async def stop(ctx):
    send_image.stop()

参考: