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

如何使用Node.js在Discord自机器人中触发斜杠命令?

解决Discord自bot无法触发斜杠命令的问题

直接发送/minesweeper文本只会生成普通消息,不会触发斜杠命令的执行——因为斜杠命令需要通过Discord的应用命令交互接口调用,而非发送文本内容。以下是修正后的实现方案:

核心修正思路

使用discord.js-selfbot-v13提供的sendCommand方法,直接调用应用命令接口,而非发送文本消息。

修正后的代码

const { Client } = require('discord.js-selfbot-v13');
const client = new Client();
const channelId = '1211807309307580430';

client.on('ready', async () => {
    console.log(`${client.user.username} is ready!`);

    const channel = client.channels.cache.get(channelId);
    if (!channel) return console.error('目标频道不存在');

    try {
        // 通过命令名称直接触发斜杠命令
        await channel.sendCommand('minesweeper');
        console.log('扫雷命令已成功触发');
    } catch (error) {
        console.error('触发命令失败:', error);
    }
});

client.login('你的Discord Token');

备选方案(若直接用名称失败)

如果服务器中有重名命令,可先获取命令对象再触发:

client.on('ready', async () => {
    console.log(`${client.user.username} is ready!`);

    const channel = client.channels.cache.get(channelId);
    if (!channel) return console.error('目标频道不存在');
    if (!channel.guild) return console.error('该频道不属于服务器');

    try {
        // 获取服务器内所有可用应用命令
        const guildCommands = await channel.guild.commands.fetch();
        // 筛选出扫雷命令
        const minesweeperCmd = guildCommands.find(cmd => cmd.name === 'minesweeper');
        
        if (!minesweeperCmd) return console.error('服务器内未找到扫雷命令');
        
        // 触发命令
        await channel.sendCommand(minesweeperCmd);
        console.log('扫雷命令已成功触发');
    } catch (error) {
        console.error('触发命令失败:', error);
    }
});

注意事项

  • 确保自bot账号有权限在目标频道使用该斜杠命令
  • 自bot行为可能违反Discord服务条款,使用前请谨慎评估风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:07:35