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

discord.py中实现带多可选参数的/profile斜杠命令求助

discord.py /profile 斜杠命令多可选参数实现方案

适用于discord.py v2.x 原生应用命令(斜杠命令)场景,核心思路是通过联合类型兼容单参数为用户/年份的两种输入场景,通过默认值实现参数可选,再按参数类型分支处理逻辑。

完整实现代码

import typing
from datetime import datetime
import discord
from discord import app_commands
from discord.ext import commands

# Cog 结构适配,如果你是在主文件写命令可自行调整结构
class ProfileCog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @app_commands.command(name="profile", description="查询用户个人资料")
    @app_commands.describe(target="要查询的用户或年份", year="要查询的资料年份")
    async def profile(
        self,
        interaction: discord.Interaction,
        target: typing.Optional[typing.Union[discord.Member, int]] = None,
        year: typing.Optional[int] = None
    ):
        # 初始化默认查询规则
        query_user = interaction.user
        current_year = datetime.now().year
        query_year = current_year

        # 分支处理不同参数输入
        if target is not None:
            # 单参数为整数:判定为年份,查询本人对应年份资料
            if isinstance(target, int):
                query_year = target
                if year is not None:
                    await interaction.response.send_message("参数格式有误,仅需输入年份即可查询本人对应年份资料", ephemeral=True)
                    return
            # 单参数为用户:查询指定用户资料,年份取第二个参数或默认当前年
            elif isinstance(target, discord.Member):
                query_user = target
                if year is not None:
                    query_year = year
        
        # 年份合法性校验,可根据自己的业务调整范围
        if query_year < 2015 or query_year > current_year:
            await interaction.response.send_message(f"仅支持查询2015-{current_year}年的资料", ephemeral=True)
            return

        # 此处替换为你自己的资料查询、返回逻辑
        await interaction.response.send_message(f"查询到 {query_user.display_name} {query_year} 年的资料:xxx")

# Cog 加载逻辑
async def setup(bot: commands.Bot):
    await bot.add_cog(ProfileCog(bot))

逻辑说明

  • 完全匹配需求的四种触发场景:
    • 输入 /profile:无参数,默认返回调用者本人当前年份资料
    • 输入 /profile personA:单参数为用户,返回指定用户当前年份资料
    • 输入 /profile 2019:单参数为整数,返回调用者本人对应年份资料
    • 输入 /profile personA 2019:双参数,返回指定用户对应年份资料
  • 所有错误提示设置为仅调用者可见(ephemeral=True),不会污染公共频道环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:15:03