首页 > 解决方案 > 用 Python 编写 Discord 机器人 - 如何让它自动发送消息?

问题描述

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

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'。我是编程新手,所以任何见解都将不胜感激!

标签: pythondiscord.py

解决方案


您收到该错误是因为通道变量是None(aNoneType没有任何属性/方法),因为通道不在内部缓存中,您阻塞了整个线程,因此它永远不会加载。我猜我可以修复您的代码,但对于后台任务来说是一个非常糟糕的解决方案。幸运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()

参考:


推荐阅读