discord.py如何在单条指令中接收多参数及整合多类型指令功能?
discord.py 指令多参数接收与多类型参数整合方案
一、单指令接收多参数基础实现
discord.py的指令系统支持直接通过函数参数类型声明,自动匹配用户输入的参数类型,不需要手动做类型解析,以下是你提到的三个场景的实现代码:
1. /say 接收字符串参数
import discord from discord import app_commands client = discord.Client(intents=discord.Intents.default()) tree = app_commands.CommandTree(client) @tree.command(name="say", description="让机器人发送指定文本") async def say(ctx, content: str): # 若使用前缀指令要接收带空格的整段文本,可写为 async def say(ctx, *, content: str) await ctx.response.send_message(content)
2. /repeat 接收整数+字符串参数
@tree.command(name="repeat", description="按指定次数重复发送内容") async def repeat(ctx, times: int, content: str): # 限制重复次数避免刷屏 if 1 > times or times > 10: await ctx.response.send_message("重复次数仅支持1-10", ephemeral=True) return await ctx.response.send_message("\n".join([content for _ in range(times)]))
3. /kill 接收提及用户参数
@tree.command(name="kill", description="整活指令:击杀指定用户") async def kill(ctx, user: discord.Member): await ctx.response.send_message(f"user killed {user.mention}")
二、多类型参数功能整合到同一指令的实现
有两种常用方案可以实现把不同参数类型的功能合并到同一条指令:
方案1:联合类型自动匹配
用typing.Union声明参数支持的多种类型,程序会自动判断输入参数的类型执行对应逻辑:
from typing import Union @tree.command(name="action", description="整合功能指令,自动识别输入类型执行对应操作") async def action(ctx, param: Union[int, str, discord.Member]): if isinstance(param, int): # 输入为整数时执行重复逻辑 await ctx.response.send_message("\n".join(["默认重复内容" for _ in range(param)])) elif isinstance(param, discord.Member): # 输入为提及用户时执行击杀逻辑 await ctx.response.send_message(f"user killed {param.mention}") elif isinstance(param, str): # 输入为普通文本时执行发送逻辑 await ctx.response.send_message(param)
方案2:子命令组(更清晰易用)
如果希望功能区分更明确,用户调用时不容易出错,可以用子命令组实现:
# 定义主指令为 action 的子命令组 action_group = app_commands.Group(name="action", description="整合功能指令组") @action_group.command(name="say", description="发送指定文本") async def action_say(ctx, content: str): await ctx.response.send_message(content) @action_group.command(name="repeat", description="重复发送指定内容") async def action_repeat(ctx, times: int, content: str): if 1 > times or times > 10: await ctx.response.send_message("重复次数仅支持1-10", ephemeral=True) return await ctx.response.send_message("\n".join([content]*times)) @action_group.command(name="kill", description="击杀指定用户") async def action_kill(ctx, user: discord.Member): await ctx.response.send_message(f"user killed {user.mention}") # 把子命令组注册到指令树 tree.add_command(action_group)
注册完成后用户可以通过/action say、/action repeat、/action kill分别调用对应的功能。
注:以上代码基于discord.py 2.0+版本实现,低版本需要先升级依赖库。
内容的提问来源于stack exchange,提问作者Nathan Riptidal
相关产品推荐
相关产品推荐

