如何为 discord.py 命令制作包装函数?
How can I make a wrapper function for discord.py commands?
我一直在尝试创建包装器@validate_channel,如果在服务器上而不是在私人频道上执行,这个包装器应该只使命令 运行,我正在尝试:
命令函数:
@validate_channel
@bot.command(brief="Adds one or more members to the whitelist")
async def add(ctx: commands.Context, *users: discord.Member):
if not check_permissions(ctx.author.id, ctx.guild):
await ctx.send(NOT_ALLOWED_MSG)
else:
config = get_config(ctx.guild.id)
allowed_users = config.get('allowed-users', [])
if not users:
await ctx.send(f"You didn't specify any users!")
return
for user in users:
if user.id not in allowed_users:
allowed_users.append(user.id)
config['allowed-users'] = allowed_users
update_config(ctx.guild.id, config)
await ctx.send(f"Added {', '.join(user.name for user in users)} to the whitelist!")
包装器:
def validate_channel(func):
async def inner(ctx: commands.Context, message, *args, **kwargs):
if ctx.channel.type is discord.ChannelType.private:
await ctx.send("This command cannot be run from direct messages.")
else:
return func
return inner
但似乎不管用,不管我怎么试,谁能帮帮我?
您应该使用 commands.check
而不是返回 inner
def validate_channel():
async def inner(ctx):
if not ctx.channel.type is discord.ChannelType.private: # or even better `not isinstance(ctx.channel, discord.DMChannel)`
await ctx.send("You cannot use this command in DMs")
return False
return True
return commands.check(inner)
@validate_channel()
@bot.command()
async def ...
更好、更短、更简单的方法是使用 commands.dm_only
检查:
@commands.dm_only()
@bot.command()
async def ...
我一直在尝试创建包装器@validate_channel,如果在服务器上而不是在私人频道上执行,这个包装器应该只使命令 运行,我正在尝试:
命令函数:
@validate_channel
@bot.command(brief="Adds one or more members to the whitelist")
async def add(ctx: commands.Context, *users: discord.Member):
if not check_permissions(ctx.author.id, ctx.guild):
await ctx.send(NOT_ALLOWED_MSG)
else:
config = get_config(ctx.guild.id)
allowed_users = config.get('allowed-users', [])
if not users:
await ctx.send(f"You didn't specify any users!")
return
for user in users:
if user.id not in allowed_users:
allowed_users.append(user.id)
config['allowed-users'] = allowed_users
update_config(ctx.guild.id, config)
await ctx.send(f"Added {', '.join(user.name for user in users)} to the whitelist!")
包装器:
def validate_channel(func):
async def inner(ctx: commands.Context, message, *args, **kwargs):
if ctx.channel.type is discord.ChannelType.private:
await ctx.send("This command cannot be run from direct messages.")
else:
return func
return inner
但似乎不管用,不管我怎么试,谁能帮帮我?
您应该使用 commands.check
而不是返回 inner
def validate_channel():
async def inner(ctx):
if not ctx.channel.type is discord.ChannelType.private: # or even better `not isinstance(ctx.channel, discord.DMChannel)`
await ctx.send("You cannot use this command in DMs")
return False
return True
return commands.check(inner)
@validate_channel()
@bot.command()
async def ...
更好、更短、更简单的方法是使用 commands.dm_only
检查:
@commands.dm_only()
@bot.command()
async def ...