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

如何在discord.py编写的机器人中实现指定频道仅允许发送help单词的功能

discord.py 实现指定频道仅允许发送「help」消息的方案

前置准备

discord.py v2.0及以上版本需要手动开启消息内容读取权限:

  1. 前往Discord开发者后台的机器人管理页,开启Message Content Intent开关
  2. 代码初始化Bot时声明消息内容意图:
import discord
from discord.ext import commands

# 声明所需权限
intents = discord.Intents.default()
intents.message_content = True

# 初始化Bot,前缀可自行修改
bot = commands.Bot(command_prefix="!", intents=intents)

核心监听逻辑

# 替换为你的目标限制频道的数字ID
TARGET_CHANNEL_ID = 123456789012345678

@bot.event
async def on_message(message):
    # 跳过机器人自身发送的消息,避免循环触发
    if message.author.bot:
        return

    # 仅对目标限制频道做校验
    if message.channel.id == TARGET_CHANNEL_ID:
        # 去除消息首尾空格后校验内容,加.lower()实现不区分大小写匹配
        if message.content.strip().lower() != "help":
            # 机器人需要拥有目标频道的「管理消息」权限才能删除消息
            await message.delete()
            # 可选:给触发规则的用户发送私信提醒,注释取消即可启用
            # try:
            #     await message.author.send(f"频道 {message.channel.name} 仅允许发送`help`单词,其他消息会被自动拦截")
            # except:
            #     # 忽略用户关闭私信导致的发送失败异常
            #     pass

    # 必须保留这行代码,否则Bot的其他slash command/前缀命令会无法触发
    await bot.process_commands(message)

扩展适配

  • 如需同时限制多个频道,可将TARGET_CHANNEL_ID改为ID列表,判断逻辑调整为if message.channel.id in [频道ID1, 频道ID2, 频道ID3]
  • 如需严格区分大小写匹配,删除.lower()即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 20:15:01