discord.js v14如何设置斜杠命令仅可在服务器使用,禁止DM调用
实现Discord斜杠命令仅服务器可用的方案
下面分主流的两个Discord开发库给出具体实现方式:
一、使用discord.py(Python)
方法1:使用官方自带的guild_only装饰器
这是最简洁的方式,给斜杠命令加上装饰器后,用户在私信调用时会自动触发错误,你可以捕获错误并给出明确提示:
import discord from discord import app_commands from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.default()) @bot.tree.command(name="test") @app_commands.guild_only() # 核心装饰器,限制仅服务器可用 async def test_command(interaction: discord.Interaction): await interaction.response.send_message("这是仅服务器可用的命令!") # 捕获私信调用的错误,给用户反馈 @bot.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.NoPrivateMessage): await interaction.response.send_message("此命令仅能在服务器中使用,无法通过私信调用!", ephemeral=True) else: # 处理其他类型的命令错误 raise error bot.run("你的机器人Token")
方法2:手动检查服务器上下文
如果不想用装饰器,也可以在命令逻辑里直接判断调用环境:
@bot.tree.command(name="test") async def test_command(interaction: discord.Interaction): # 检查是否在服务器环境中 if not interaction.guild: await interaction.response.send_message("此命令仅能在服务器中使用!", ephemeral=True) return # 正常执行命令逻辑 await interaction.response.send_message("命令执行成功!")
二、使用discord.js(JavaScript/TypeScript)
方法1:在命令执行时检查服务器存在性
在斜杠命令的execute函数开头,先判断interaction.guild是否存在,不存在则直接回复提示:
const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('test') .setDescription('仅服务器可用的测试命令'), async execute(interaction) { if (!interaction.guild) { return interaction.reply({ content: '此命令仅能在服务器中使用,无法通过私信调用!', ephemeral: true // 仅调用者能看到这条回复 }); } // 正常执行命令逻辑 await interaction.reply('命令执行成功!'); }, };
方法2:使用内置的GuildOnly预检查(v14+)
discord.js v14及以上版本支持给命令添加预检查,可全局或针对单个命令设置:
const { SlashCommandBuilder, GuildOnly } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('test') .setDescription('仅服务器可用的测试命令'), preconditions: [GuildOnly], // 核心预检查规则 async execute(interaction) { await interaction.reply('命令执行成功!'); }, };
然后在客户端的错误处理中捕获预检查失败的情况,给用户提示:
client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; const command = interaction.client.commands.get(interaction.commandName); if (!command) return; try { await command.execute(interaction); } catch (error) { if (error.name === 'GuildOnlyError') { return interaction.reply({ content: '此命令仅能在服务器中使用!', ephemeral: true }); } console.error(error); await interaction.reply({ content: '执行命令时出错!', ephemeral: true }); } });
内容的提问来源于stack exchange,提问作者Fome
相关产品推荐
相关产品推荐

