嗨,我正在尝试在用户在支票中的通道以外的通道中使用命令!add
时返回一条消息。这就是我检查命令应在以下渠道中使用的方式:
@commands.check(lambda ctx: ctx.channel.id in [555913791615926302, 567769278351409174])
这是我尝试执行此操作并遇到以下问题的方式:
if not ctx.channel.id:
await ctx.send("You can only use this command in botroom.")
return
这就是我在代码中的用法:
@commands.command(pass_context=True)
@commands.check(lambda ctx: ctx.channel.id in [555913791615926302, 567769278351409174])
async def add(self, ctx, *, rolename):
author = ctx.message.author
role_dict = {
"members":557212810468392970,
"ps4":568761643916328960,
"lol":559792606364565505,
"pc":568725587322208287,
"nintendo switch":558649595102625795,
"ze/zir":569170061592494083}
if not ctx.channel.id:
await ctx.send("You can only use this command in botroom.")
return
role_id = role_dict.get(rolename.lower())
if not role_id:
message = 'I cannot find the role **{}**.'
embed = discord.Embed(description=message.format(rolename))
await ctx.send(embed=embed)
return
role = discord.utils.get(ctx.message.guild.roles, id = role_id)
if role in author.roles:
message = 'It looks like you already have the role **{}**.'
embed = discord.Embed(description=message.format(role.name))
await ctx.send(embed=embed)
else:
await author.add_roles(role)
message = '{} added the role **{}**.'.format(author.display_name, role.name)
embed = discord.Embed(description=message.format(author.display_name, role.name), colour=0x56e011)
await ctx.send(embed=embed)
答案 0 :(得分:1)
如果检查失败,您的协程将永远不会被调用。而是会引发错误,然后可以通过为命令定义error handler来处理错误。
在查看时,您可以同时使该支票看起来更好
def in_channel_with_id(*ids):
def predicate(ctx):
return ctx.channel.id in ids
return commands.check(predicate)
@commands.command()
@in_channel_with_id(555913791615926302, 567769278351409174)
async def add(self, ctx, *, rolename):
...
@add.error
async def add_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send("You can only use this command in botroom.")
else:
raise error