如何在Discord.js中检查服务器成员能否在指定频道发送消息
Discord斜杠命令权限校验:仅允许用户在有权限的频道发送Embed
下面分主流开发库给出实现方案:
一、使用discord.py实现
核心逻辑是在命令执行时,先校验用户在所选频道的发送消息权限,无权限则终止命令并提示用户。
import discord from discord import appcommands class MyClient(discord.Client): def __init__(self): super().__init__(intents=discord.Intents.default()) self.tree = appcommands.CommandTree(self) async def setup_hook(self): await self.tree.sync() client = MyClient() @client.tree.command(name="send_embed", description="发送Embed消息到指定频道") @appcommands.describe(channel="选择要发送Embed的频道") async def send_embed(interaction: discord.Interaction, channel: discord.TextChannel): # 校验用户在目标频道的发消息权限 if not channel.permissions_for(interaction.user).send_messages: await interaction.response.send_message( f"你在频道 {channel.mention} 没有发送消息的权限,无法执行此命令。", ephemeral=True # 仅当前用户可见该提示 ) return # 构建并发送Embed embed = discord.Embed( title="测试Embed", description="这是一条通过斜杠命令发送的Embed消息", color=discord.Color.blue() ) await channel.send(embed=embed) await interaction.response.send_message( f"Embed已成功发送到频道 {channel.mention}!", ephemeral=True ) client.run("你的Bot令牌")
关键说明
channel.permissions_for(interaction.user).send_messages:直接获取用户在目标频道的发送消息权限状态ephemeral=True:避免无关用户看到权限校验提示,保持频道整洁
二、使用discord.js实现
同样先校验权限,再执行发送逻辑:
const { Client, GatewayIntentBits, SlashCommandBuilder, PermissionsBitField } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages ] }); client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); // 注册斜杠命令 client.application.commands.create( new SlashCommandBuilder() .setName('send_embed') .setDescription('发送Embed消息到指定频道') .addChannelOption(option => option.setName('channel') .setDescription('选择要发送Embed的频道') .setRequired(true) ) ); }); client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'send_embed') { const targetChannel = interaction.options.getChannel('channel'); // 校验用户权限 const hasSendPermission = targetChannel.permissionsFor(interaction.user).has( PermissionsBitField.Flags.SendMessages ); if (!hasSendPermission) { return await interaction.reply({ content: `你在频道 ${targetChannel} 没有发送消息的权限,无法执行此命令。`, ephemeral: true }); } // 构建并发送Embed const embed = { title: '测试Embed', description: '这是一条通过斜杠命令发送的Embed消息', color: 0x0099ff }; await targetChannel.send({ embeds: [embed] }); await interaction.reply({ content: `Embed已成功发送到频道 ${targetChannel}!`, ephemeral: true }); } }); client.login('你的Bot令牌');
关键说明
targetChannel.permissionsFor(interaction.user).has(PermissionsBitField.Flags.SendMessages):精准校验发送消息权限- 全程使用
ephemeral: true返回提示,避免干扰其他用户
内容的提问来源于stack exchange,提问作者Harsh Agrawal
相关产品推荐
相关产品推荐

