用 Python 编写一个 Discord 机器人 - 如何让它每天在特定时间发送一条消息?

时间:2021-02-01 01:42:50

标签: python discord.py

我想让机器人每天下午 1 点发送一条消息。这是我的代码:

@tasks.loop(hours=24)
async def called_every_day():
    channel = client.get_channel(800476409587171369)
    print(f"Got channel {channel}")
    await channel.send("Your message")

@called_every_day.before_loop
async def before():
    await client.wait_until_ready()
    print("Finished waiting")

called_every_day.start()

这有效,如果我在下午 1 点启动机器人。但是,每当我编辑代码并重新启动机器人时,它都会重新启动循环。我想防止这种情况发生,我该怎么做?我是编程新手,因此不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以使用 APSchedulerCron 安排您的命令在特定时间发送,例如下午 12:00

文档:https://apscheduler.readthedocs.io/en/stable/https://apscheduler.readthedocs.io/en/stable/modules/triggers/cron.html

这是一个例子:

# Async scheduler so it does not block other events
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord.ext import commands
import discord

bot = commands.Bot(command_prefix="!")

async def func():
    await bot.wait_until_ready()
    c = bot.get_channel(800476409587171369)
    await c.send("Your Message")

@bot.event
async def on_ready():
    print("Ready")
    # Initializing scheduler
    scheduler = AsyncIOScheduler()
    # Executes your function at 24:00 (Local Time)
    scheduler.add_job(func, CronTrigger(hour="24", minute="0", second="0")) 
    # Starting the scheduler
    scheduler.start()