Discord机器人的命令参数能否同时支持成员提及和身份组提及?
可行实现方案
你当前的代码问题出在类型注解写法不符合discord.py的转换器规则:discord.Member or discord.Role 不会被正确识别为「成员或角色」的联合类型,只会生效第一个discord.Member匹配规则,输入身份组时会报错。
修正后的完整实现如下:
第一步:前置依赖与权限配置
需要先从typing模块导入Union声明联合类型,同时确保你的机器人开启了Server Members Intent权限(在Discord开发者后台的机器人配置页开启,同时代码初始化时要传入对应intent)。
第二步:功能代码实现
from typing import Union import discord from discord.ext import commands # 初始化实例时必须开启成员intent,否则无法匹配非缓存的用户/身份组 intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix="!", intents=intents) @client.command() async def remind(ctx, target: Union[discord.Member, discord.Role] = None, *, content: str = "收到一条提醒"): if not target: await ctx.send("请指定要提醒的用户或身份组") return # 直接调用mention属性即可触发@提及效果,discord.py会自动处理为平台可识别的提及格式 await ctx.send(f"{target.mention} {content}")
补充说明
- 如果需要支持@全体成员,额外新增参数匹配规则,同时给机器人开放
@everyone权限即可 - 若要实现定时提醒,将target对象和提醒内容存储到数据库/内存,触发时调用
mention属性发送消息即可,格式和即时发送完全一致
内容的提问来源于stack exchange,提问作者looke
相关产品推荐
相关产品推荐

