You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py机器人如何实现固定时间间隔自动发送消息?

Python Discord机器人定时自动发消息的可行实现方案

方案1:使用discord.py内置tasks扩展(原生适配,优先推荐)

这是discord.py官方提供的异步定时任务工具,不需要额外安装第三方依赖,适配机器人的异步运行环境,适合绝大多数定时发消息的需求。

  • 核心用法示例:
import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta

# 替换为你自己的intents配置,需要开启消息相关权限
YOUR_INTENTS = 你自己的intents配置
bot = commands.Bot(command_prefix="!", intents=YOUR_INTENTS)

# 定义每周执行一次的消息发送任务
@tasks.loop(hours=24*7)
async def weekly_announce():
    # 替换为目标发送频道的ID
    channel = bot.get_channel(1234567890)
    if channel:
        await channel.send("这是每周定时推送的公告内容")

# 可选配置:固定任务触发的具体时间点,比如固定每周一中午12点发送
@weekly_announce.before_loop
async def before_task_start():
    # 等Bot完全启动后再执行任务
    await bot.wait_until_ready()
    # 计算当前时间到下一个周一12点的时间差,作为首次启动的延迟
    now = datetime.now()
    next_run = now + timedelta(days=(0 - now.weekday()) % 7, hours=12, minutes=0, seconds=0)
    if next_run < now:
        next_run += timedelta(days=7)
    await asyncio.sleep((next_run - now).total_seconds())

@bot.event
async def on_ready():
    # Bot上线时启动定时任务
    weekly_announce.start()
    print("Bot已正常启动")

bot.run("你自己的Bot Token")

方案2:使用APScheduler定时任务库(适合复杂定时规则)

如果需要更灵活的定时规则,比如每月最后一天推送、每周三下午3点推送这种自定义场景,推荐用APScheduler库,它支持cron表达式,自动处理时区、时间差计算,不需要自己写时间逻辑。

  • 首先安装依赖:pip install apscheduler
  • 核心用法示例:
from discord.ext import commands
from apscheduler.schedulers.asyncio import AsyncIOScheduler

YOUR_INTENTS = 你自己的intents配置
bot = commands.Bot(command_prefix="!", intents=YOUR_INTENTS)
# 配置对应时区,避免时间误差
scheduler = AsyncIOScheduler(timezone="Asia/Shanghai")

# 定义每月推送的消息任务
async def monthly_announce():
    channel = bot.get_channel(1234567890)
    if channel:
        await channel.send("这是每月定时推送的公告内容")

@bot.event
async def on_ready():
    # 添加cron规则定时任务:示例为每月1号上午10点执行
    scheduler.add_job(monthly_announce, "cron", day=1, hour=10, minute=0)
    # 每周一12点推送的规则示例:scheduler.add_job(weekly_announce, "cron", day_of_week=0, hour=12, minute=0)
    scheduler.start()
    print("Bot已启动,定时任务已加载")

bot.run("你自己的Bot Token")

方案3:asyncio原生sleep循环(仅推荐临时测试用)

如果是短周期的简单测试,可以直接用asyncio的sleep实现循环发送,但是长周期(周/月级别)不推荐使用,长时间运行容易出现时间误差,且Bot重启后无法保留任务进度。

  • 核心用法示例:
import asyncio
from discord.ext import commands

YOUR_INTENTS = 你自己的intents配置
bot = commands.Bot(command_prefix="!", intents=YOUR_INTENTS)

async def auto_send_loop():
    await bot.wait_until_ready()
    channel = bot.get_channel(1234567890)
    while not bot.is_closed():
        if channel:
            await channel.send("测试定时消息")
        # 间隔时间单位为秒,示例为1天
        await asyncio.sleep(86400)

@bot.event
async def on_ready():
    bot.loop.create_task(auto_send_loop())
    print("Bot已启动")

bot.run("你自己的Bot Token")
通用注意事项
  • 所有代码中的占位参数(intents配置、频道ID、Bot Token)需要替换为你自己的实际配置
  • 确保Bot在目标频道拥有查看频道、发送消息的权限,否则会出现发送失败的问题
  • 长周期运行的任务建议添加日志记录执行状态,方便排查问题;如果部署的服务有自动重启逻辑,建议将任务执行记录存在本地文件或数据库中,重启后可以判断是否需要补发消息

内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:39:01