繁体   English   中英

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

[英]Programming a Discord bot in Python- How do I make it automatically send messages?

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

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

您收到该错误是因为通道变量为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()

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM