如何动态获取Discord交互命令的输入字段名称与值?
解决Discord交互命令动态获取参数名与值的问题
可以通过两种方式实现动态获取用户输入的参数名和对应值:
方法1:利用函数内置属性(适合参数少的场景)
直接通过函数的__code__.co_varnames拿到定义的参数名,排除必传的interaction后,和参数值配对生成字典,只保留用户实际输入的非None项:
@bot.tree.command(name='getchar', description='Get all the information about an NPC') async def getchar(interaction: discord.Interaction, name: str = None, residence: str = None, age: int = None): # 获取所有参数名,排除第一个interaction参数 param_names = getchar.__code__.co_varnames[1:] # 获取对应参数的值 param_values = [name, residence, age] # 生成仅包含非None值的参数字典 input_params = {name: value for name, value in zip(param_names, param_values) if value is not None} print(input_params) await interaction.response.send_message(f"用户输入的参数:{input_params}")
当用户输入/getchar name:test age:40时,input_params会生成{'name': 'test', 'age': 40},直接用于后续逻辑即可。
方法2:用inspect模块(适合参数多的场景)
如果你的命令有7个可选参数,手动列参数值太繁琐,用inspect模块自动解析函数签名,配合locals()获取变量值,更灵活:
import inspect @bot.tree.command(name='getchar', description='Get all the information about an NPC') async def getchar(interaction: discord.Interaction, name: str = None, residence: str = None, age: int = None, gender: str = None, job: str = None, hobby: str = None, status: str = None): # 获取函数签名,提取除interaction外的所有参数名 sig = inspect.signature(getchar) param_names = list(sig.parameters.keys())[1:] # 从当前作用域中筛选出非None的参数 input_params = {param: locals()[param] for param in param_names if locals()[param] is not None} print(input_params) await interaction.response.send_message(f"用户输入的参数:{input_params}")
这种方式不用手动维护参数值列表,新增或删除参数时代码不用跟着改,适配性更强。
内容的提问来源于stack exchange,提问作者Chrisspray
相关产品推荐
相关产品推荐

