【问题标题】:How do I end a emmiter.on within a conditional statement如何在条件语句中结束emitter.on
【发布时间】:2018-02-12 18:17:58
【问题描述】:

现在我正在尝试创建一个 Discord 机器人命令,该命令会忽略特定频道中的特定命令。为了取消忽略频道,用户必须输入命令,然后他们会收到一个提示,告诉他们输入“是/否”,然后响应“是”、“否”,或者如果他们没有输入“是/否”,则告诉他们这样做然后重复。这是我的代码:

if (msg.content === prefix + 'ignore') {
    const guildMember = msg.member;
    const author = msg.author.id;
    if (guildMember.roles.has('309165526427369473')) {
      if (ignoredChannels.has(msg.channel.id)) {
        msg.reply('Would you like to stop ignoring this channel? (Yes/No)');
        client.on('message', msg => {
       /* if (author === msg.author.id) {
            if (msg.content === 'Yes') {
              ignoredChannels.delete(msg.channel.id);
              msg.reply('Channel is now not ignored.');
            }
            else if (msg.content === 'No') {
              msg.reply('Channel is still ignored.');
            }
            else {
              msg.reply('You did not type in the correct arguments. Please type "Yes" or "No".');
            }
          } */
          else {}
        });
      }
      else {
      ignoredChannels.set(msg.channel.id, msg.channel.name);
      msg.reply('Channel is now ignored.');
      }
    }
    else {
      msg.reply('You do not have the permissions to do this.');
    }
  }

在注释代码中,这是每个条件语句所在的位置。我基本上想在每个语句中加上}); 来结束client.on,但当然,这将是不正确的语法。现在我已经尝试在每个条件的末尾使用client.removeAllListeners 删除所有侦听器,但这将禁用我放置在代码中其他位置的其他“消息”侦听器,以接收所有其他命令。我也尝试过放置removeLisener,但这需要特定的侦听器功能,并且“msg”侦听器内置于 discord.js。我也不能使用client.once,因为它在每个条件下都有多个侦听器函数。为什么我需要结束 client.on 是为了阻止机器人多次响应用户所需的输入(只需要一次),永远不会结束发射器。

【问题讨论】:

  • 请正确缩进您的代码。这是你能做的最起码的事情。为了您自己的理解,以及所有其他阅读您的代码的人。
  • 首先,你应该更好地设计你的程序......“结束一个函数”的问题应该不难......用最小的设计。为什么不添加退货;结束函数?
  • 我更新了缩进 @Tomalak ,这只是由复制/粘贴引起的。
  • @Adriani6 ,什么功能?

标签: javascript node.js discord discord.js


【解决方案1】:

您不应仅仅为了收到一条确认消息而添加新事件client.on('message')
您应该改用.awaitMessages()。示例:

// Await !vote messages
const filter = m => m.content.startsWith('!vote');
// Errors: ['time'] treats ending because of the time limit as an error
channel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })
  .then(collected => console.log(collected.size))
  .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));

从文档中复制

您可以通过将响应添加到过滤器来过滤“允许”谁来确认响应。

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多