如何为Discord机器人特定命令设置专属冷却错误提示及转换时间单位
解决方案
1. 实现命令专属冷却提示 + 时间单位转换
可以通过获取触发冷却的命令名称,搭配提示模板字典实现专属提示,同时编写工具函数将秒数转换为更友好的小时/分钟格式:
@client.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandOnCooldown): # 定义各命令的专属提示模板 cooldown_messages = { "work": "你已经工作过了,请在 {time} 后重试", "beg": "你刚乞讨过,{time} 后再来试试吧", "daily": "每日奖励已领取,{time} 后再来领" # 可继续添加其他命令的提示 } # 时间转换函数:将秒转为小时+分钟格式 def format_cooldown_time(seconds): hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) if hours > 0: return f"{hours}小时{minutes}分钟" else: return f"{minutes}分钟" # 获取当前触发冷却的命令名 command_name = ctx.command.name # 选择对应提示,无匹配则用默认提示 message_template = cooldown_messages.get(command_name, "该命令正在冷却中,请在 {time} 后重试") # 格式化时间并发送消息 cool_down_time = format_cooldown_time(error.retry_after) await ctx.send(message_template.format(time=cool_down_time))
2. 关键说明
- 命令专属提示:通过
ctx.command.name获取触发冷却的命令名称,从cooldown_messages字典中匹配对应提示语,可灵活扩展不同命令的专属提示。 - 时间格式转换:
format_cooldown_time函数先计算总小时数,再计算剩余分钟数,根据是否有小时数决定输出格式,避免显示冗余的0小时。 - 默认提示兜底:若命令未配置专属提示,自动使用通用提示,保证所有冷却命令都能正常反馈。
内容的提问来源于stack exchange,提问作者Saptanshu
相关产品推荐
相关产品推荐

