Discord机器人!spin命令冷却功能失效求助
问题:Discord机器人!spin命令冷却功能失效
我为朋友制作了一款Discord机器人,其中!spin命令的功能是随机将语音频道内的成员静音并禁麦5秒,同时设置了1小时的冷却时长,但冷却功能完全没有生效。以下是相关代码:
# Check if the message is a command if message.content.startswith('!spin'): # Get the command and arguments from the message command, *args = message.content.split() command = command[1:] # remove the leading exclamation mark # Check if the command is on cooldown if command in cooldowns and cooldowns[command] > message.created_at: # The command is on cooldown, so do not execute it return # Check which command was used if command == 'spin': # Scan the voice channels in the server for channel in message.guild.voice_channels: # Get the members in the voice channel members = channel.members if not members: return # Pick a random member from the list of members lucky_member = random.choice(members) # Mute and deafen the lucky member for 5 seconds await lucky_member.edit(mute=True, deafen=True) await asyncio.sleep(5) # delay for 5 seconds await lucky_member.edit(mute=False, deafen=False) await message.channel.send('command is on cooldown for 1h') # Put the command on cooldown for 1 hour cooldowns[command] = message.created_at + datetime.timedelta(hours=1)
错误原因分析
- 冷却设置被提前跳过:遍历语音频道时,只要遇到空频道就执行
return,直接终止命令,导致后续的冷却设置代码从未被执行,命令永远不会进入冷却状态。 - 冷却无用户反馈:冷却检查时直接
return,用户无法得知命令处于冷却中,也没有任何提示。 - 语音频道逻辑错误:遍历所有语音频道时,会对每个有成员的频道都执行一次静音操作,且空频道会直接终止命令,不符合“随机选择一个成员”的需求。
修正后的代码
import random import asyncio from datetime import datetime, timedelta # 全局冷却字典,机器人启动时需初始化 cooldowns = {} if message.content.startswith('!spin'): command, *args = message.content.split() command = command[1:] # 移除开头的感叹号 current_time = message.created_at # 检查冷却并给出明确反馈 if command in cooldowns and cooldowns[command] > current_time: remaining = cooldowns[command] - current_time hours = remaining.seconds // 3600 minutes = (remaining.seconds % 3600) // 60 await message.channel.send(f'命令冷却中,还剩 {hours}小时{minutes}分钟') return if command == 'spin': # 筛选出有成员的语音频道 active_vcs = [vc for vc in message.guild.voice_channels if vc.members] if not active_vcs: await message.channel.send('当前没有成员在语音频道内') return # 随机选择语音频道和成员 target_vc = random.choice(active_vcs) lucky_member = random.choice(target_vc.members) # 执行静音禁麦操作并捕获异常 try: await lucky_member.edit(mute=True, deafen=True) await asyncio.sleep(5) await lucky_member.edit(mute=False, deafen=False) await message.channel.send(f'已对 {lucky_member.display_name} 执行静音禁麦5秒!') except Exception as e: await message.channel.send(f'操作失败:{str(e)}') # 确保冷却设置逻辑一定会执行 cooldowns[command] = current_time + timedelta(hours=1)
关键修正点
- 冷却逻辑优化:补充冷却状态的用户反馈,同时将冷却设置代码放在命令执行成功的逻辑之后,避免被提前终止的代码跳过。
- 语音频道处理调整:先筛选所有有成员的语音频道,再随机选择目标频道和成员,避免空频道导致命令终止,也符合功能需求。
- 异常处理:增加
try-except块捕获操作失败的情况(如机器人权限不足),防止机器人崩溃。
内容的提问来源于stack exchange,提问作者590ms
相关产品推荐
相关产品推荐

