You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py-rewrite中用client.command判断指令是否在指定频道触发

实现方案

discord.py-rewrite 框架内置了指令校验机制,可以直接通过装饰器实现频道限制,无需监听on_message事件,常用实现方式如下:

方法1:自定义可复用的频道检查装饰器

适合需要给多个指令配置不同允许频道的场景:

  1. 先定义通用检查装饰器
from discord.ext import commands

# 入参为允许运行指令的频道ID列表
def is_in_allowed_channels(allowed_channel_ids: list):
    async def predicate(ctx):
        return ctx.channel.id in allowed_channel_ids
    return commands.check(predicate)
  1. 给目标指令加装饰器即可生效
# 示例:仅允许ID为123456、789012的频道触发该指令
@client.command()
@is_in_allowed_channels([123456, 789012])
async def test(ctx):
    await ctx.send("指令运行成功")
  1. 可选:自定义校验失败的提示
    校验不通过时会抛出commands.CheckFailure异常,可全局捕获后返回友好提示:
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("该指令不可在当前频道使用")
    # 其他异常处理逻辑可在此补充

方法2:单指令快速配置

如果仅需要给单个指令做一次性频道限制,无需复用校验逻辑,可以直接写匿名检查:

@client.command()
@commands.check(lambda ctx: ctx.channel.id == 123456)
async def single_channel_cmd(ctx):
    await ctx.send("仅指定频道可触发该指令")

方法3:全局指令频道限制

如果需要所有指令都遵守统一的频道规则,可以注册全局检查器,无需给每个指令单独加装饰器:

@client.check
async def global_channel_check(ctx):
    allowed_channel_ids = [123456, 789012]
    # 可额外配置例外规则,示例:管理员不受频道限制
    if ctx.author.guild_permissions.administrator:
        return True
    return ctx.channel.id in allowed_channel_ids

注意:所有示例中的频道ID需要替换为你自己服务器对应频道的实际数值,频道ID可在Discord客户端开启开发者模式后右键频道复制获取

内容的提问来源于stack exchange,提问作者Useless_lol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:33:02