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

如何让Discord机器人接收临时指令并转发内容到指定/随机频道?

问题解答

一、核心功能实现(临时回复+随机频道转发)

你的需求完全可以通过Discord.js原生API实现,不需要额外的集合存储方案,具体修改如下:

  1. 添加临时回复:在execute函数开头调用interaction.reply并设置ephemeral: true,就能生成仅指令发起者可见的临时消息:
await interaction.reply({ content: '内容已转发至目标频道', ephemeral: true });
  1. 补全随机频道逻辑:你的代码里缺少getRandomInt函数的定义,同时需要给channels数组填充有效的频道ID,完整代码示例:
// 定义随机数生成函数
function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

// 填入需要转发的目标频道ID
const channels = ['频道ID1', '频道ID2', '频道ID3']; // 替换为实际频道ID

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('mainframe')
        .setDescription('bot will post to the mainframe for you.')
        .addStringOption(option =>
            option.setName('post')
                .setDescription('What you would like posted.')
                .setRequired(true)),

    async execute(interaction) {
        const post = interaction.options.getString('post');
        let response = `"${post}".`;

        // 发送仅发起者可见的临时回复
        await interaction.reply({ content: '内容已成功转发', ephemeral: true });

        // 随机选择目标频道发送内容
        const targetChannelId = channels[getRandomInt(channels.length)];
        const targetChannel = interaction.guild.channels.cache.get(targetChannelId);
        
        if (targetChannel) {
            await targetChannel.send({ content: response });
        } else {
            // 可选:频道不存在时给发起者补发临时提示
            await interaction.followUp({ content: '目标频道不存在,转发失败', ephemeral: true });
        }
    },
};

二、关于Reddit提到的集合存储方案

这个方案可行但没必要:

  • 可行原因:确实可以把用户输入的内容(或对应的URL)存入集合(比如Map或数组),之后再让机器人从集合中取出内容发送到指定频道,适合需要延迟发送、批量处理的场景。
  • 没必要的原因:你的需求是即时转发,直接拿到用户输入后立刻发送即可,额外的集合存储反而增加复杂度,完全可以用原生API一步完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:50:21