You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Discord机器人的freegen命令添加冷却错误处理器?

解决Discord机器人freegen命令冷却无提示问题

默认的@app_commands.checks.cooldown触发冷却限制时,会抛出AppCommandRateLimited异常,但这个异常不会被你代码里的try-except块捕获(因为异常在命令函数执行前就触发了)。要实现自定义冷却提示,需要给命令添加专门的错误处理函数:

修改后的完整代码

import discord
from discord import app_commands
from discord.app_commands import AppCommandRateLimited
import glob
import random
import os

# 确保你的ShowCookieView类已正确定义
class ShowCookieView(discord.ui.View):
    def __init__(self, file_path):
        super().__init__()
        self.file_path = file_path
    # 这里补充你原有的按钮逻辑(如果有)

@tree.command(guild=discord.Object(id=1071088035652976711), name="freegen", description="Generates a cookie alt or gamepass alt.")
@app_commands.checks.cooldown(1, 3600, key=lambda i: (i.user.id))
async def gen(interaction: discord.Interaction, type: str):
    try:
        if type.lower() == "cookie alt":
            file_paths = glob.glob(r"C:\Users\PC\Downloads\blahajaltsfixyay\freealts\*.txt")
            if not file_paths:
                embed = discord.Embed(title="Out of Stock", color=discord.Color.red())
                embed.description = "Sorry, we are out of stock currently."
                await interaction.response.send_message(embed=embed, ephemeral=True)
                return
            file_path = random.choice(file_paths)
            view = ShowCookieView(file_path)
            embed = discord.Embed(title="Cookie Alt Generated", color=0x9B59B6)
            embed.add_field(name="Username", value=f"```{os.path.splitext(os.path.basename(file_path))[0]}```", inline=False)
            await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
        elif type.lower() == "gamepass":
            file_path = r"C:\Users\PC\Downloads\blahajaltsfixyay\freegamepass\alts.txt"
            with open(file_path, "r") as f:
                lines = f.readlines()
            if len(lines) == 0:
                embed = discord.Embed(title="Out of Stock", color=discord.Color.red())
                embed.description = "We're out of stock, Please wait until we restock then try again."
                await interaction.response.send_message(embed=embed, ephemeral=True)
                return
            line = random.choice(lines).strip()
            email, password = line.split(":")
            dm_embed = discord.Embed(title="Gamepass Alt Generated!", color=discord.Color.purple())
            dm_embed.add_field(name="Email", value=f"```{email}```", inline=False)
            dm_embed.add_field(name="Password", value=f"```{password}```", inline=False)
            dm_embed.add_field(name="Combo", value=f"```{line}```", inline=False)
            dm_embed.set_footer(text="Generated by Blahaj Alts")
            await interaction.response.send_message(embed=discord.Embed(title="Check your DMs", color=discord.Color.purple()), ephemeral=True)
            await interaction.user.send(embed=dm_embed)
            lines.remove(line + "\n")
            with open(file_path, "w") as f:
                f.writelines(lines)
        else:
            await interaction.response.send_message("Invalid Alt Type selected.", ephemeral=True)
    except Exception as e:
        print(f"An error occurred: {e}")
        await interaction.response.send_message("An error occurred while processing your request.", ephemeral=True)

# 冷却专属错误处理函数
@gen.error
async def gen_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, AppCommandRateLimited):
        remaining_time = int(error.retry_after)
        # 如需转成分钟显示,可替换为:remaining_minutes = remaining_time // 60
        await interaction.response.send_message(f"您处于冷却中,剩余时长为{remaining_time}秒", ephemeral=True)
    else:
        await interaction.response.send_message("命令执行出错,请稍后再试。", ephemeral=True)
        print(f"Command error: {error}")

关键说明

  1. 导入异常类:必须导入AppCommandRateLimited才能捕获冷却触发的异常
  2. 绑定错误处理:通过@gen.error装饰器将错误处理函数与freegen命令绑定,仅处理该命令的错误
  3. 剩余时间计算:error.retry_after返回剩余冷却秒数,转成整数后可直接显示,也可转换成分钟等更友好的格式
  4. 私密提示:用ephemeral=True确保只有触发冷却的用户能看到提示,避免公共频道刷屏

内容的提问来源于stack exchange,提问作者cat mother

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:07:07