在频道问题中返回消息

Returning a message in a channel issue

您好,当用户在检查中的频道以外的频道中使用命令 !add 时,我正在尝试 return 一条消息。这就是我检查应该使用命令的频道的方式:

@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)

如果检查失败,您的协程将永远不会被调用。相反,会引发错误,然后您可以通过为命令定义 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