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

使用discord.py实现Discord机器人定时执行命令问题

实现Discord机器人每周定时执行任务的方案

完全可以实现,不用纠结旧方案失效的问题,用APScheduler配合最新版的discord.py就能搞定,下面是具体步骤:

1. 安装依赖

先安装适配discord.py异步环境的APScheduler版本:

pip install apscheduler

2. 整合定时任务到机器人代码

以下是完整的示例框架,你可以把已实现的命令逻辑直接嵌入进去:

import discord
from discord.ext import commands
from apscheduler.schedulers.asyncio import AsyncIOScheduler

# 初始化机器人(根据你的intents配置调整)
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

# 初始化调度器,设置你的时区(比如亚洲上海)
scheduler = AsyncIOScheduler(timezone='Asia/Shanghai')

# 定义定时执行的任务函数
async def run_scheduled_jobs():
    # 替换成你要发送消息的目标频道ID
    target_channel = bot.get_channel(123456789012345678)
    if not target_channel:
        print("目标频道不存在,任务终止")
        return

    # 调用你已实现的计时器和调查逻辑
    # 方式1:直接发送命令触发(如果你的命令是通过消息触发的)
    await target_channel.send("!timer")
    await target_channel.send("!survey1")
    await target_channel.send("!survey2")

    # 方式2:直接调用命令函数(更稳定,不需要依赖消息触发)
    # 假设你的计时器命令函数是timer_func,调查是survey1_func、survey2_func
    # await timer_func(target_channel)
    # await survey1_func(target_channel)
    # await survey2_func(target_channel)

# 机器人就绪时启动调度器
@bot.event
async def on_ready():
    print(f"已登录为 {bot.user.name}")
    # 添加定时任务:每周二、周四上午11:30执行
    scheduler.add_job(
        run_scheduled_jobs,
        trigger='cron',
        day_of_week='tue,thu',  # 周二=tue,周四=thu
        hour=11,
        minute=30
    )
    scheduler.start()

# 运行机器人
bot.run("你的机器人TOKEN")

关键注意事项

  • 时区设置:一定要把timezone参数改成你所在的时区,比如Asia/Shanghai,否则定时时间会偏差。
  • 命令调用方式:优先用直接调用函数的方式,比发送消息触发更稳定,避免因为前缀权限、消息过滤等问题导致命令不执行。
  • 机器人托管:定时任务需要机器人持续在线,所以要把机器人部署到云服务器、VPS或者类似的托管平台上。
  • discord.py版本:确保使用最新的v2.x版本,旧版本的API和事件循环可能和APScheduler不兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:30:58