Python如何让Discord机器人指定时间单发多条消息且不冲突主代码
问题解决:Discord机器人添加定时任务无冲突方案
问题核心原因
Discord.py 基于异步事件循环运行,你之前使用的同步阻塞式定时循环会占用事件循环线程,导致机器人的消息响应逻辑无法被调度;而协程未await的报错是因为定时任务没有被注册到异步事件循环中执行。
完整修改代码
import discord import datetime from neuralintents import GenericAssistant from discord.ext import tasks chatbot = GenericAssistant('intents.json') chatbot.train_model() chatbot.save_model() print("Bot is active. . .") client = discord.Client(intents=discord.Intents.all()) # 替换为你要发送消息的目标频道数字ID TARGET_CHANNEL_ID = 123456789012345678 # 标记消息是否已发送,避免重复发送 first_msg_sent = False second_msg_sent = False # 异步定时任务,每分钟检查一次时间 @tasks.loop(minutes=1) async def scheduled_send(): global first_msg_sent, second_msg_sent now = datetime.datetime.now() # 19:30发送第一条消息 if now.hour == 19 and now.minute == 30 and not first_msg_sent: channel = client.get_channel(TARGET_CHANNEL_ID) if channel: await channel.send("替换为第一条定时消息的内容") first_msg_sent = True # 19:33发送第二条消息 if now.hour == 19 and now.minute == 33 and not second_msg_sent: channel = client.get_channel(TARGET_CHANNEL_ID) if channel: await channel.send("替换为第二条定时消息的内容") second_msg_sent = True @client.event async def on_ready(): print(f"已登录为 {client.user}") # 机器人就绪后再启动定时任务,避免资源未加载报错 if not scheduled_send.is_running(): scheduled_send.start() @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith("$bb"): response = chatbot.request(message.content[4:]) await message.channel.send(response) # 替换为你自己的机器人令牌 client.run("TOKEN")
关键修改说明
- 用
discord.ext.tasks提供的异步定时循环替代同步阻塞循环,不会占用事件循环线程,不影响机器人正常响应消息指令 - 定时任务在机器人登录完成的
on_ready事件中启动,确保频道等资源已经加载完成 - 用标记变量控制每条消息仅在指定时间发送一次,避免重复触发
注意事项
- 请将代码中的
TOKEN替换为你自己的Discord机器人令牌,TARGET_CHANNEL_ID替换为目标频道的数字ID - 需在Discord开发者平台的机器人设置页开启Message Content Intent权限,否则机器人无法读取消息内容响应
$bb指令 - 定时逻辑使用运行机器人的设备的本地时间,若需要使用UTC时间可将
datetime.datetime.now()替换为datetime.datetime.utcnow()后调整小时判断值 - 若需要每天重复发送两条定时消息,可在定时任务中添加每日重置标记变量的逻辑即可
内容的提问来源于stack exchange,提问作者basil_Jago
相关产品推荐
相关产品推荐

