首页 > 解决方案 > 如何在 discord.js 中创建交互式命令

问题描述

我想知道如何在 discord.js 中制作像赠品机器人这样的交互式赠品命令

我在 V11/12 例如当我做 g!giveaway start 时,它会启动一个交互式设置,它将像这样工作

机器人会说“时间”

然后我使用变量设置它将持续的类型(m 代表分钟,d 代表天,w 代表几周)

然后会说

“好!现在你要送什么?”

然后我就说我想送什么

然后它会说

“太好了!赠品将在哪个频道?”

然后我把频道

然后机器人说

“好!(奖品)的赠品已在(频道)开始,并将持续(时间)秒/天/周

请问这里能不能帮帮我,谢谢!

标签: node.jsdiscord.js

解决方案


使用收集器(awaitMessages)发送消息并等待响应

询问后我们会希望等待消息,因此我们将使用收集器。

异步TextChannel.awaitMessages()阅读文档)可用于收集消息。它需要一个过滤器来知道要接受哪些消息,以及一些选项来知道何时停止收集。

// accepted messages will be those from the same author, we compare IDs to make sure
const filter = msg => msg.author.id == message.author.id;

// the only option needed will be maxMatches, to only take one message before ending the collector
const options = {
  maxMatches: 1
};

然后收集器将返回一个消息集合.first(),因为只有一个,我们将始终接收,并存储其内容。

// assuming you have the `channel` object, and are inside an async function
let collector = await channel.awaitMessages(filter, options);
let answer = collector.first().content;

channel.send()对于您从用户那里看到的每个不同的答案,请在每次之后使用上述内容。

收集器使用示例

client.on("message", async message => {
  if (message.content === "!color") {
    // request
    message.channel.send("What's your fav color?");

    // collector
    let collector = await message.channel.awaitMessages(filter, options);
    let answer = collector.first().content;

    // response
    await message.reply("your fav color is " + answer + "!");
  }
});

请注意,这只是一个示例,在实际实现中,您必须正确处理错误。这是示例结果:

颜色命令示例

如果您需要更多输入,只需创建更多收集器和答案,然后根据需要处理这些信息。


推荐阅读