如何在Discord Bot的awaitMessages方法中使用多个过滤器?
错误原因
SyntaxError: Identifier 'filter' has already been declared
这个错误是因为const声明的变量不允许在同一个块级作用域内重复定义。你当前使用的switch语句中,所有case默认处于同一作用域,在case0中声明的filter变量会作用于整个switch块,后续case再声明同名filter就会触发报错。
解决方案
最优方案是给每个case添加独立的块级作用域,用大括号{}包裹每个case内的全部代码,这样每个case内声明的变量仅在当前case块内生效,不会和其他case的同名变量冲突,修改后的代码示例如下:
switch (yourCaseVariable) { case 0: { // 开启case0的独立作用域 const LGEmbed0 = new Discord.MessageEmbed() .setTitle("Guess the Level!") .setDescription("Difficulty: Medium") .setColor("#36ff69") .setImage( "https://media.discordapp.net/attachments/891672414361112616/892153208082923520/fever.PNG" ) .setFooter( `Requested by ${message.author.username}`, `https://cdn.discordapp.com/avatars/${message.author.id}/${message.author.avatar}.webp` ) .setTimestamp(); console.log("Answer: Fever"); message.channel.send({ embeds: [LGEmbed0], }); const filter = (m) => m.content.startsWith("Fever"); message.channel .awaitMessages({ filter, max: 1, time: 10000, errors: ["time"] }) .then((collected) => message.channel.send({ embeds: [cor] })) .catch((collected) => message.channel.send({ embeds: [time] })); break; } // 闭合case0的独立作用域 case 1: { // 开启case1的独立作用域 const LGEmbed1 = new Discord.MessageEmbed() .setTitle("Guess the Level!") .setDescription("Difficulty: Harder") .setColor("#ff7d36") .setImage( "https://cdn.discordapp.com/attachments/891672414361112616/892153203465027685/beautiful_vacations.PNG" ) .setFooter(`Requested by ${message.author.username}`) .setTimestamp(); console.log("Answer: Beautiful Vacations"); message.channel.send({ embeds: [LGEmbed1], }); // 可正常声明同名filter,不会和case0的变量冲突 const filter = (m) => m.content.startsWith("Beautiful Vacations"); message.channel .awaitMessages({ filter, max: 1, time: 10000, errors: ["time"] }) .then((collected) => message.channel.send({ embeds: [cor] })) .catch((collected) => message.channel.send({ embeds: [time] })); break; } }
也可以选择给不同case的filter变量起不同名称(比如filter0、filter1),但这种方案代码冗余度更高,不如独立作用域方案简洁。
内容的提问来源于stack exchange,提问作者KontrollFreek
相关产品推荐
相关产品推荐

