如何实现Discord Bot每日本地时间8点自动发送天气消息?
解决Discord Bot每日定时发送天气消息的问题
原代码的核心问题
- 你的
weather函数仅在Bot启动瞬间恰好是8点时才会被定义,且就算定义成功,它作为命令函数也需要用户手动输入!weather才能触发,完全达不到自动执行的效果。 - 代码里没有持续检测时间的逻辑,Bot启动后只检查一次当前时间,之后不会再定时判断是否到了8点。
正确实现方式:使用discord.py的Tasks扩展
discord.py官方提供了tasks模块专门处理定时/循环任务,这是实现自动触发逻辑最可靠的方式,比手动轮询时间高效得多。
修改后的完整代码
import discord from discord.ext import commands, tasks from datetime import time # 如需指定非UTC时区,先安装pytz库(pip install pytz)再导入 # import pytz intents = discord.Intents.all() client = commands.Bot(command_prefix="!", intents=intents) token = "你的Bot令牌" # 替换成你要发送消息的服务器频道ID(开启Discord开发者模式可复制) TARGET_CHANNEL_ID = 123456789012345678 @client.event async def on_ready(): print("-------------------") print("The Bot Is Ready!") print("-------------------") # 启动定时任务,防止重复启动 if not daily_weather_report.is_running(): daily_weather_report.start() @client.command() async def info(ctx): await ctx.send("Hello, I am the Weather Pledge!") await ctx.send("I send out a location-based weather report every morning at 8am local time.") # 定义每日8点执行的定时任务 # 若要指定时区(比如中国时区),修改为: # @tasks.loop(time=time(hour=8), tz=pytz.timezone('Asia/Shanghai')) @tasks.loop(time=time(hour=8)) async def daily_weather_report(): # 获取目标频道 channel = client.get_channel(TARGET_CHANNEL_ID) if channel: # 此处替换为你的天气API调用逻辑 await channel.send("今日天气报告:") await channel.send("气温:25℃,降雨概率:10%") else: print("无法找到目标频道,请检查频道ID是否正确") # 捕获定时任务的执行错误 @daily_weather_report.error async def daily_weather_report_error(error): print(f"定时任务出错:{error}") client.run(token)
关键细节说明
@tasks.loop(time=time(hour=8)):直接指定任务每天8点执行,可通过minute和second参数精确到分秒;需要时区支持时,用tz参数指定对应时区即可。on_ready中启动任务:确保Bot完全初始化就绪后再启动定时任务,避免出现未加载完成就执行任务的异常。- 频道ID设置:必须开启Discord开发者模式,才能复制目标频道的ID,确保Bot能找到发送消息的渠道。
- 错误处理:通过
@任务名.error装饰器捕获任务执行中的异常,方便快速排查问题。
额外注意事项
- 确保Bot在目标服务器中拥有发送消息的权限,可在服务器设置中给Bot分配对应权限。
- 如果需要针对不同用户的本地时间发送消息,需要提前存储用户的时区信息,再根据每个用户的时区计算发送时间,这种场景建议搭配数据库存储用户设置。
内容的提问来源于stack exchange,提问作者Benjamin Buchanan
相关产品推荐
相关产品推荐

