Discord Python Bot添加后台定时任务后原有交互命令失效问题
问题原因
- 核心问题是定时任务逻辑阻塞了异步事件循环。你代码中的
await asyncio.sleep(1)写在了while not client.is_closed()循环外部,导致循环运行时没有任何暂停操作,会以最高频率无限空转,完全占用了Discord Bot的异步事件调度资源,Bot没有空闲处理用户发送的命令触发事件。 - 若你使用的是discord.py 2.0及以上版本,还可能是未开启消息内容意图:Discord v10 API之后要求机器人显式申请消息内容权限才能读取用户发送的普通消息内容,否则无法匹配前缀命令。
修复方案
- 修正timer函数的sleep位置,将
await asyncio.sleep(1)缩进放到while循环内部,每轮循环后释放1秒资源给其他事件处理,修改后的timer函数如下:
async def timer(): await client.wait_until_ready() msg_sent = False while not client.is_closed(): if any(time().hour == race for race in race_times_utc) and time().minute == 0: if not msg_sent: channel = client.get_channel(838626115326636022) racer_role = get(channel.guild.roles, name = 'Racers') embed = discord.Embed( title = 'Race Time', description = 'Scheduled reminder for everyone that race starts soon.', colour = discord.Colour.blue() ) await channel.send(f'{racer_role.mention}',embed=embed) msg_sent = True else: msg_sent = False # sleep移到循环内部 await asyncio.sleep(1)
- 若使用discord.py 2.0及以上版本,补充开启消息内容意图:
- 先在Discord开发者后台的对应机器人设置页面,打开
Message Content Intent开关 - 修改Bot初始化代码,增加意图配置:
intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix = ';',help_command=None, intents=intents)
- 确保
;help等命令的实现逻辑完整,将示例中的...替换为实际的响应代码,比如:
@client.command() async def help(ctx): await ctx.send("可用命令:\n;help 查看帮助说明")
内容的提问来源于stack exchange,提问作者user14707947
相关产品推荐
相关产品推荐

